id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_2901_0
/* radare - LGPL - Copyright 2008-2017 - nibble, pancake, alvaro_fe */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <r_types.h> #include <r_util.h> #include "elf.h" #ifdef IFDBG #undef IFDBG #endif #define DO_THE_DBG 0 #define IFDBG if (DO_THE_DBG) #define IFINT if (0) #define ELF_PAGE_MASK 0xFFFFFFFFFFFFF000LL #define ELF_PAGE_SIZE 12 #define R_ELF_NO_RELRO 0 #define R_ELF_PART_RELRO 1 #define R_ELF_FULL_RELRO 2 #define bprintf if(bin->verbose)eprintf #define READ8(x, i) r_read_ble8(x + i); i += 1; #define READ16(x, i) r_read_ble16(x + i, bin->endian); i += 2; #define READ32(x, i) r_read_ble32(x + i, bin->endian); i += 4; #define READ64(x, i) r_read_ble64(x + i, bin->endian); i += 8; #define GROWTH_FACTOR (1.5) static inline int __strnlen(const char *str, int len) { int l = 0; while (IS_PRINTABLE (*str) && --len) { if (((ut8)*str) == 0xff) { break; } str++; l++; } return l + 1; } static int handle_e_ident(ELFOBJ *bin) { return !strncmp ((char *)bin->ehdr.e_ident, ELFMAG, SELFMAG) || !strncmp ((char *)bin->ehdr.e_ident, CGCMAG, SCGCMAG); } static int init_ehdr(ELFOBJ *bin) { ut8 e_ident[EI_NIDENT]; ut8 ehdr[sizeof (Elf_(Ehdr))] = {0}; int i, len; if (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) { bprintf ("Warning: read (magic)\n"); return false; } sdb_set (bin->kv, "elf_type.cparse", "enum elf_type { ET_NONE=0, ET_REL=1," " ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff," " ET_LOPROC=0xff00, ET_HIPROC=0xffff };", 0); sdb_set (bin->kv, "elf_machine.cparse", "enum elf_machine{EM_NONE=0, EM_M32=1," " EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_486=6, " " EM_860=7, EM_MIPS=8, EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11," " EM_UNKNOWN12=12, EM_UNKNOWN13=13, EM_UNKNOWN14=14, " " EM_PA_RISC=15, EM_PARISC=EM_PA_RISC, EM_nCUBE=16, EM_VPP500=17," " EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, " " EM_S390=22, EM_UNKNOWN22=EM_S390, EM_UNKNOWN23=23, EM_UNKNOWN24=24," " EM_UNKNOWN25=25, EM_UNKNOWN26=26, EM_UNKNOWN27=27, EM_UNKNOWN28=28," " EM_UNKNOWN29=29, EM_UNKNOWN30=30, EM_UNKNOWN31=31, EM_UNKNOWN32=32," " EM_UNKNOWN33=33, EM_UNKNOWN34=34, EM_UNKNOWN35=35, EM_V800=36," " EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40, EM_ALPHA=41, EM_SH=42," " EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46, EM_H8_300H=47," " EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51, EM_COLDFIRE=52," " EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57," " EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_AMD64=62," " EM_X86_64=EM_AMD64, EM_PDSP=63, EM_UNKNOWN64=64, EM_UNKNOWN65=65," " EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69, EM_68HC11=70," " EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75, " " EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80," " EM_HUANY=81, EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86," " EM_V850=87, EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91," " EM_OPENRISC=92, EM_ARC_A5=93, EM_XTENSA=94, EM_NUM=95};", 0); sdb_num_set (bin->kv, "elf_header.offset", 0, 0); sdb_num_set (bin->kv, "elf_header.size", sizeof (Elf_(Ehdr)), 0); #if R_BIN_ELF64 sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exqqqxwwwwww" " ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize" " phentsize phnum shentsize shnum shstrndx", 0); #else sdb_set (bin->kv, "elf_header.format", "[16]z[2]E[2]Exxxxxwwwwww" " ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize" " phentsize phnum shentsize shnum shstrndx", 0); #endif bin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0; memset (&bin->ehdr, 0, sizeof (Elf_(Ehdr))); len = r_buf_read_at (bin->b, 0, ehdr, sizeof (Elf_(Ehdr))); if (len < 1) { bprintf ("Warning: read (ehdr)\n"); return false; } memcpy (&bin->ehdr.e_ident, ehdr, 16); i = 16; bin->ehdr.e_type = READ16 (ehdr, i) bin->ehdr.e_machine = READ16 (ehdr, i) bin->ehdr.e_version = READ32 (ehdr, i) #if R_BIN_ELF64 bin->ehdr.e_entry = READ64 (ehdr, i) bin->ehdr.e_phoff = READ64 (ehdr, i) bin->ehdr.e_shoff = READ64 (ehdr, i) #else bin->ehdr.e_entry = READ32 (ehdr, i) bin->ehdr.e_phoff = READ32 (ehdr, i) bin->ehdr.e_shoff = READ32 (ehdr, i) #endif bin->ehdr.e_flags = READ32 (ehdr, i) bin->ehdr.e_ehsize = READ16 (ehdr, i) bin->ehdr.e_phentsize = READ16 (ehdr, i) bin->ehdr.e_phnum = READ16 (ehdr, i) bin->ehdr.e_shentsize = READ16 (ehdr, i) bin->ehdr.e_shnum = READ16 (ehdr, i) bin->ehdr.e_shstrndx = READ16 (ehdr, i) return handle_e_ident (bin); // Usage example: // > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse` // > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset` } static int init_phdr(ELFOBJ *bin) { ut32 phdr_size; ut8 phdr[sizeof (Elf_(Phdr))] = {0}; int i, j, len; if (!bin->ehdr.e_phnum) { return false; } if (bin->phdr) { return true; } if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) { return false; } if (!phdr_size) { return false; } if (phdr_size > bin->size) { return false; } if (phdr_size > (ut32)bin->size) { return false; } if (bin->ehdr.e_phoff > bin->size) { return false; } if (bin->ehdr.e_phoff + phdr_size > bin->size) { return false; } if (!(bin->phdr = calloc (phdr_size, 1))) { perror ("malloc (phdr)"); return false; } for (i = 0; i < bin->ehdr.e_phnum; i++) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr))); if (len < 1) { bprintf ("Warning: read (phdr)\n"); R_FREE (bin->phdr); return false; } bin->phdr[i].p_type = READ32 (phdr, j) #if R_BIN_ELF64 bin->phdr[i].p_flags = READ32 (phdr, j) bin->phdr[i].p_offset = READ64 (phdr, j) bin->phdr[i].p_vaddr = READ64 (phdr, j) bin->phdr[i].p_paddr = READ64 (phdr, j) bin->phdr[i].p_filesz = READ64 (phdr, j) bin->phdr[i].p_memsz = READ64 (phdr, j) bin->phdr[i].p_align = READ64 (phdr, j) #else bin->phdr[i].p_offset = READ32 (phdr, j) bin->phdr[i].p_vaddr = READ32 (phdr, j) bin->phdr[i].p_paddr = READ32 (phdr, j) bin->phdr[i].p_filesz = READ32 (phdr, j) bin->phdr[i].p_memsz = READ32 (phdr, j) bin->phdr[i].p_flags = READ32 (phdr, j) bin->phdr[i].p_align = READ32 (phdr, j) #endif } sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0); sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0); sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2," "PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000," "PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0); sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1," "PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6," "PF_Read_Write_Exec=7};", 0); #if R_BIN_ELF64 sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags" " offset vaddr paddr filesz memsz align", 0); #else sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr" " filesz memsz (elf_p_flags)flags align", 0); #endif return true; // Usage example: // > td `k bin/cur/info/elf_p_type.cparse`; td `k bin/cur/info/elf_p_flags.cparse` // > pf `k bin/cur/info/elf_phdr.format` @ `k bin/cur/info/elf_phdr.offset` } static int init_shdr(ELFOBJ *bin) { ut32 shdr_size; ut8 shdr[sizeof (Elf_(Shdr))] = {0}; int i, j, len; if (!bin || bin->shdr) { return true; } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size < 1) { return false; } if (shdr_size > bin->size) { return false; } if (bin->ehdr.e_shoff > bin->size) { return false; } if (bin->ehdr.e_shoff + shdr_size > bin->size) { return false; } if (!(bin->shdr = calloc (1, shdr_size + 1))) { perror ("malloc (shdr)"); return false; } sdb_num_set (bin->kv, "elf_shdr.offset", bin->ehdr.e_shoff, 0); sdb_num_set (bin->kv, "elf_shdr.size", sizeof (Elf_(Shdr)), 0); sdb_set (bin->kv, "elf_s_type.cparse", "enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1," "SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7," "SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000," "SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};", 0); for (i = 0; i < bin->ehdr.e_shnum; i++) { j = 0; len = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr))); if (len < 1) { bprintf ("Warning: read (shdr) at 0x%"PFMT64x"\n", (ut64) bin->ehdr.e_shoff); R_FREE (bin->shdr); return false; } bin->shdr[i].sh_name = READ32 (shdr, j) bin->shdr[i].sh_type = READ32 (shdr, j) #if R_BIN_ELF64 bin->shdr[i].sh_flags = READ64 (shdr, j) bin->shdr[i].sh_addr = READ64 (shdr, j) bin->shdr[i].sh_offset = READ64 (shdr, j) bin->shdr[i].sh_size = READ64 (shdr, j) bin->shdr[i].sh_link = READ32 (shdr, j) bin->shdr[i].sh_info = READ32 (shdr, j) bin->shdr[i].sh_addralign = READ64 (shdr, j) bin->shdr[i].sh_entsize = READ64 (shdr, j) #else bin->shdr[i].sh_flags = READ32 (shdr, j) bin->shdr[i].sh_addr = READ32 (shdr, j) bin->shdr[i].sh_offset = READ32 (shdr, j) bin->shdr[i].sh_size = READ32 (shdr, j) bin->shdr[i].sh_link = READ32 (shdr, j) bin->shdr[i].sh_info = READ32 (shdr, j) bin->shdr[i].sh_addralign = READ32 (shdr, j) bin->shdr[i].sh_entsize = READ32 (shdr, j) #endif } #if R_BIN_ELF64 sdb_set (bin->kv, "elf_s_flags_64.cparse", "enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1," "SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5," "SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};", 0); sdb_set (bin->kv, "elf_shdr.format", "x[4]E[8]Eqqqxxqq name (elf_s_type)type" " (elf_s_flags_64)flags addr offset size link info addralign entsize", 0); #else sdb_set (bin->kv, "elf_s_flags_32.cparse", "enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1," "SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5," "SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};", 0); sdb_set (bin->kv, "elf_shdr.format", "x[4]E[4]Exxxxxxx name (elf_s_type)type" " (elf_s_flags_32)flags addr offset size link info addralign entsize", 0); #endif return true; // Usage example: // > td `k bin/cur/info/elf_s_type.cparse`; td `k bin/cur/info/elf_s_flags_64.cparse` // > pf `k bin/cur/info/elf_shdr.format` @ `k bin/cur/info/elf_shdr.offset` } static int init_strtab(ELFOBJ *bin) { if (bin->strtab || !bin->shdr) { return false; } if (bin->ehdr.e_shstrndx != SHN_UNDEF && (bin->ehdr.e_shstrndx >= bin->ehdr.e_shnum || (bin->ehdr.e_shstrndx >= SHN_LORESERVE && bin->ehdr.e_shstrndx < SHN_HIRESERVE))) return false; /* sh_size must be lower than UT32_MAX and not equal to zero, to avoid bugs on malloc() */ if (bin->shdr[bin->ehdr.e_shstrndx].sh_size > UT32_MAX) { return false; } if (!bin->shdr[bin->ehdr.e_shstrndx].sh_size) { return false; } bin->shstrtab_section = bin->strtab_section = &bin->shdr[bin->ehdr.e_shstrndx]; bin->shstrtab_size = bin->strtab_section->sh_size; if (bin->shstrtab_size > bin->size) { return false; } if (!(bin->shstrtab = calloc (1, bin->shstrtab_size + 1))) { perror ("malloc"); bin->shstrtab = NULL; return false; } if (bin->shstrtab_section->sh_offset > bin->size) { R_FREE (bin->shstrtab); return false; } if (bin->shstrtab_section->sh_offset + bin->shstrtab_section->sh_size > bin->size) { R_FREE (bin->shstrtab); return false; } if (r_buf_read_at (bin->b, bin->shstrtab_section->sh_offset, (ut8*)bin->shstrtab, bin->shstrtab_section->sh_size + 1) < 1) { bprintf ("Warning: read (shstrtab) at 0x%"PFMT64x"\n", (ut64) bin->shstrtab_section->sh_offset); R_FREE (bin->shstrtab); return false; } bin->shstrtab[bin->shstrtab_section->sh_size] = '\0'; sdb_num_set (bin->kv, "elf_shstrtab.offset", bin->shstrtab_section->sh_offset, 0); sdb_num_set (bin->kv, "elf_shstrtab.size", bin->shstrtab_section->sh_size, 0); return true; } static int init_dynamic_section(struct Elf_(r_bin_elf_obj_t) *bin) { Elf_(Dyn) *dyn = NULL; Elf_(Dyn) d = {0}; Elf_(Addr) strtabaddr = 0; ut64 offset = 0; char *strtab = NULL; size_t relentry = 0, strsize = 0; int entries; int i, j, len, r; ut8 sdyn[sizeof (Elf_(Dyn))] = {0}; ut32 dyn_size = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) { return false; } for (i = 0; i < bin->ehdr.e_phnum ; i++) { if (bin->phdr[i].p_type == PT_DYNAMIC) { dyn_size = bin->phdr[i].p_filesz; break; } } if (i == bin->ehdr.e_phnum) { return false; } if (bin->phdr[i].p_filesz > bin->size) { return false; } if (bin->phdr[i].p_offset > bin->size) { return false; } if (bin->phdr[i].p_offset + sizeof(Elf_(Dyn)) > bin->size) { return false; } for (entries = 0; entries < (dyn_size / sizeof (Elf_(Dyn))); entries++) { j = 0; len = r_buf_read_at (bin->b, bin->phdr[i].p_offset + entries * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn))); if (len < 1) { goto beach; } #if R_BIN_ELF64 d.d_tag = READ64 (sdyn, j) #else d.d_tag = READ32 (sdyn, j) #endif if (d.d_tag == DT_NULL) { break; } } if (entries < 1) { return false; } dyn = (Elf_(Dyn)*)calloc (entries, sizeof (Elf_(Dyn))); if (!dyn) { return false; } if (!UT32_MUL (&dyn_size, entries, sizeof (Elf_(Dyn)))) { goto beach; } if (!dyn_size) { goto beach; } offset = Elf_(r_bin_elf_v2p) (bin, bin->phdr[i].p_vaddr); if (offset > bin->size || offset + dyn_size > bin->size) { goto beach; } for (i = 0; i < entries; i++) { j = 0; r_buf_read_at (bin->b, offset + i * sizeof (Elf_(Dyn)), sdyn, sizeof (Elf_(Dyn))); if (len < 1) { bprintf("Warning: read (dyn)\n"); } #if R_BIN_ELF64 dyn[i].d_tag = READ64 (sdyn, j) dyn[i].d_un.d_ptr = READ64 (sdyn, j) #else dyn[i].d_tag = READ32 (sdyn, j) dyn[i].d_un.d_ptr = READ32 (sdyn, j) #endif switch (dyn[i].d_tag) { case DT_STRTAB: strtabaddr = Elf_(r_bin_elf_v2p) (bin, dyn[i].d_un.d_ptr); break; case DT_STRSZ: strsize = dyn[i].d_un.d_val; break; case DT_PLTREL: bin->is_rela = dyn[i].d_un.d_val; break; case DT_RELAENT: relentry = dyn[i].d_un.d_val; break; default: if ((dyn[i].d_tag >= DT_VERSYM) && (dyn[i].d_tag <= DT_VERNEEDNUM)) { bin->version_info[DT_VERSIONTAGIDX (dyn[i].d_tag)] = dyn[i].d_un.d_val; } break; } } if (!bin->is_rela) { bin->is_rela = sizeof (Elf_(Rela)) == relentry? DT_RELA : DT_REL; } if (!strtabaddr || strtabaddr > bin->size || strsize > ST32_MAX || !strsize || strsize > bin->size) { if (!strtabaddr) { bprintf ("Warning: section.shstrtab not found or invalid\n"); } goto beach; } strtab = (char *)calloc (1, strsize + 1); if (!strtab) { goto beach; } if (strtabaddr + strsize > bin->size) { free (strtab); goto beach; } r = r_buf_read_at (bin->b, strtabaddr, (ut8 *)strtab, strsize); if (r < 1) { free (strtab); goto beach; } bin->dyn_buf = dyn; bin->dyn_entries = entries; bin->strtab = strtab; bin->strtab_size = strsize; r = Elf_(r_bin_elf_has_relro)(bin); switch (r) { case R_ELF_FULL_RELRO: sdb_set (bin->kv, "elf.relro", "full", 0); break; case R_ELF_PART_RELRO: sdb_set (bin->kv, "elf.relro", "partial", 0); break; default: sdb_set (bin->kv, "elf.relro", "no", 0); break; } sdb_num_set (bin->kv, "elf_strtab.offset", strtabaddr, 0); sdb_num_set (bin->kv, "elf_strtab.size", strsize, 0); return true; beach: free (dyn); return false; } static RBinElfSection* get_section_by_name(ELFOBJ *bin, const char *section_name) { int i; if (!bin->g_sections) { return NULL; } for (i = 0; !bin->g_sections[i].last; i++) { if (!strncmp (bin->g_sections[i].name, section_name, ELF_STRING_LENGTH-1)) { return &bin->g_sections[i]; } } return NULL; } static char *get_ver_flags(ut32 flags) { static char buff[32]; buff[0] = 0; if (!flags) { return "none"; } if (flags & VER_FLG_BASE) { strcpy (buff, "BASE "); } if (flags & VER_FLG_WEAK) { if (flags & VER_FLG_BASE) { strcat (buff, "| "); } strcat (buff, "WEAK "); } if (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)) { strcat (buff, "| <unknown>"); } return buff; } static Sdb *store_versioninfo_gnu_versym(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { int i; const ut64 num_entries = sz / sizeof (Elf_(Versym)); const char *section_name = ""; const char *link_section_name = ""; Elf_(Shdr) *link_shdr = NULL; Sdb *sdb = sdb_new0(); if (!sdb) { return NULL; } if (!bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]) { sdb_free (sdb); return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { sdb_free (sdb); return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; ut8 *edata = (ut8*) calloc (R_MAX (1, num_entries), sizeof (ut16)); if (!edata) { sdb_free (sdb); return NULL; } ut16 *data = (ut16*) calloc (R_MAX (1, num_entries), sizeof (ut16)); if (!data) { free (edata); sdb_free (sdb); return NULL; } ut64 off = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERSYM)]); if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } r_buf_read_at (bin->b, off, edata, sizeof (ut16) * num_entries); sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", num_entries, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (i = num_entries; i--;) { data[i] = r_read_ble16 (&edata[i * sizeof (ut16)], bin->endian); } R_FREE (edata); for (i = 0; i < num_entries; i += 4) { int j; int check_def; char key[32] = {0}; Sdb *sdb_entry = sdb_new0 (); snprintf (key, sizeof (key), "entry%d", i / 4); sdb_ns_set (sdb, key, sdb_entry); sdb_num_set (sdb_entry, "idx", i, 0); for (j = 0; (j < 4) && (i + j) < num_entries; ++j) { int k; char *tmp_val = NULL; snprintf (key, sizeof (key), "value%d", j); switch (data[i + j]) { case 0: sdb_set (sdb_entry, key, "0 (*local*)", 0); break; case 1: sdb_set (sdb_entry, key, "1 (*global*)", 0); break; default: tmp_val = sdb_fmt (0, "%x ", data[i+j] & 0x7FFF); check_def = true; if (bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]) { Elf_(Verneed) vn; ut8 svn[sizeof (Elf_(Verneed))] = {0}; ut64 offset = Elf_(r_bin_elf_v2p) (bin, bin->version_info[DT_VERSIONTAGIDX (DT_VERNEED)]); do { Elf_(Vernaux) vna; ut8 svna[sizeof (Elf_(Vernaux))] = {0}; ut64 a_off; if (offset > bin->size || offset + sizeof (vn) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, offset, svn, sizeof (svn)) < 0) { bprintf ("Warning: Cannot read Verneed for Versym\n"); goto beach; } k = 0; vn.vn_version = READ16 (svn, k) vn.vn_cnt = READ16 (svn, k) vn.vn_file = READ32 (svn, k) vn.vn_aux = READ32 (svn, k) vn.vn_next = READ32 (svn, k) a_off = offset + vn.vn_aux; do { if (a_off > bin->size || a_off + sizeof (vna) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, a_off, svna, sizeof (svna)) < 0) { bprintf ("Warning: Cannot read Vernaux for Versym\n"); goto beach; } k = 0; vna.vna_hash = READ32 (svna, k) vna.vna_flags = READ16 (svna, k) vna.vna_other = READ16 (svna, k) vna.vna_name = READ32 (svna, k) vna.vna_next = READ32 (svna, k) a_off += vna.vna_next; } while (vna.vna_other != data[i + j] && vna.vna_next != 0); if (vna.vna_other == data[i + j]) { if (vna.vna_name > bin->strtab_size) { goto beach; } sdb_set (sdb_entry, key, sdb_fmt (0, "%s(%s)", tmp_val, bin->strtab + vna.vna_name), 0); check_def = false; break; } offset += vn.vn_next; } while (vn.vn_next); } ut64 vinfoaddr = bin->version_info[DT_VERSIONTAGIDX (DT_VERDEF)]; if (check_def && data[i + j] != 0x8001 && vinfoaddr) { Elf_(Verdef) vd; ut8 svd[sizeof (Elf_(Verdef))] = {0}; ut64 offset = Elf_(r_bin_elf_v2p) (bin, vinfoaddr); if (offset > bin->size || offset + sizeof (vd) > bin->size) { goto beach; } do { if (r_buf_read_at (bin->b, offset, svd, sizeof (svd)) < 0) { bprintf ("Warning: Cannot read Verdef for Versym\n"); goto beach; } k = 0; vd.vd_version = READ16 (svd, k) vd.vd_flags = READ16 (svd, k) vd.vd_ndx = READ16 (svd, k) vd.vd_cnt = READ16 (svd, k) vd.vd_hash = READ32 (svd, k) vd.vd_aux = READ32 (svd, k) vd.vd_next = READ32 (svd, k) offset += vd.vd_next; } while (vd.vd_ndx != (data[i + j] & 0x7FFF) && vd.vd_next != 0); if (vd.vd_ndx == (data[i + j] & 0x7FFF)) { Elf_(Verdaux) vda; ut8 svda[sizeof (Elf_(Verdaux))] = {0}; ut64 off_vda = offset - vd.vd_next + vd.vd_aux; if (off_vda > bin->size || off_vda + sizeof (vda) > bin->size) { goto beach; } if (r_buf_read_at (bin->b, off_vda, svda, sizeof (svda)) < 0) { bprintf ("Warning: Cannot read Verdaux for Versym\n"); goto beach; } k = 0; vda.vda_name = READ32 (svda, k) vda.vda_next = READ32 (svda, k) if (vda.vda_name > bin->strtab_size) { goto beach; } const char *name = bin->strtab + vda.vda_name; sdb_set (sdb_entry, key, sdb_fmt (0,"%s(%s%-*s)", tmp_val, name, (int)(12 - strlen (name)),")") , 0); } } } } } beach: free (data); return sdb; } static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = ""; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = ""; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0); sdb_num_set (sdb_version, "idx", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, "file_name", s, 0); free (s); } sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0); st32 vnaux = entry->vn_aux; if (vnaux < 1) { goto beach; } vstart += vnaux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, "idx", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, "name", name, 0); } sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), "vernaux%d", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf ("Invalid vn_next\n"); break; } i += entry->vn_next; snprintf (key, sizeof (key), "version%d", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; } static Sdb *store_versioninfo(ELFOBJ *bin) { Sdb *sdb_versioninfo = NULL; int num_verdef = 0; int num_verneed = 0; int num_versym = 0; int i; if (!bin || !bin->shdr) { return NULL; } if (!(sdb_versioninfo = sdb_new0 ())) { return NULL; } for (i = 0; i < bin->ehdr.e_shnum; i++) { Sdb *sdb = NULL; char key[32] = {0}; int size = bin->shdr[i].sh_size; if (size - (i*sizeof(Elf_(Shdr)) > bin->size)) { size = bin->size - (i*sizeof(Elf_(Shdr))); } int left = size - (i * sizeof (Elf_(Shdr))); left = R_MIN (left, bin->shdr[i].sh_size); if (left < 0) { break; } switch (bin->shdr[i].sh_type) { case SHT_GNU_verdef: sdb = store_versioninfo_gnu_verdef (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "verdef%d", num_verdef++); sdb_ns_set (sdb_versioninfo, key, sdb); break; case SHT_GNU_verneed: sdb = store_versioninfo_gnu_verneed (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "verneed%d", num_verneed++); sdb_ns_set (sdb_versioninfo, key, sdb); break; case SHT_GNU_versym: sdb = store_versioninfo_gnu_versym (bin, &bin->shdr[i], left); snprintf (key, sizeof (key), "versym%d", num_versym++); sdb_ns_set (sdb_versioninfo, key, sdb); break; } } return sdb_versioninfo; } static bool init_dynstr(ELFOBJ *bin) { int i, r; const char *section_name = NULL; if (!bin || !bin->shdr) { return false; } if (!bin->shstrtab) { return false; } for (i = 0; i < bin->ehdr.e_shnum; ++i) { if (bin->shdr[i].sh_name > bin->shstrtab_size) { return false; } section_name = &bin->shstrtab[bin->shdr[i].sh_name]; if (bin->shdr[i].sh_type == SHT_STRTAB && !strcmp (section_name, ".dynstr")) { if (!(bin->dynstr = (char*) calloc (bin->shdr[i].sh_size + 1, sizeof (char)))) { bprintf("Warning: Cannot allocate memory for dynamic strings\n"); return false; } if (bin->shdr[i].sh_offset > bin->size) { return false; } if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size > bin->size) { return false; } if (bin->shdr[i].sh_offset + bin->shdr[i].sh_size < bin->shdr[i].sh_size) { return false; } r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset, (ut8*)bin->dynstr, bin->shdr[i].sh_size); if (r < 1) { R_FREE (bin->dynstr); bin->dynstr_size = 0; return false; } bin->dynstr_size = bin->shdr[i].sh_size; return true; } } return false; } static int elf_init(ELFOBJ *bin) { bin->phdr = NULL; bin->shdr = NULL; bin->strtab = NULL; bin->shstrtab = NULL; bin->strtab_size = 0; bin->strtab_section = NULL; bin->dyn_buf = NULL; bin->dynstr = NULL; ZERO_FILL (bin->version_info); bin->g_sections = NULL; bin->g_symbols = NULL; bin->g_imports = NULL; /* bin is not an ELF */ if (!init_ehdr (bin)) { return false; } if (!init_phdr (bin)) { bprintf ("Warning: Cannot initialize program headers\n"); } if (!init_shdr (bin)) { bprintf ("Warning: Cannot initialize section headers\n"); } if (!init_strtab (bin)) { bprintf ("Warning: Cannot initialize strings table\n"); } if (!init_dynstr (bin)) { bprintf ("Warning: Cannot initialize dynamic strings\n"); } bin->baddr = Elf_(r_bin_elf_get_baddr) (bin); if (!init_dynamic_section (bin) && !Elf_(r_bin_elf_get_static)(bin)) bprintf ("Warning: Cannot initialize dynamic section\n"); bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; bin->symbols_by_ord_size = 0; bin->symbols_by_ord = NULL; bin->g_sections = Elf_(r_bin_elf_get_sections) (bin); bin->boffset = Elf_(r_bin_elf_get_boffset) (bin); sdb_ns_set (bin->kv, "versioninfo", store_versioninfo (bin)); return true; } ut64 Elf_(r_bin_elf_get_section_offset)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); if (!section) return UT64_MAX; return section->offset; } ut64 Elf_(r_bin_elf_get_section_addr)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); return section? section->rva: UT64_MAX; } ut64 Elf_(r_bin_elf_get_section_addr_end)(ELFOBJ *bin, const char *section_name) { RBinElfSection *section = get_section_by_name (bin, section_name); return section? section->rva + section->size: UT64_MAX; } #define REL (is_rela ? (void*)rela : (void*)rel) #define REL_BUF is_rela ? (ut8*)(&rela[k]) : (ut8*)(&rel[k]) #define REL_OFFSET is_rela ? rela[k].r_offset : rel[k].r_offset #define REL_TYPE is_rela ? rela[k].r_info : rel[k].r_info static ut64 get_import_addr(ELFOBJ *bin, int sym) { Elf_(Rel) *rel = NULL; Elf_(Rela) *rela = NULL; ut8 rl[sizeof (Elf_(Rel))] = {0}; ut8 rla[sizeof (Elf_(Rela))] = {0}; RBinElfSection *rel_sec = NULL; Elf_(Addr) plt_sym_addr = -1; ut64 got_addr, got_offset; ut64 plt_addr; int j, k, tsize, len, nrel; bool is_rela = false; const char *rel_sect[] = { ".rel.plt", ".rela.plt", ".rel.dyn", ".rela.dyn", NULL }; const char *rela_sect[] = { ".rela.plt", ".rel.plt", ".rela.dyn", ".rel.dyn", NULL }; if ((!bin->shdr || !bin->strtab) && !bin->phdr) { return -1; } if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) == -1 && (got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) == -1) { return -1; } if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1 && (got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt")) == -1) { return -1; } if (bin->is_rela == DT_REL) { j = 0; while (!rel_sec && rel_sect[j]) { rel_sec = get_section_by_name (bin, rel_sect[j++]); } tsize = sizeof (Elf_(Rel)); } else if (bin->is_rela == DT_RELA) { j = 0; while (!rel_sec && rela_sect[j]) { rel_sec = get_section_by_name (bin, rela_sect[j++]); } is_rela = true; tsize = sizeof (Elf_(Rela)); } if (!rel_sec) { return -1; } if (rel_sec->size < 1) { return -1; } nrel = (ut32)((int)rel_sec->size / (int)tsize); if (nrel < 1) { return -1; } if (is_rela) { rela = calloc (nrel, tsize); if (!rela) { return -1; } } else { rel = calloc (nrel, tsize); if (!rel) { return -1; } } for (j = k = 0; j < rel_sec->size && k < nrel; j += tsize, k++) { int l = 0; if (rel_sec->offset + j > bin->size) { goto out; } if (rel_sec->offset + j + tsize > bin->size) { goto out; } len = r_buf_read_at ( bin->b, rel_sec->offset + j, is_rela ? rla : rl, is_rela ? sizeof (Elf_ (Rela)) : sizeof (Elf_ (Rel))); if (len < 1) { goto out; } #if R_BIN_ELF64 if (is_rela) { rela[k].r_offset = READ64 (rla, l) rela[k].r_info = READ64 (rla, l) rela[k].r_addend = READ64 (rla, l) } else { rel[k].r_offset = READ64 (rl, l) rel[k].r_info = READ64 (rl, l) } #else if (is_rela) { rela[k].r_offset = READ32 (rla, l) rela[k].r_info = READ32 (rla, l) rela[k].r_addend = READ32 (rla, l) } else { rel[k].r_offset = READ32 (rl, l) rel[k].r_info = READ32 (rl, l) } #endif int reloc_type = ELF_R_TYPE (REL_TYPE); int reloc_sym = ELF_R_SYM (REL_TYPE); if (reloc_sym == sym) { int of = REL_OFFSET; of = of - got_addr + got_offset; switch (bin->ehdr.e_machine) { case EM_PPC: case EM_PPC64: { RBinElfSection *s = get_section_by_name (bin, ".plt"); if (s) { ut8 buf[4]; ut64 base; len = r_buf_read_at (bin->b, s->offset, buf, sizeof (buf)); if (len < 4) { goto out; } base = r_read_be32 (buf); base -= (nrel * 16); base += (k * 16); plt_addr = base; free (REL); return plt_addr; } } break; case EM_SPARC: case EM_SPARCV9: case EM_SPARC32PLUS: plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt"); if (plt_addr == -1) { free (rela); return -1; } if (reloc_type == R_386_PC16) { plt_addr += k * 12 + 20; // thumb symbol if (plt_addr & 1) { plt_addr--; } free (REL); return plt_addr; } else { bprintf ("Unknown sparc reloc type %d\n", reloc_type); } /* SPARC */ break; case EM_ARM: case EM_AARCH64: plt_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".plt"); if (plt_addr == -1) { free (rela); return UT32_MAX; } switch (reloc_type) { case R_386_8: { plt_addr += k * 12 + 20; // thumb symbol if (plt_addr & 1) { plt_addr--; } free (REL); return plt_addr; } break; case 1026: // arm64 aarch64 plt_sym_addr = plt_addr + k * 16 + 32; goto done; default: bprintf ("Unsupported relocation type for imports %d\n", reloc_type); break; } break; case EM_386: case EM_X86_64: switch (reloc_type) { case 1: // unknown relocs found in voidlinux for x86-64 // break; case R_386_GLOB_DAT: case R_386_JMP_SLOT: { ut8 buf[8]; if (of + sizeof(Elf_(Addr)) < bin->size) { // ONLY FOR X86 if (of > bin->size || of + sizeof (Elf_(Addr)) > bin->size) { goto out; } len = r_buf_read_at (bin->b, of, buf, sizeof (Elf_(Addr))); if (len < -1) { goto out; } plt_sym_addr = sizeof (Elf_(Addr)) == 4 ? r_read_le32 (buf) : r_read_le64 (buf); if (!plt_sym_addr) { //XXX HACK ALERT!!!! full relro?? try to fix it //will there always be .plt.got, what would happen if is .got.plt? RBinElfSection *s = get_section_by_name (bin, ".plt.got"); if (Elf_(r_bin_elf_has_relro)(bin) < R_ELF_PART_RELRO || !s) { goto done; } plt_addr = s->offset; of = of + got_addr - got_offset; while (plt_addr + 2 + 4 < s->offset + s->size) { /*we try to locate the plt entry that correspond with the relocation since got does not point back to .plt. In this case it has the following form ff253a152000 JMP QWORD [RIP + 0x20153A] 6690 NOP ---- ff25ec9f0408 JMP DWORD [reloc.puts_236] plt_addr + 2 to remove jmp opcode and get the imm reading 4 and if RIP (plt_addr + 6) + imm == rel->offset return plt_addr, that will be our sym addr perhaps this hack doesn't work on 32 bits */ len = r_buf_read_at (bin->b, plt_addr + 2, buf, 4); if (len < -1) { goto out; } plt_sym_addr = sizeof (Elf_(Addr)) == 4 ? r_read_le32 (buf) : r_read_le64 (buf); //relative address if ((plt_addr + 6 + Elf_(r_bin_elf_v2p) (bin, plt_sym_addr)) == of) { plt_sym_addr = plt_addr; goto done; } else if (plt_sym_addr == of) { plt_sym_addr = plt_addr; goto done; } plt_addr += 8; } } else { plt_sym_addr -= 6; } goto done; } break; } default: bprintf ("Unsupported relocation type for imports %d\n", reloc_type); free (REL); return of; break; } break; case 8: // MIPS32 BIG ENDIAN relocs { RBinElfSection *s = get_section_by_name (bin, ".rela.plt"); if (s) { ut8 buf[1024]; const ut8 *base; plt_addr = s->rva + s->size; len = r_buf_read_at (bin->b, s->offset + s->size, buf, sizeof (buf)); if (len != sizeof (buf)) { // oops } base = r_mem_mem_aligned (buf, sizeof (buf), (const ut8*)"\x3c\x0f\x00", 3, 4); if (base) { plt_addr += (int)(size_t)(base - buf); } else { plt_addr += 108 + 8; // HARDCODED HACK } plt_addr += k * 16; free (REL); return plt_addr; } } break; default: bprintf ("Unsupported relocs type %d for arch %d\n", reloc_type, bin->ehdr.e_machine); break; } } } done: free (REL); return plt_sym_addr; out: free (REL); return -1; } int Elf_(r_bin_elf_has_nx)(ELFOBJ *bin) { int i; if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_GNU_STACK) { return (!(bin->phdr[i].p_flags & 1))? 1: 0; } } } return 0; } int Elf_(r_bin_elf_has_relro)(ELFOBJ *bin) { int i; bool haveBindNow = false; bool haveGnuRelro = false; if (bin && bin->dyn_buf) { for (i = 0; i < bin->dyn_entries; i++) { switch (bin->dyn_buf[i].d_tag) { case DT_BIND_NOW: haveBindNow = true; break; case DT_FLAGS: for (i++; i < bin->dyn_entries ; i++) { ut32 dTag = bin->dyn_buf[i].d_tag; if (!dTag) { break; } switch (dTag) { case DT_FLAGS_1: if (bin->dyn_buf[i].d_un.d_val & DF_1_NOW) { haveBindNow = true; break; } } } break; } } } if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_GNU_RELRO) { haveGnuRelro = true; break; } } } if (haveGnuRelro) { if (haveBindNow) { return R_ELF_FULL_RELRO; } return R_ELF_PART_RELRO; } return R_ELF_NO_RELRO; } /* To compute the base address, one determines the memory address associated with the lowest p_vaddr value for a PT_LOAD segment. One then obtains the base address by truncating the memory address to the nearest multiple of the maximum page size */ ut64 Elf_(r_bin_elf_get_baddr)(ELFOBJ *bin) { int i; ut64 tmp, base = UT64_MAX; if (!bin) { return 0; } if (bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_LOAD) { tmp = (ut64)bin->phdr[i].p_vaddr & ELF_PAGE_MASK; tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE)); if (tmp < base) { base = tmp; } } } } if (base == UT64_MAX && bin->ehdr.e_type == ET_REL) { //we return our own base address for ET_REL type //we act as a loader for ELF return 0x08000000; } return base == UT64_MAX ? 0 : base; } ut64 Elf_(r_bin_elf_get_boffset)(ELFOBJ *bin) { int i; ut64 tmp, base = UT64_MAX; if (bin && bin->phdr) { for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_LOAD) { tmp = (ut64)bin->phdr[i].p_offset & ELF_PAGE_MASK; tmp = tmp - (tmp % (1 << ELF_PAGE_SIZE)); if (tmp < base) { base = tmp; } } } } return base == UT64_MAX ? 0 : base; } ut64 Elf_(r_bin_elf_get_init_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (r_buf_read_at (bin->b, entry + 16, buf, sizeof (buf)) < 1) { bprintf ("Warning: read (init_offset)\n"); return 0; } if (buf[0] == 0x68) { // push // x86 only ut64 addr; memmove (buf, buf+1, 4); addr = (ut64)r_read_le32 (buf); return Elf_(r_bin_elf_v2p) (bin, addr); } return 0; } ut64 Elf_(r_bin_elf_get_fini_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (r_buf_read_at (bin->b, entry+11, buf, sizeof (buf)) == -1) { bprintf ("Warning: read (get_fini)\n"); return 0; } if (*buf == 0x68) { // push // x86/32 only ut64 addr; memmove (buf, buf+1, 4); addr = (ut64)r_read_le32 (buf); return Elf_(r_bin_elf_v2p) (bin, addr); } return 0; } ut64 Elf_(r_bin_elf_get_entry_offset)(ELFOBJ *bin) { ut64 entry; if (!bin) { return 0LL; } entry = bin->ehdr.e_entry; if (!entry) { entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init.text"); if (entry != UT64_MAX) { return entry; } entry = Elf_(r_bin_elf_get_section_offset)(bin, ".text"); if (entry != UT64_MAX) { return entry; } entry = Elf_(r_bin_elf_get_section_offset)(bin, ".init"); if (entry != UT64_MAX) { return entry; } if (entry == UT64_MAX) { return 0; } } return Elf_(r_bin_elf_v2p) (bin, entry); } static ut64 getmainsymbol(ELFOBJ *bin) { struct r_bin_elf_symbol_t *symbol; int i; if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) { return UT64_MAX; } for (i = 0; !symbol[i].last; i++) { if (!strcmp (symbol[i].name, "main")) { ut64 paddr = symbol[i].offset; return Elf_(r_bin_elf_p2v) (bin, paddr); } } return UT64_MAX; } ut64 Elf_(r_bin_elf_get_main_offset)(ELFOBJ *bin) { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); ut8 buf[512]; if (!bin) { return 0LL; } if (entry > bin->size || (entry + sizeof (buf)) > bin->size) { return 0; } if (r_buf_read_at (bin->b, entry, buf, sizeof (buf)) < 1) { bprintf ("Warning: read (main)\n"); return 0; } // ARM64 if (buf[0x18+3] == 0x58 && buf[0x2f] == 0x00) { ut32 entry_vaddr = Elf_(r_bin_elf_p2v) (bin, entry); ut32 main_addr = r_read_le32 (&buf[0x30]); if ((main_addr >> 16) == (entry_vaddr >> 16)) { return Elf_(r_bin_elf_v2p) (bin, main_addr); } } // TODO: Use arch to identify arch before memcmp's // ARM ut64 text = Elf_(r_bin_elf_get_section_offset)(bin, ".text"); ut64 text_end = text + bin->size; // ARM-Thumb-Linux if (entry & 1 && !memcmp (buf, "\xf0\x00\x0b\x4f\xf0\x00", 6)) { ut32 * ptr = (ut32*)(buf+40-1); if (*ptr &1) { return Elf_(r_bin_elf_v2p) (bin, *ptr -1); } } if (!memcmp (buf, "\x00\xb0\xa0\xe3\x00\xe0\xa0\xe3", 8)) { // endian stuff here ut32 *addr = (ut32*)(buf+0x34); /* 0x00012000 00b0a0e3 mov fp, 0 0x00012004 00e0a0e3 mov lr, 0 */ if (*addr > text && *addr < (text_end)) { return Elf_(r_bin_elf_v2p) (bin, *addr); } } // MIPS /* get .got, calculate offset of main symbol */ if (!memcmp (buf, "\x21\x00\xe0\x03\x01\x00\x11\x04", 8)) { /* assuming the startup code looks like got = gp-0x7ff0 got[index__libc_start_main] ( got[index_main] ); looking for the instruction generating the first argument to find main lw a0, offset(gp) */ ut64 got_offset; if ((got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got")) != -1 || (got_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".got.plt")) != -1) { const ut64 gp = got_offset + 0x7ff0; unsigned i; for (i = 0; i < sizeof(buf) / sizeof(buf[0]); i += 4) { const ut32 instr = r_read_le32 (&buf[i]); if ((instr & 0xffff0000) == 0x8f840000) { // lw a0, offset(gp) const short delta = instr & 0x0000ffff; r_buf_read_at (bin->b, /* got_entry_offset = */ gp + delta, buf, 4); return Elf_(r_bin_elf_v2p) (bin, r_read_le32 (&buf[0])); } } } return 0; } // ARM if (!memcmp (buf, "\x24\xc0\x9f\xe5\x00\xb0\xa0\xe3", 8)) { ut64 addr = r_read_le32 (&buf[48]); return Elf_(r_bin_elf_v2p) (bin, addr); } // X86-CGC if (buf[0] == 0xe8 && !memcmp (buf + 5, "\x50\xe8\x00\x00\x00\x00\xb8\x01\x00\x00\x00\x53", 12)) { size_t SIZEOF_CALL = 5; ut64 rel_addr = (ut64)((int)(buf[1] + (buf[2] << 8) + (buf[3] << 16) + (buf[4] << 24))); ut64 addr = Elf_(r_bin_elf_p2v)(bin, entry + SIZEOF_CALL); addr += rel_addr; return Elf_(r_bin_elf_v2p) (bin, addr); } // X86-PIE if (buf[0x00] == 0x48 && buf[0x1e] == 0x8d && buf[0x11] == 0xe8) { ut32 *pmain = (ut32*)(buf + 0x30); ut64 vmain = Elf_(r_bin_elf_p2v) (bin, (ut64)*pmain); ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry); if (vmain >> 16 == ventry >> 16) { return (ut64)vmain; } } // X86-PIE if (buf[0x1d] == 0x48 && buf[0x1e] == 0x8b) { if (!memcmp (buf, "\x31\xed\x49\x89", 4)) {// linux ut64 maddr, baddr; ut8 n32s[sizeof (ut32)] = {0}; maddr = entry + 0x24 + r_read_le32 (buf + 0x20); if (r_buf_read_at (bin->b, maddr, n32s, sizeof (ut32)) == -1) { bprintf ("Warning: read (maddr) 2\n"); return 0; } maddr = (ut64)r_read_le32 (&n32s[0]); baddr = (bin->ehdr.e_entry >> 16) << 16; if (bin->phdr) { baddr = Elf_(r_bin_elf_get_baddr) (bin); } maddr += baddr; return maddr; } } // X86-NONPIE #if R_BIN_ELF64 if (!memcmp (buf, "\x49\x89\xd9", 3) && buf[156] == 0xe8) { // openbsd return r_read_le32 (&buf[157]) + entry + 156 + 5; } if (!memcmp (buf+29, "\x48\xc7\xc7", 3)) { // linux ut64 addr = (ut64)r_read_le32 (&buf[29 + 3]); return Elf_(r_bin_elf_v2p) (bin, addr); } #else if (buf[23] == '\x68') { ut64 addr = (ut64)r_read_le32 (&buf[23 + 1]); return Elf_(r_bin_elf_v2p) (bin, addr); } #endif /* linux64 pie main -- probably buggy in some cases */ if (buf[29] == 0x48 && buf[30] == 0x8d) { // lea rdi, qword [rip-0x21c4] ut8 *p = buf + 32; st32 maindelta = (st32)r_read_le32 (p); ut64 vmain = (ut64)(entry + 29 + maindelta) + 7; ut64 ventry = Elf_(r_bin_elf_p2v) (bin, entry); if (vmain>>16 == ventry>>16) { return (ut64)vmain; } } /* find sym.main if possible */ { ut64 m = getmainsymbol (bin); if (m != UT64_MAX) return m; } return UT64_MAX; } int Elf_(r_bin_elf_get_stripped)(ELFOBJ *bin) { int i; if (!bin->shdr) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if (bin->shdr[i].sh_type == SHT_SYMTAB) { return false; } } return true; } char *Elf_(r_bin_elf_intrp)(ELFOBJ *bin) { int i; if (!bin || !bin->phdr) { return NULL; } for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { char *str = NULL; ut64 addr = bin->phdr[i].p_offset; int sz = bin->phdr[i].p_memsz; sdb_num_set (bin->kv, "elf_header.intrp_addr", addr, 0); sdb_num_set (bin->kv, "elf_header.intrp_size", sz, 0); if (sz < 1) { return NULL; } str = malloc (sz + 1); if (!str) { return NULL; } if (r_buf_read_at (bin->b, addr, (ut8*)str, sz) < 1) { bprintf ("Warning: read (main)\n"); return 0; } str[sz] = 0; sdb_set (bin->kv, "elf_header.intrp", str, 0); return str; } } return NULL; } int Elf_(r_bin_elf_get_static)(ELFOBJ *bin) { int i; if (!bin->phdr) { return false; } for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { return false; } } return true; } char* Elf_(r_bin_elf_get_data_encoding)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_DATA]) { case ELFDATANONE: return strdup ("none"); case ELFDATA2LSB: return strdup ("2's complement, little endian"); case ELFDATA2MSB: return strdup ("2's complement, big endian"); default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_DATA]); } } int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) { return true; } char* Elf_(r_bin_elf_get_arch)(ELFOBJ *bin) { switch (bin->ehdr.e_machine) { case EM_ARC: case EM_ARC_A5: return strdup ("arc"); case EM_AVR: return strdup ("avr"); case EM_CRIS: return strdup ("cris"); case EM_68K: return strdup ("m68k"); case EM_MIPS: case EM_MIPS_RS3_LE: case EM_MIPS_X: return strdup ("mips"); case EM_MCST_ELBRUS: return strdup ("elbrus"); case EM_TRICORE: return strdup ("tricore"); case EM_ARM: case EM_AARCH64: return strdup ("arm"); case EM_HEXAGON: return strdup ("hexagon"); case EM_BLACKFIN: return strdup ("blackfin"); case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: return strdup ("sparc"); case EM_PPC: case EM_PPC64: return strdup ("ppc"); case EM_PARISC: return strdup ("hppa"); case EM_PROPELLER: return strdup ("propeller"); case EM_MICROBLAZE: return strdup ("microblaze.gnu"); case EM_RISCV: return strdup ("riscv"); case EM_VAX: return strdup ("vax"); case EM_XTENSA: return strdup ("xtensa"); case EM_LANAI: return strdup ("lanai"); case EM_VIDEOCORE3: case EM_VIDEOCORE4: return strdup ("vc4"); case EM_SH: return strdup ("sh"); case EM_V850: return strdup ("v850"); case EM_IA_64: return strdup("ia64"); default: return strdup ("x86"); } } char* Elf_(r_bin_elf_get_machine_name)(ELFOBJ *bin) { switch (bin->ehdr.e_machine) { case EM_NONE: return strdup ("No machine"); case EM_M32: return strdup ("AT&T WE 32100"); case EM_SPARC: return strdup ("SUN SPARC"); case EM_386: return strdup ("Intel 80386"); case EM_68K: return strdup ("Motorola m68k family"); case EM_88K: return strdup ("Motorola m88k family"); case EM_860: return strdup ("Intel 80860"); case EM_MIPS: return strdup ("MIPS R3000"); case EM_S370: return strdup ("IBM System/370"); case EM_MIPS_RS3_LE: return strdup ("MIPS R3000 little-endian"); case EM_PARISC: return strdup ("HPPA"); case EM_VPP500: return strdup ("Fujitsu VPP500"); case EM_SPARC32PLUS: return strdup ("Sun's \"v8plus\""); case EM_960: return strdup ("Intel 80960"); case EM_PPC: return strdup ("PowerPC"); case EM_PPC64: return strdup ("PowerPC 64-bit"); case EM_S390: return strdup ("IBM S390"); case EM_V800: return strdup ("NEC V800 series"); case EM_FR20: return strdup ("Fujitsu FR20"); case EM_RH32: return strdup ("TRW RH-32"); case EM_RCE: return strdup ("Motorola RCE"); case EM_ARM: return strdup ("ARM"); case EM_BLACKFIN: return strdup ("Analog Devices Blackfin"); case EM_FAKE_ALPHA: return strdup ("Digital Alpha"); case EM_SH: return strdup ("Hitachi SH"); case EM_SPARCV9: return strdup ("SPARC v9 64-bit"); case EM_TRICORE: return strdup ("Siemens Tricore"); case EM_ARC: return strdup ("Argonaut RISC Core"); case EM_H8_300: return strdup ("Hitachi H8/300"); case EM_H8_300H: return strdup ("Hitachi H8/300H"); case EM_H8S: return strdup ("Hitachi H8S"); case EM_H8_500: return strdup ("Hitachi H8/500"); case EM_IA_64: return strdup ("Intel Merced"); case EM_MIPS_X: return strdup ("Stanford MIPS-X"); case EM_COLDFIRE: return strdup ("Motorola Coldfire"); case EM_68HC12: return strdup ("Motorola M68HC12"); case EM_MMA: return strdup ("Fujitsu MMA Multimedia Accelerator"); case EM_PCP: return strdup ("Siemens PCP"); case EM_NCPU: return strdup ("Sony nCPU embeeded RISC"); case EM_NDR1: return strdup ("Denso NDR1 microprocessor"); case EM_STARCORE: return strdup ("Motorola Start*Core processor"); case EM_ME16: return strdup ("Toyota ME16 processor"); case EM_ST100: return strdup ("STMicroelectronic ST100 processor"); case EM_TINYJ: return strdup ("Advanced Logic Corp. Tinyj emb.fam"); case EM_X86_64: return strdup ("AMD x86-64 architecture"); case EM_LANAI: return strdup ("32bit LANAI architecture"); case EM_PDSP: return strdup ("Sony DSP Processor"); case EM_FX66: return strdup ("Siemens FX66 microcontroller"); case EM_ST9PLUS: return strdup ("STMicroelectronics ST9+ 8/16 mc"); case EM_ST7: return strdup ("STmicroelectronics ST7 8 bit mc"); case EM_68HC16: return strdup ("Motorola MC68HC16 microcontroller"); case EM_68HC11: return strdup ("Motorola MC68HC11 microcontroller"); case EM_68HC08: return strdup ("Motorola MC68HC08 microcontroller"); case EM_68HC05: return strdup ("Motorola MC68HC05 microcontroller"); case EM_SVX: return strdup ("Silicon Graphics SVx"); case EM_ST19: return strdup ("STMicroelectronics ST19 8 bit mc"); case EM_VAX: return strdup ("Digital VAX"); case EM_CRIS: return strdup ("Axis Communications 32-bit embedded processor"); case EM_JAVELIN: return strdup ("Infineon Technologies 32-bit embedded processor"); case EM_FIREPATH: return strdup ("Element 14 64-bit DSP Processor"); case EM_ZSP: return strdup ("LSI Logic 16-bit DSP Processor"); case EM_MMIX: return strdup ("Donald Knuth's educational 64-bit processor"); case EM_HUANY: return strdup ("Harvard University machine-independent object files"); case EM_PRISM: return strdup ("SiTera Prism"); case EM_AVR: return strdup ("Atmel AVR 8-bit microcontroller"); case EM_FR30: return strdup ("Fujitsu FR30"); case EM_D10V: return strdup ("Mitsubishi D10V"); case EM_D30V: return strdup ("Mitsubishi D30V"); case EM_V850: return strdup ("NEC v850"); case EM_M32R: return strdup ("Mitsubishi M32R"); case EM_MN10300: return strdup ("Matsushita MN10300"); case EM_MN10200: return strdup ("Matsushita MN10200"); case EM_PJ: return strdup ("picoJava"); case EM_OPENRISC: return strdup ("OpenRISC 32-bit embedded processor"); case EM_ARC_A5: return strdup ("ARC Cores Tangent-A5"); case EM_XTENSA: return strdup ("Tensilica Xtensa Architecture"); case EM_AARCH64: return strdup ("ARM aarch64"); case EM_PROPELLER: return strdup ("Parallax Propeller"); case EM_MICROBLAZE: return strdup ("Xilinx MicroBlaze"); case EM_RISCV: return strdup ("RISC V"); case EM_VIDEOCORE3: return strdup ("VideoCore III"); case EM_VIDEOCORE4: return strdup ("VideoCore IV"); default: return r_str_newf ("<unknown>: 0x%x", bin->ehdr.e_machine); } } char* Elf_(r_bin_elf_get_file_type)(ELFOBJ *bin) { ut32 e_type; if (!bin) { return NULL; } e_type = (ut32)bin->ehdr.e_type; // cast to avoid warn in iphone-gcc, must be ut16 switch (e_type) { case ET_NONE: return strdup ("NONE (None)"); case ET_REL: return strdup ("REL (Relocatable file)"); case ET_EXEC: return strdup ("EXEC (Executable file)"); case ET_DYN: return strdup ("DYN (Shared object file)"); case ET_CORE: return strdup ("CORE (Core file)"); } if ((e_type >= ET_LOPROC) && (e_type <= ET_HIPROC)) { return r_str_newf ("Processor Specific: %x", e_type); } if ((e_type >= ET_LOOS) && (e_type <= ET_HIOS)) { return r_str_newf ("OS Specific: %x", e_type); } return r_str_newf ("<unknown>: %x", e_type); } char* Elf_(r_bin_elf_get_elf_class)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_CLASS]) { case ELFCLASSNONE: return strdup ("none"); case ELFCLASS32: return strdup ("ELF32"); case ELFCLASS64: return strdup ("ELF64"); default: return r_str_newf ("<unknown: %x>", bin->ehdr.e_ident[EI_CLASS]); } } int Elf_(r_bin_elf_get_bits)(ELFOBJ *bin) { /* Hack for ARCompact */ if (bin->ehdr.e_machine == EM_ARC_A5) { return 16; } /* Hack for Ps2 */ if (bin->phdr && bin->ehdr.e_machine == EM_MIPS) { const ut32 mipsType = bin->ehdr.e_flags & EF_MIPS_ARCH; if (bin->ehdr.e_type == ET_EXEC) { int i; bool haveInterp = false; for (i = 0; i < bin->ehdr.e_phnum; i++) { if (bin->phdr[i].p_type == PT_INTERP) { haveInterp = true; } } if (!haveInterp && mipsType == EF_MIPS_ARCH_3) { // Playstation2 Hack return 64; } } // TODO: show this specific asm.cpu somewhere in bininfo (mips1, mips2, mips3, mips32r2, ...) switch (mipsType) { case EF_MIPS_ARCH_1: case EF_MIPS_ARCH_2: case EF_MIPS_ARCH_3: case EF_MIPS_ARCH_4: case EF_MIPS_ARCH_5: case EF_MIPS_ARCH_32: return 32; case EF_MIPS_ARCH_64: return 64; case EF_MIPS_ARCH_32R2: return 32; case EF_MIPS_ARCH_64R2: return 64; break; } return 32; } /* Hack for Thumb */ if (bin->ehdr.e_machine == EM_ARM) { if (bin->ehdr.e_type != ET_EXEC) { struct r_bin_elf_symbol_t *symbol; if ((symbol = Elf_(r_bin_elf_get_symbols) (bin))) { int i = 0; for (i = 0; !symbol[i].last; i++) { ut64 paddr = symbol[i].offset; if (paddr & 1) { return 16; } } } } { ut64 entry = Elf_(r_bin_elf_get_entry_offset) (bin); if (entry & 1) { return 16; } } } switch (bin->ehdr.e_ident[EI_CLASS]) { case ELFCLASS32: return 32; case ELFCLASS64: return 64; case ELFCLASSNONE: default: return 32; // defaults } } static inline int noodle(ELFOBJ *bin, const char *s) { const ut8 *p = bin->b->buf; if (bin->b->length > 64) { p += bin->b->length - 64; } else { return 0; } return r_mem_mem (p, 64, (const ut8 *)s, strlen (s)) != NULL; } static inline int needle(ELFOBJ *bin, const char *s) { if (bin->shstrtab) { ut32 len = bin->shstrtab_size; if (len > 4096) { len = 4096; // avoid slow loading .. can be buggy? } return r_mem_mem ((const ut8*)bin->shstrtab, len, (const ut8*)s, strlen (s)) != NULL; } return 0; } // TODO: must return const char * all those strings must be const char os[LINUX] or so char* Elf_(r_bin_elf_get_osabi_name)(ELFOBJ *bin) { switch (bin->ehdr.e_ident[EI_OSABI]) { case ELFOSABI_LINUX: return strdup("linux"); case ELFOSABI_SOLARIS: return strdup("solaris"); case ELFOSABI_FREEBSD: return strdup("freebsd"); case ELFOSABI_HPUX: return strdup("hpux"); } /* Hack to identify OS */ if (needle (bin, "openbsd")) return strdup ("openbsd"); if (needle (bin, "netbsd")) return strdup ("netbsd"); if (needle (bin, "freebsd")) return strdup ("freebsd"); if (noodle (bin, "BEOS:APP_VERSION")) return strdup ("beos"); if (needle (bin, "GNU")) return strdup ("linux"); return strdup ("linux"); } ut8 *Elf_(r_bin_elf_grab_regstate)(ELFOBJ *bin, int *len) { if (bin->phdr) { int i; int num = bin->ehdr.e_phnum; for (i = 0; i < num; i++) { if (bin->phdr[i].p_type != PT_NOTE) { continue; } int bits = Elf_(r_bin_elf_get_bits)(bin); int regdelta = (bits == 64)? 0x84: 0x40; // x64 vs x32 int regsize = 160; // for x86-64 ut8 *buf = malloc (regsize); if (r_buf_read_at (bin->b, bin->phdr[i].p_offset + regdelta, buf, regsize) != regsize) { free (buf); bprintf ("Cannot read register state from CORE file\n"); return NULL; } if (len) { *len = regsize; } return buf; } } bprintf ("Cannot find NOTE section\n"); return NULL; } int Elf_(r_bin_elf_is_big_endian)(ELFOBJ *bin) { return (bin->ehdr.e_ident[EI_DATA] == ELFDATA2MSB); } /* XXX Init dt_strtab? */ char *Elf_(r_bin_elf_get_rpath)(ELFOBJ *bin) { char *ret = NULL; int j; if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab) { return NULL; } for (j = 0; j< bin->dyn_entries; j++) { if (bin->dyn_buf[j].d_tag == DT_RPATH || bin->dyn_buf[j].d_tag == DT_RUNPATH) { if (!(ret = calloc (1, ELF_STRING_LENGTH))) { perror ("malloc (rpath)"); return NULL; } if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) { free (ret); return NULL; } strncpy (ret, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH); ret[ELF_STRING_LENGTH - 1] = '\0'; break; } } return ret; } static size_t get_relocs_num(ELFOBJ *bin) { size_t i, size, ret = 0; /* we need to be careful here, in malformed files the section size might * not be a multiple of a Rel/Rela size; round up so we allocate enough * space. */ #define NUMENTRIES_ROUNDUP(sectionsize, entrysize) (((sectionsize)+(entrysize)-1)/(entrysize)) if (!bin->g_sections) { return 0; } size = bin->is_rela == DT_REL ? sizeof (Elf_(Rel)) : sizeof (Elf_(Rela)); for (i = 0; !bin->g_sections[i].last; i++) { if (!strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela."))) { if (!bin->is_rela) { size = sizeof (Elf_(Rela)); } ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size); } else if (!strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel."))){ if (!bin->is_rela) { size = sizeof (Elf_(Rel)); } ret += NUMENTRIES_ROUNDUP (bin->g_sections[i].size, size); } } return ret; #undef NUMENTRIES_ROUNDUP } static int read_reloc(ELFOBJ *bin, RBinElfReloc *r, int is_rela, ut64 offset) { ut8 *buf = bin->b->buf; int j = 0; if (offset + sizeof (Elf_ (Rela)) > bin->size || offset + sizeof (Elf_(Rela)) < offset) { return -1; } if (is_rela == DT_RELA) { Elf_(Rela) rela; #if R_BIN_ELF64 rela.r_offset = READ64 (buf + offset, j) rela.r_info = READ64 (buf + offset, j) rela.r_addend = READ64 (buf + offset, j) #else rela.r_offset = READ32 (buf + offset, j) rela.r_info = READ32 (buf + offset, j) rela.r_addend = READ32 (buf + offset, j) #endif r->is_rela = is_rela; r->offset = rela.r_offset; r->type = ELF_R_TYPE (rela.r_info); r->sym = ELF_R_SYM (rela.r_info); r->last = 0; r->addend = rela.r_addend; return sizeof (Elf_(Rela)); } else { Elf_(Rel) rel; #if R_BIN_ELF64 rel.r_offset = READ64 (buf + offset, j) rel.r_info = READ64 (buf + offset, j) #else rel.r_offset = READ32 (buf + offset, j) rel.r_info = READ32 (buf + offset, j) #endif r->is_rela = is_rela; r->offset = rel.r_offset; r->type = ELF_R_TYPE (rel.r_info); r->sym = ELF_R_SYM (rel.r_info); r->last = 0; return sizeof (Elf_(Rel)); } } RBinElfReloc* Elf_(r_bin_elf_get_relocs)(ELFOBJ *bin) { int res, rel, rela, i, j; size_t reloc_num = 0; RBinElfReloc *ret = NULL; if (!bin || !bin->g_sections) { return NULL; } reloc_num = get_relocs_num (bin); if (!reloc_num) { return NULL; } bin->reloc_num = reloc_num; ret = (RBinElfReloc*)calloc ((size_t)reloc_num + 1, sizeof(RBinElfReloc)); if (!ret) { return NULL; } #if DEAD_CODE ut64 section_text_offset = Elf_(r_bin_elf_get_section_offset) (bin, ".text"); if (section_text_offset == -1) { section_text_offset = 0; } #endif for (i = 0, rel = 0; !bin->g_sections[i].last && rel < reloc_num ; i++) { bool is_rela = 0 == strncmp (bin->g_sections[i].name, ".rela.", strlen (".rela.")); bool is_rel = 0 == strncmp (bin->g_sections[i].name, ".rel.", strlen (".rel.")); if (!is_rela && !is_rel) { continue; } for (j = 0; j < bin->g_sections[i].size; j += res) { if (bin->g_sections[i].size > bin->size) { break; } if (bin->g_sections[i].offset > bin->size) { break; } if (rel >= reloc_num) { bprintf ("Internal error: ELF relocation buffer too small," "please file a bug report."); break; } if (!bin->is_rela) { rela = is_rela? DT_RELA : DT_REL; } else { rela = bin->is_rela; } res = read_reloc (bin, &ret[rel], rela, bin->g_sections[i].offset + j); if (j + res > bin->g_sections[i].size) { bprintf ("Warning: malformed file, relocation entry #%u is partially beyond the end of section %u.\n", rel, i); } if (bin->ehdr.e_type == ET_REL) { if (bin->g_sections[i].info < bin->ehdr.e_shnum && bin->shdr) { ret[rel].rva = bin->shdr[bin->g_sections[i].info].sh_offset + ret[rel].offset; ret[rel].rva = Elf_(r_bin_elf_p2v) (bin, ret[rel].rva); } else { ret[rel].rva = ret[rel].offset; } } else { ret[rel].rva = ret[rel].offset; ret[rel].offset = Elf_(r_bin_elf_v2p) (bin, ret[rel].offset); } ret[rel].last = 0; if (res < 0) { break; } rel++; } } ret[reloc_num].last = 1; return ret; } RBinElfLib* Elf_(r_bin_elf_get_libs)(ELFOBJ *bin) { RBinElfLib *ret = NULL; int j, k; if (!bin || !bin->phdr || !bin->dyn_buf || !bin->strtab || *(bin->strtab+1) == '0') { return NULL; } for (j = 0, k = 0; j < bin->dyn_entries; j++) if (bin->dyn_buf[j].d_tag == DT_NEEDED) { RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib)); if (!r) { perror ("realloc (libs)"); free (ret); return NULL; } ret = r; if (bin->dyn_buf[j].d_un.d_val > bin->strtab_size) { free (ret); return NULL; } strncpy (ret[k].name, bin->strtab + bin->dyn_buf[j].d_un.d_val, ELF_STRING_LENGTH); ret[k].name[ELF_STRING_LENGTH - 1] = '\0'; ret[k].last = 0; if (ret[k].name[0]) { k++; } } RBinElfLib *r = realloc (ret, (k + 1) * sizeof (RBinElfLib)); if (!r) { perror ("realloc (libs)"); free (ret); return NULL; } ret = r; ret[k].last = 1; return ret; } static RBinElfSection* get_sections_from_phdr(ELFOBJ *bin) { RBinElfSection *ret; int i, num_sections = 0; ut64 reldyn = 0, relava = 0, pltgotva = 0, relva = 0; ut64 reldynsz = 0, relasz = 0, pltgotsz = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) return NULL; for (i = 0; i < bin->dyn_entries; i++) { switch (bin->dyn_buf[i].d_tag) { case DT_REL: reldyn = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_RELA: relva = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_RELSZ: reldynsz = bin->dyn_buf[i].d_un.d_val; break; case DT_RELASZ: relasz = bin->dyn_buf[i].d_un.d_val; break; case DT_PLTGOT: pltgotva = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; case DT_PLTRELSZ: pltgotsz = bin->dyn_buf[i].d_un.d_val; break; case DT_JMPREL: relava = bin->dyn_buf[i].d_un.d_ptr; num_sections++; break; default: break; } } ret = calloc (num_sections + 1, sizeof(RBinElfSection)); if (!ret) { return NULL; } i = 0; if (reldyn) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, reldyn); ret[i].rva = reldyn; ret[i].size = reldynsz; strcpy (ret[i].name, ".rel.dyn"); ret[i].last = 0; i++; } if (relava) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relava); ret[i].rva = relava; ret[i].size = pltgotsz; strcpy (ret[i].name, ".rela.plt"); ret[i].last = 0; i++; } if (relva) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, relva); ret[i].rva = relva; ret[i].size = relasz; strcpy (ret[i].name, ".rel.plt"); ret[i].last = 0; i++; } if (pltgotva) { ret[i].offset = Elf_(r_bin_elf_v2p) (bin, pltgotva); ret[i].rva = pltgotva; ret[i].size = pltgotsz; strcpy (ret[i].name, ".got.plt"); ret[i].last = 0; i++; } ret[i].last = 1; return ret; } RBinElfSection* Elf_(r_bin_elf_get_sections)(ELFOBJ *bin) { RBinElfSection *ret = NULL; char unknown_s[20], invalid_s[20]; int i, nidx, unknown_c=0, invalid_c=0; if (!bin) { return NULL; } if (bin->g_sections) { return bin->g_sections; } if (!bin->shdr) { //we don't give up search in phdr section return get_sections_from_phdr (bin); } if (!(ret = calloc ((bin->ehdr.e_shnum + 1), sizeof (RBinElfSection)))) { return NULL; } for (i = 0; i < bin->ehdr.e_shnum; i++) { ret[i].offset = bin->shdr[i].sh_offset; ret[i].size = bin->shdr[i].sh_size; ret[i].align = bin->shdr[i].sh_addralign; ret[i].flags = bin->shdr[i].sh_flags; ret[i].link = bin->shdr[i].sh_link; ret[i].info = bin->shdr[i].sh_info; ret[i].type = bin->shdr[i].sh_type; if (bin->ehdr.e_type == ET_REL) { ret[i].rva = bin->baddr + bin->shdr[i].sh_offset; } else { ret[i].rva = bin->shdr[i].sh_addr; } nidx = bin->shdr[i].sh_name; #define SHNAME (int)bin->shdr[i].sh_name #define SHNLEN ELF_STRING_LENGTH - 4 #define SHSIZE (int)bin->shstrtab_size if (nidx < 0 || !bin->shstrtab_section || !bin->shstrtab_size || nidx > bin->shstrtab_size) { snprintf (invalid_s, sizeof (invalid_s) - 4, "invalid%d", invalid_c); strncpy (ret[i].name, invalid_s, SHNLEN); invalid_c++; } else { if (bin->shstrtab && (SHNAME > 0) && (SHNAME < SHSIZE)) { strncpy (ret[i].name, &bin->shstrtab[SHNAME], SHNLEN); } else { if (bin->shdr[i].sh_type == SHT_NULL) { //to follow the same behaviour as readelf strncpy (ret[i].name, "", sizeof (ret[i].name) - 4); } else { snprintf (unknown_s, sizeof (unknown_s)-4, "unknown%d", unknown_c); strncpy (ret[i].name, unknown_s, sizeof (ret[i].name)-4); unknown_c++; } } } ret[i].name[ELF_STRING_LENGTH-2] = '\0'; ret[i].last = 0; } ret[i].last = 1; return ret; } static void fill_symbol_bind_and_type (struct r_bin_elf_symbol_t *ret, Elf_(Sym) *sym) { #define s_bind(x) ret->bind = x #define s_type(x) ret->type = x switch (ELF_ST_BIND(sym->st_info)) { case STB_LOCAL: s_bind ("LOCAL"); break; case STB_GLOBAL: s_bind ("GLOBAL"); break; case STB_WEAK: s_bind ("WEAK"); break; case STB_NUM: s_bind ("NUM"); break; case STB_LOOS: s_bind ("LOOS"); break; case STB_HIOS: s_bind ("HIOS"); break; case STB_LOPROC: s_bind ("LOPROC"); break; case STB_HIPROC: s_bind ("HIPROC"); break; default: s_bind ("UNKNOWN"); } switch (ELF_ST_TYPE (sym->st_info)) { case STT_NOTYPE: s_type ("NOTYPE"); break; case STT_OBJECT: s_type ("OBJECT"); break; case STT_FUNC: s_type ("FUNC"); break; case STT_SECTION: s_type ("SECTION"); break; case STT_FILE: s_type ("FILE"); break; case STT_COMMON: s_type ("COMMON"); break; case STT_TLS: s_type ("TLS"); break; case STT_NUM: s_type ("NUM"); break; case STT_LOOS: s_type ("LOOS"); break; case STT_HIOS: s_type ("HIOS"); break; case STT_LOPROC: s_type ("LOPROC"); break; case STT_HIPROC: s_type ("HIPROC"); break; default: s_type ("UNKNOWN"); } } static RBinElfSymbol* get_symbols_from_phdr(ELFOBJ *bin, int type) { Elf_(Sym) *sym = NULL; Elf_(Addr) addr_sym_table = 0; ut8 s[sizeof (Elf_(Sym))] = {0}; RBinElfSymbol *ret = NULL; int i, j, r, tsize, nsym, ret_ctr; ut64 toffset = 0, tmp_offset; ut32 size, sym_size = 0; if (!bin || !bin->phdr || !bin->ehdr.e_phnum) { return NULL; } for (j = 0; j < bin->dyn_entries; j++) { switch (bin->dyn_buf[j].d_tag) { case (DT_SYMTAB): addr_sym_table = Elf_(r_bin_elf_v2p) (bin, bin->dyn_buf[j].d_un.d_ptr); break; case (DT_SYMENT): sym_size = bin->dyn_buf[j].d_un.d_val; break; default: break; } } if (!addr_sym_table) { return NULL; } if (!sym_size) { return NULL; } //since ELF doesn't specify the symbol table size we may read until the end of the buffer nsym = (bin->size - addr_sym_table) / sym_size; if (!UT32_MUL (&size, nsym, sizeof (Elf_ (Sym)))) { goto beach; } if (size < 1) { goto beach; } if (addr_sym_table > bin->size || addr_sym_table + size > bin->size) { goto beach; } if (nsym < 1) { return NULL; } // we reserve room for 4096 and grow as needed. size_t capacity1 = 4096; size_t capacity2 = 4096; sym = (Elf_(Sym)*) calloc (capacity1, sym_size); ret = (RBinElfSymbol *) calloc (capacity2, sizeof (struct r_bin_elf_symbol_t)); if (!sym || !ret) { goto beach; } for (i = 1, ret_ctr = 0; i < nsym; i++) { if (i >= capacity1) { // maybe grow // You take what you want, but you eat what you take. Elf_(Sym)* temp_sym = (Elf_(Sym)*) realloc(sym, (capacity1 * GROWTH_FACTOR) * sym_size); if (!temp_sym) { goto beach; } sym = temp_sym; capacity1 *= GROWTH_FACTOR; } if (ret_ctr >= capacity2) { // maybe grow RBinElfSymbol *temp_ret = realloc (ret, capacity2 * GROWTH_FACTOR * sizeof (struct r_bin_elf_symbol_t)); if (!temp_ret) { goto beach; } ret = temp_ret; capacity2 *= GROWTH_FACTOR; } // read in one entry r = r_buf_read_at (bin->b, addr_sym_table + i * sizeof (Elf_ (Sym)), s, sizeof (Elf_ (Sym))); if (r < 1) { goto beach; } int j = 0; #if R_BIN_ELF64 sym[i].st_name = READ32 (s, j); sym[i].st_info = READ8 (s, j); sym[i].st_other = READ8 (s, j); sym[i].st_shndx = READ16 (s, j); sym[i].st_value = READ64 (s, j); sym[i].st_size = READ64 (s, j); #else sym[i].st_name = READ32 (s, j); sym[i].st_value = READ32 (s, j); sym[i].st_size = READ32 (s, j); sym[i].st_info = READ8 (s, j); sym[i].st_other = READ8 (s, j); sym[i].st_shndx = READ16 (s, j); #endif // zero symbol is always empty // Examine entry and maybe store if (type == R_BIN_ELF_IMPORTS && sym[i].st_shndx == STN_UNDEF) { if (sym[i].st_value) { toffset = sym[i].st_value; } else if ((toffset = get_import_addr (bin, i)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[i].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[i].st_info) != STT_SECTION && ELF_ST_TYPE (sym[i].st_info) != STT_FILE) { tsize = sym[i].st_size; toffset = (ut64) sym[i].st_value; } else { continue; } tmp_offset = Elf_(r_bin_elf_v2p) (bin, toffset); if (tmp_offset > bin->size) { goto done; } if (sym[i].st_name + 2 > bin->strtab_size) { // Since we are reading beyond the symbol table what's happening // is that some entry is trying to dereference the strtab beyond its capacity // is not a symbol so is the end goto done; } ret[ret_ctr].offset = tmp_offset; ret[ret_ctr].size = tsize; { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[i].st_name; int maxsize = R_MIN (bin->size, bin->strtab_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const int len = __strnlen (bin->strtab + st_name, rest); memcpy (ret[ret_ctr].name, &bin->strtab[st_name], len); } } ret[ret_ctr].ordinal = i; ret[ret_ctr].in_shdr = false; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[i]); ret[ret_ctr].last = 0; ret_ctr++; } done: ret[ret_ctr].last = 1; // Size everything down to only what is used { nsym = i > 0 ? i : 1; Elf_ (Sym) * temp_sym = (Elf_ (Sym)*) realloc (sym, (nsym * GROWTH_FACTOR) * sym_size); if (!temp_sym) { goto beach; } sym = temp_sym; } { ret_ctr = ret_ctr > 0 ? ret_ctr : 1; RBinElfSymbol *p = (RBinElfSymbol *) realloc (ret, (ret_ctr + 1) * sizeof (RBinElfSymbol)); if (!p) { goto beach; } ret = p; } if (type == R_BIN_ELF_IMPORTS && !bin->imports_by_ord_size) { bin->imports_by_ord_size = ret_ctr + 1; if (ret_ctr > 0) { bin->imports_by_ord = (RBinImport * *) calloc (ret_ctr + 1, sizeof (RBinImport*)); } else { bin->imports_by_ord = NULL; } } else if (type == R_BIN_ELF_SYMBOLS && !bin->symbols_by_ord_size && ret_ctr) { bin->symbols_by_ord_size = ret_ctr + 1; if (ret_ctr > 0) { bin->symbols_by_ord = (RBinSymbol * *) calloc (ret_ctr + 1, sizeof (RBinSymbol*)); }else { bin->symbols_by_ord = NULL; } } free (sym); return ret; beach: free (sym); free (ret); return NULL; } static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_symbols)(ELFOBJ *bin) { if (!bin) { return NULL; } if (bin->phdr_symbols) { return bin->phdr_symbols; } bin->phdr_symbols = get_symbols_from_phdr (bin, R_BIN_ELF_SYMBOLS); return bin->phdr_symbols; } static RBinElfSymbol *Elf_(r_bin_elf_get_phdr_imports)(ELFOBJ *bin) { if (!bin) { return NULL; } if (bin->phdr_imports) { return bin->phdr_imports; } bin->phdr_imports = get_symbols_from_phdr (bin, R_BIN_ELF_IMPORTS); return bin->phdr_imports; } static int Elf_(fix_symbols)(ELFOBJ *bin, int nsym, int type, RBinElfSymbol **sym) { int count = 0; RBinElfSymbol *ret = *sym; RBinElfSymbol *phdr_symbols = (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); RBinElfSymbol *tmp, *p; if (phdr_symbols) { RBinElfSymbol *d = ret; while (!d->last) { /* find match in phdr */ p = phdr_symbols; while (!p->last) { if (p->offset && d->offset == p->offset) { p->in_shdr = true; if (*p->name && strcmp (d->name, p->name)) { strcpy (d->name, p->name); } } p++; } d++; } p = phdr_symbols; while (!p->last) { if (!p->in_shdr) { count++; } p++; } /*Take those symbols that are not present in the shdr but yes in phdr*/ /*This should only should happen with fucked up binaries*/ if (count > 0) { /*what happens if a shdr says it has only one symbol? we should look anyway into phdr*/ tmp = (RBinElfSymbol*)realloc (ret, (nsym + count + 1) * sizeof (RBinElfSymbol)); if (!tmp) { return -1; } ret = tmp; ret[nsym--].last = 0; p = phdr_symbols; while (!p->last) { if (!p->in_shdr) { memcpy (&ret[++nsym], p, sizeof (RBinElfSymbol)); } p++; } ret[nsym + 1].last = 1; } *sym = ret; return nsym + 1; } return nsym; } static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) { ut32 shdr_size; int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize; ut64 toffset; ut32 size = 0; RBinElfSymbol *ret = NULL; Elf_(Shdr) *strtab_section = NULL; Elf_(Sym) *sym = NULL; ut8 s[sizeof (Elf_(Sym))] = { 0 }; char *strtab = NULL; if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size + 8 > bin->size) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) || (type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) { if (bin->shdr[i].sh_link < 1) { /* oops. fix out of range pointers */ continue; } // hack to avoid asan cry if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) { /* oops. fix out of range pointers */ continue; } strtab_section = &bin->shdr[bin->shdr[i].sh_link]; if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) { bprintf ("size (syms strtab)"); free (ret); free (strtab); return NULL; } if (!strtab) { if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) { bprintf ("malloc (syms strtab)"); goto beach; } if (strtab_section->sh_offset > bin->size || strtab_section->sh_offset + strtab_section->sh_size > bin->size) { goto beach; } if (r_buf_read_at (bin->b, strtab_section->sh_offset, (ut8*)strtab, strtab_section->sh_size) == -1) { bprintf ("Warning: read (syms strtab)\n"); goto beach; } } newsize = 1 + bin->shdr[i].sh_size; if (newsize < 0 || newsize > bin->size) { bprintf ("invalid shdr %d size\n", i); goto beach; } nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym))); if (nsym < 0) { goto beach; } if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) { bprintf ("calloc (syms)"); goto beach; } if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) { goto beach; } if (size < 1 || size > bin->size) { goto beach; } if (bin->shdr[i].sh_offset > bin->size) { goto beach; } if (bin->shdr[i].sh_offset + size > bin->size) { goto beach; } for (j = 0; j < nsym; j++) { int k = 0; r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym))); if (r < 1) { bprintf ("Warning: read (sym)\n"); goto beach; } #if R_BIN_ELF64 sym[j].st_name = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) sym[j].st_value = READ64 (s, k) sym[j].st_size = READ64 (s, k) #else sym[j].st_name = READ32 (s, k) sym[j].st_value = READ32 (s, k) sym[j].st_size = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) #endif } free (ret); ret = calloc (nsym, sizeof (RBinElfSymbol)); if (!ret) { bprintf ("Cannot allocate %d symbols\n", nsym); goto beach; } for (k = 1, ret_ctr = 0; k < nsym; k++) { if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) { if (sym[k].st_value) { toffset = sym[k].st_value; } else if ((toffset = get_import_addr (bin, k)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[k].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[k].st_info) != STT_SECTION && ELF_ST_TYPE (sym[k].st_info) != STT_FILE) { //int idx = sym[k].st_shndx; tsize = sym[k].st_size; toffset = (ut64)sym[k].st_value; } else { continue; } if (bin->ehdr.e_type == ET_REL) { if (sym[k].st_shndx < bin->ehdr.e_shnum) ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset; } else { ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset); } ret[ret_ctr].size = tsize; if (sym[k].st_name + 2 > strtab_section->sh_size) { bprintf ("Warning: index out of strtab range\n"); goto beach; } { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[k].st_name; int maxsize = R_MIN (bin->b->length, strtab_section->sh_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const size_t len = __strnlen (strtab + sym[k].st_name, rest); memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len); } } ret[ret_ctr].ordinal = k; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]); ret[ret_ctr].last = 0; ret_ctr++; } ret[ret_ctr].last = 1; // ugly dirty hack :D R_FREE (strtab); R_FREE (sym); } } if (!ret) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } int max = -1; RBinElfSymbol *aux = NULL; nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret); if (nsym == -1) { goto beach; } aux = ret; while (!aux->last) { if ((int)aux->ordinal > max) { max = aux->ordinal; } aux++; } nsym = max; if (type == R_BIN_ELF_IMPORTS) { R_FREE (bin->imports_by_ord); bin->imports_by_ord_size = nsym + 1; bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*)); } else if (type == R_BIN_ELF_SYMBOLS) { R_FREE (bin->symbols_by_ord); bin->symbols_by_ord_size = nsym + 1; bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*)); } return ret; beach: free (ret); free (sym); free (strtab); return NULL; } RBinElfSymbol *Elf_(r_bin_elf_get_symbols)(ELFOBJ *bin) { if (!bin->g_symbols) { bin->g_symbols = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_SYMBOLS); } return bin->g_symbols; } RBinElfSymbol *Elf_(r_bin_elf_get_imports)(ELFOBJ *bin) { if (!bin->g_imports) { bin->g_imports = Elf_(_r_bin_elf_get_symbols_imports) (bin, R_BIN_ELF_IMPORTS); } return bin->g_imports; } RBinElfField* Elf_(r_bin_elf_get_fields)(ELFOBJ *bin) { RBinElfField *ret = NULL; int i = 0, j; if (!bin || !(ret = calloc ((bin->ehdr.e_phnum + 3 + 1), sizeof (RBinElfField)))) { return NULL; } strncpy (ret[i].name, "ehdr", ELF_STRING_LENGTH); ret[i].offset = 0; ret[i++].last = 0; strncpy (ret[i].name, "shoff", ELF_STRING_LENGTH); ret[i].offset = bin->ehdr.e_shoff; ret[i++].last = 0; strncpy (ret[i].name, "phoff", ELF_STRING_LENGTH); ret[i].offset = bin->ehdr.e_phoff; ret[i++].last = 0; for (j = 0; bin->phdr && j < bin->ehdr.e_phnum; i++, j++) { snprintf (ret[i].name, ELF_STRING_LENGTH, "phdr_%i", j); ret[i].offset = bin->phdr[j].p_offset; ret[i].last = 0; } ret[i].last = 1; return ret; } void* Elf_(r_bin_elf_free)(ELFOBJ* bin) { int i; if (!bin) { return NULL; } free (bin->phdr); free (bin->shdr); free (bin->strtab); free (bin->dyn_buf); free (bin->shstrtab); free (bin->dynstr); //free (bin->strtab_section); if (bin->imports_by_ord) { for (i = 0; i<bin->imports_by_ord_size; i++) { free (bin->imports_by_ord[i]); } free (bin->imports_by_ord); } if (bin->symbols_by_ord) { for (i = 0; i<bin->symbols_by_ord_size; i++) { free (bin->symbols_by_ord[i]); } free (bin->symbols_by_ord); } r_buf_free (bin->b); if (bin->g_symbols != bin->phdr_symbols) { R_FREE (bin->phdr_symbols); } if (bin->g_imports != bin->phdr_imports) { R_FREE (bin->phdr_imports); } R_FREE (bin->g_sections); R_FREE (bin->g_symbols); R_FREE (bin->g_imports); free (bin); return NULL; } ELFOBJ* Elf_(r_bin_elf_new)(const char* file, bool verbose) { ut8 *buf; int size; ELFOBJ *bin = R_NEW0 (ELFOBJ); if (!bin) { return NULL; } memset (bin, 0, sizeof (ELFOBJ)); bin->file = file; if (!(buf = (ut8*)r_file_slurp (file, &size))) { return Elf_(r_bin_elf_free) (bin); } bin->size = size; bin->verbose = verbose; bin->b = r_buf_new (); if (!r_buf_set_bytes (bin->b, buf, bin->size)) { free (buf); return Elf_(r_bin_elf_free) (bin); } if (!elf_init (bin)) { free (buf); return Elf_(r_bin_elf_free) (bin); } free (buf); return bin; } ELFOBJ* Elf_(r_bin_elf_new_buf)(RBuffer *buf, bool verbose) { ELFOBJ *bin = R_NEW0 (ELFOBJ); bin->kv = sdb_new0 (); bin->b = r_buf_new (); bin->size = (ut32)buf->length; bin->verbose = verbose; if (!r_buf_set_bytes (bin->b, buf->buf, buf->length)) { return Elf_(r_bin_elf_free) (bin); } if (!elf_init (bin)) { return Elf_(r_bin_elf_free) (bin); } return bin; } static int is_in_pphdr (Elf_(Phdr) *p, ut64 addr) { return addr >= p->p_offset && addr < p->p_offset + p->p_memsz; } static int is_in_vphdr (Elf_(Phdr) *p, ut64 addr) { return addr >= p->p_vaddr && addr < p->p_vaddr + p->p_memsz; } /* converts a physical address to the virtual address, looking * at the program headers in the binary bin */ ut64 Elf_(r_bin_elf_p2v) (ELFOBJ *bin, ut64 paddr) { int i; if (!bin) return 0; if (!bin->phdr) { if (bin->ehdr.e_type == ET_REL) { return bin->baddr + paddr; } return paddr; } for (i = 0; i < bin->ehdr.e_phnum; ++i) { Elf_(Phdr) *p = &bin->phdr[i]; if (!p) { break; } if (p->p_type == PT_LOAD && is_in_pphdr (p, paddr)) { if (!p->p_vaddr && !p->p_offset) { continue; } return p->p_vaddr + paddr - p->p_offset; } } return paddr; } /* converts a virtual address to the relative physical address, looking * at the program headers in the binary bin */ ut64 Elf_(r_bin_elf_v2p) (ELFOBJ *bin, ut64 vaddr) { int i; if (!bin) { return 0; } if (!bin->phdr) { if (bin->ehdr.e_type == ET_REL) { return vaddr - bin->baddr; } return vaddr; } for (i = 0; i < bin->ehdr.e_phnum; ++i) { Elf_(Phdr) *p = &bin->phdr[i]; if (!p) { break; } if (p->p_type == PT_LOAD && is_in_vphdr (p, vaddr)) { if (!p->p_offset && !p->p_vaddr) { continue; } return p->p_offset + vaddr - p->p_vaddr; } } return vaddr; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_2901_0
crossvul-cpp_data_good_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) && hv_enabled; 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(&reg, argp, sizeof(reg))) goto out; if (ioctl == KVM_SET_ONE_REG) r = kvm_vcpu_ioctl_set_one_reg(vcpu, &reg); else r = kvm_vcpu_ioctl_get_one_reg(vcpu, &reg); 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/good_2858_0
crossvul-cpp_data_good_1024_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. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } // This call should change the current thread to the selected user. // I didn't test it. if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); 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. */ 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: user name or password incorrect"); 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: user name or password incorrect"); 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 crypt_password = crypt(password, user_password); if (crypt_password == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } if (strcmp(user_password, crypt_password) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); 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-476/c/good_1024_0
crossvul-cpp_data_bad_3154_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * The IP to API glue. * * Authors: see ip.c * * Fixes: * Many : Split from ip.c , see ip.c for history. * Martin Mares : TOS setting fixed. * Alan Cox : Fixed a couple of oopses in Martin's * TOS tweaks. * Mike McLagan : Routing by source */ #include <linux/module.h> #include <linux/types.h> #include <linux/mm.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <linux/icmp.h> #include <linux/inetdevice.h> #include <linux/netdevice.h> #include <linux/slab.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/tcp_states.h> #include <linux/udp.h> #include <linux/igmp.h> #include <linux/netfilter.h> #include <linux/route.h> #include <linux/mroute.h> #include <net/inet_ecn.h> #include <net/route.h> #include <net/xfrm.h> #include <net/compat.h> #include <net/checksum.h> #if IS_ENABLED(CONFIG_IPV6) #include <net/transp_v6.h> #endif #include <net/ip_fib.h> #include <linux/errqueue.h> #include <linux/uaccess.h> /* * SOL_IP control messages. */ static void ip_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb) { struct in_pktinfo info = *PKTINFO_SKB_CB(skb); info.ipi_addr.s_addr = ip_hdr(skb)->daddr; put_cmsg(msg, SOL_IP, IP_PKTINFO, sizeof(info), &info); } static void ip_cmsg_recv_ttl(struct msghdr *msg, struct sk_buff *skb) { int ttl = ip_hdr(skb)->ttl; put_cmsg(msg, SOL_IP, IP_TTL, sizeof(int), &ttl); } static void ip_cmsg_recv_tos(struct msghdr *msg, struct sk_buff *skb) { put_cmsg(msg, SOL_IP, IP_TOS, 1, &ip_hdr(skb)->tos); } static void ip_cmsg_recv_opts(struct msghdr *msg, struct sk_buff *skb) { if (IPCB(skb)->opt.optlen == 0) return; put_cmsg(msg, SOL_IP, IP_RECVOPTS, IPCB(skb)->opt.optlen, ip_hdr(skb) + 1); } static void ip_cmsg_recv_retopts(struct msghdr *msg, struct sk_buff *skb) { unsigned char optbuf[sizeof(struct ip_options) + 40]; struct ip_options *opt = (struct ip_options *)optbuf; if (IPCB(skb)->opt.optlen == 0) return; if (ip_options_echo(opt, skb)) { msg->msg_flags |= MSG_CTRUNC; return; } ip_options_undo(opt); put_cmsg(msg, SOL_IP, IP_RETOPTS, opt->optlen, opt->__data); } static void ip_cmsg_recv_fragsize(struct msghdr *msg, struct sk_buff *skb) { int val; if (IPCB(skb)->frag_max_size == 0) return; val = IPCB(skb)->frag_max_size; put_cmsg(msg, SOL_IP, IP_RECVFRAGSIZE, sizeof(val), &val); } static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) csum = csum_sub(csum, csum_partial(skb_transport_header(skb) + tlen, offset, 0)); put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); } static void ip_cmsg_recv_security(struct msghdr *msg, struct sk_buff *skb) { char *secdata; u32 seclen, secid; int err; err = security_socket_getpeersec_dgram(NULL, skb, &secid); if (err) return; err = security_secid_to_secctx(secid, &secdata, &seclen); if (err) return; put_cmsg(msg, SOL_IP, SCM_SECURITY, seclen, secdata); security_release_secctx(secdata, seclen); } static void ip_cmsg_recv_dstaddr(struct msghdr *msg, struct sk_buff *skb) { struct sockaddr_in sin; const struct iphdr *iph = ip_hdr(skb); __be16 *ports = (__be16 *)skb_transport_header(skb); if (skb_transport_offset(skb) + 4 > (int)skb->len) return; /* All current transport protocols have the port numbers in the * first four bytes of the transport header and this function is * written with this assumption in mind. */ sin.sin_family = AF_INET; sin.sin_addr.s_addr = iph->daddr; sin.sin_port = ports[1]; memset(sin.sin_zero, 0, sizeof(sin.sin_zero)); put_cmsg(msg, SOL_IP, IP_ORIGDSTADDR, sizeof(sin), &sin); } void ip_cmsg_recv_offset(struct msghdr *msg, struct sock *sk, struct sk_buff *skb, int tlen, int offset) { struct inet_sock *inet = inet_sk(sk); unsigned int flags = inet->cmsg_flags; /* Ordered by supposed usage frequency */ if (flags & IP_CMSG_PKTINFO) { ip_cmsg_recv_pktinfo(msg, skb); flags &= ~IP_CMSG_PKTINFO; if (!flags) return; } if (flags & IP_CMSG_TTL) { ip_cmsg_recv_ttl(msg, skb); flags &= ~IP_CMSG_TTL; if (!flags) return; } if (flags & IP_CMSG_TOS) { ip_cmsg_recv_tos(msg, skb); flags &= ~IP_CMSG_TOS; if (!flags) return; } if (flags & IP_CMSG_RECVOPTS) { ip_cmsg_recv_opts(msg, skb); flags &= ~IP_CMSG_RECVOPTS; if (!flags) return; } if (flags & IP_CMSG_RETOPTS) { ip_cmsg_recv_retopts(msg, skb); flags &= ~IP_CMSG_RETOPTS; if (!flags) return; } if (flags & IP_CMSG_PASSSEC) { ip_cmsg_recv_security(msg, skb); flags &= ~IP_CMSG_PASSSEC; if (!flags) return; } if (flags & IP_CMSG_ORIGDSTADDR) { ip_cmsg_recv_dstaddr(msg, skb); flags &= ~IP_CMSG_ORIGDSTADDR; if (!flags) return; } if (flags & IP_CMSG_CHECKSUM) ip_cmsg_recv_checksum(msg, skb, tlen, offset); if (flags & IP_CMSG_RECVFRAGSIZE) ip_cmsg_recv_fragsize(msg, skb); } EXPORT_SYMBOL(ip_cmsg_recv_offset); int ip_cmsg_send(struct sock *sk, struct msghdr *msg, struct ipcm_cookie *ipc, bool allow_ipv6) { int err, val; struct cmsghdr *cmsg; struct net *net = sock_net(sk); for_each_cmsghdr(cmsg, msg) { if (!CMSG_OK(msg, cmsg)) return -EINVAL; #if IS_ENABLED(CONFIG_IPV6) if (allow_ipv6 && cmsg->cmsg_level == SOL_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) { struct in6_pktinfo *src_info; if (cmsg->cmsg_len < CMSG_LEN(sizeof(*src_info))) return -EINVAL; src_info = (struct in6_pktinfo *)CMSG_DATA(cmsg); if (!ipv6_addr_v4mapped(&src_info->ipi6_addr)) return -EINVAL; ipc->oif = src_info->ipi6_ifindex; ipc->addr = src_info->ipi6_addr.s6_addr32[3]; continue; } #endif if (cmsg->cmsg_level == SOL_SOCKET) { err = __sock_cmsg_send(sk, msg, cmsg, &ipc->sockc); if (err) return err; continue; } if (cmsg->cmsg_level != SOL_IP) continue; switch (cmsg->cmsg_type) { case IP_RETOPTS: err = cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)); /* Our caller is responsible for freeing ipc->opt */ err = ip_options_get(net, &ipc->opt, CMSG_DATA(cmsg), err < 40 ? err : 40); if (err) return err; break; case IP_PKTINFO: { struct in_pktinfo *info; if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct in_pktinfo))) return -EINVAL; info = (struct in_pktinfo *)CMSG_DATA(cmsg); ipc->oif = info->ipi_ifindex; ipc->addr = info->ipi_spec_dst.s_addr; break; } case IP_TTL: if (cmsg->cmsg_len != CMSG_LEN(sizeof(int))) return -EINVAL; val = *(int *)CMSG_DATA(cmsg); if (val < 1 || val > 255) return -EINVAL; ipc->ttl = val; break; case IP_TOS: if (cmsg->cmsg_len == CMSG_LEN(sizeof(int))) val = *(int *)CMSG_DATA(cmsg); else if (cmsg->cmsg_len == CMSG_LEN(sizeof(u8))) val = *(u8 *)CMSG_DATA(cmsg); else return -EINVAL; if (val < 0 || val > 255) return -EINVAL; ipc->tos = val; ipc->priority = rt_tos2priority(ipc->tos); break; default: return -EINVAL; } } return 0; } /* Special input handler for packets caught by router alert option. They are selected only by protocol field, and then processed likely local ones; but only if someone wants them! Otherwise, router not running rsvpd will kill RSVP. It is user level problem, what it will make with them. I have no idea, how it will masquearde or NAT them (it is joke, joke :-)), but receiver should be enough clever f.e. to forward mtrace requests, sent to multicast group to reach destination designated router. */ struct ip_ra_chain __rcu *ip_ra_chain; static DEFINE_SPINLOCK(ip_ra_lock); static void ip_ra_destroy_rcu(struct rcu_head *head) { struct ip_ra_chain *ra = container_of(head, struct ip_ra_chain, rcu); sock_put(ra->saved_sk); kfree(ra); } int ip_ra_control(struct sock *sk, unsigned char on, void (*destructor)(struct sock *)) { struct ip_ra_chain *ra, *new_ra; struct ip_ra_chain __rcu **rap; if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num == IPPROTO_RAW) return -EINVAL; new_ra = on ? kmalloc(sizeof(*new_ra), GFP_KERNEL) : NULL; spin_lock_bh(&ip_ra_lock); for (rap = &ip_ra_chain; (ra = rcu_dereference_protected(*rap, lockdep_is_held(&ip_ra_lock))) != NULL; rap = &ra->next) { if (ra->sk == sk) { if (on) { spin_unlock_bh(&ip_ra_lock); kfree(new_ra); return -EADDRINUSE; } /* dont let ip_call_ra_chain() use sk again */ ra->sk = NULL; RCU_INIT_POINTER(*rap, ra->next); spin_unlock_bh(&ip_ra_lock); if (ra->destructor) ra->destructor(sk); /* * Delay sock_put(sk) and kfree(ra) after one rcu grace * period. This guarantee ip_call_ra_chain() dont need * to mess with socket refcounts. */ ra->saved_sk = sk; call_rcu(&ra->rcu, ip_ra_destroy_rcu); return 0; } } if (!new_ra) { spin_unlock_bh(&ip_ra_lock); return -ENOBUFS; } new_ra->sk = sk; new_ra->destructor = destructor; RCU_INIT_POINTER(new_ra->next, ra); rcu_assign_pointer(*rap, new_ra); sock_hold(sk); spin_unlock_bh(&ip_ra_lock); return 0; } void ip_icmp_error(struct sock *sk, struct sk_buff *skb, int err, __be16 port, u32 info, u8 *payload) { struct sock_exterr_skb *serr; skb = skb_clone(skb, GFP_ATOMIC); if (!skb) return; serr = SKB_EXT_ERR(skb); serr->ee.ee_errno = err; serr->ee.ee_origin = SO_EE_ORIGIN_ICMP; serr->ee.ee_type = icmp_hdr(skb)->type; serr->ee.ee_code = icmp_hdr(skb)->code; serr->ee.ee_pad = 0; serr->ee.ee_info = info; serr->ee.ee_data = 0; serr->addr_offset = (u8 *)&(((struct iphdr *)(icmp_hdr(skb) + 1))->daddr) - skb_network_header(skb); serr->port = port; if (skb_pull(skb, payload - skb->data)) { skb_reset_transport_header(skb); if (sock_queue_err_skb(sk, skb) == 0) return; } kfree_skb(skb); } void ip_local_error(struct sock *sk, int err, __be32 daddr, __be16 port, u32 info) { struct inet_sock *inet = inet_sk(sk); struct sock_exterr_skb *serr; struct iphdr *iph; struct sk_buff *skb; if (!inet->recverr) return; skb = alloc_skb(sizeof(struct iphdr), GFP_ATOMIC); if (!skb) return; skb_put(skb, sizeof(struct iphdr)); skb_reset_network_header(skb); iph = ip_hdr(skb); iph->daddr = daddr; serr = SKB_EXT_ERR(skb); serr->ee.ee_errno = err; serr->ee.ee_origin = SO_EE_ORIGIN_LOCAL; serr->ee.ee_type = 0; serr->ee.ee_code = 0; serr->ee.ee_pad = 0; serr->ee.ee_info = info; serr->ee.ee_data = 0; serr->addr_offset = (u8 *)&iph->daddr - skb_network_header(skb); serr->port = port; __skb_pull(skb, skb_tail_pointer(skb) - skb->data); skb_reset_transport_header(skb); if (sock_queue_err_skb(sk, skb)) kfree_skb(skb); } /* For some errors we have valid addr_offset even with zero payload and * zero port. Also, addr_offset should be supported if port is set. */ static inline bool ipv4_datagram_support_addr(struct sock_exterr_skb *serr) { return serr->ee.ee_origin == SO_EE_ORIGIN_ICMP || serr->ee.ee_origin == SO_EE_ORIGIN_LOCAL || serr->port; } /* IPv4 supports cmsg on all imcp errors and some timestamps * * Timestamp code paths do not initialize the fields expected by cmsg: * the PKTINFO fields in skb->cb[]. Fill those in here. */ static bool ipv4_datagram_support_cmsg(const struct sock *sk, struct sk_buff *skb, int ee_origin) { struct in_pktinfo *info; if (ee_origin == SO_EE_ORIGIN_ICMP) return true; if (ee_origin == SO_EE_ORIGIN_LOCAL) return false; /* Support IP_PKTINFO on tstamp packets if requested, to correlate * timestamp with egress dev. Not possible for packets without dev * or without payload (SOF_TIMESTAMPING_OPT_TSONLY). */ if ((!(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_CMSG)) || (!skb->dev)) return false; info = PKTINFO_SKB_CB(skb); info->ipi_spec_dst.s_addr = ip_hdr(skb)->saddr; info->ipi_ifindex = skb->dev->ifindex; return true; } /* * Handle MSG_ERRQUEUE */ int ip_recv_error(struct sock *sk, struct msghdr *msg, int len, int *addr_len) { struct sock_exterr_skb *serr; struct sk_buff *skb; DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct { struct sock_extended_err ee; struct sockaddr_in offender; } errhdr; int err; int copied; WARN_ON_ONCE(sk->sk_family == AF_INET6); err = -EAGAIN; skb = sock_dequeue_err_skb(sk); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_msg(skb, 0, msg, copied); if (unlikely(err)) { kfree_skb(skb); return err; } sock_recv_timestamp(msg, sk, skb); serr = SKB_EXT_ERR(skb); if (sin && ipv4_datagram_support_addr(serr)) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = *(__be32 *)(skb_network_header(skb) + serr->addr_offset); sin->sin_port = serr->port; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } memcpy(&errhdr.ee, &serr->ee, sizeof(struct sock_extended_err)); sin = &errhdr.offender; memset(sin, 0, sizeof(*sin)); if (ipv4_datagram_support_cmsg(sk, skb, serr->ee.ee_origin)) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; if (inet_sk(sk)->cmsg_flags) ip_cmsg_recv(msg, skb); } put_cmsg(msg, SOL_IP, IP_RECVERR, sizeof(errhdr), &errhdr); /* Now we could try to dump offended packet options */ msg->msg_flags |= MSG_ERRQUEUE; err = copied; consume_skb(skb); out: return err; } /* * Socket option code for IP. This is the end of the line after any * TCP,UDP etc options on an IP socket. */ static bool setsockopt_needs_rtnl(int optname) { switch (optname) { case IP_ADD_MEMBERSHIP: case IP_ADD_SOURCE_MEMBERSHIP: case IP_BLOCK_SOURCE: case IP_DROP_MEMBERSHIP: case IP_DROP_SOURCE_MEMBERSHIP: case IP_MSFILTER: case IP_UNBLOCK_SOURCE: case MCAST_BLOCK_SOURCE: case MCAST_MSFILTER: case MCAST_JOIN_GROUP: case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_UNBLOCK_SOURCE: return true; } return false; } static int do_ip_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); int val = 0, err; bool needs_rtnl = setsockopt_needs_rtnl(optname); switch (optname) { case IP_PKTINFO: case IP_RECVTTL: case IP_RECVOPTS: case IP_RECVTOS: case IP_RETOPTS: case IP_TOS: case IP_TTL: case IP_HDRINCL: case IP_MTU_DISCOVER: case IP_RECVERR: case IP_ROUTER_ALERT: case IP_FREEBIND: case IP_PASSSEC: case IP_TRANSPARENT: case IP_MINTTL: case IP_NODEFRAG: case IP_BIND_ADDRESS_NO_PORT: case IP_UNICAST_IF: case IP_MULTICAST_TTL: case IP_MULTICAST_ALL: case IP_MULTICAST_LOOP: case IP_RECVORIGDSTADDR: case IP_CHECKSUM: case IP_RECVFRAGSIZE: if (optlen >= sizeof(int)) { if (get_user(val, (int __user *) optval)) return -EFAULT; } else if (optlen >= sizeof(char)) { unsigned char ucval; if (get_user(ucval, (unsigned char __user *) optval)) return -EFAULT; val = (int) ucval; } } /* If optlen==0, it is equivalent to val == 0 */ if (ip_mroute_opt(optname)) return ip_mroute_setsockopt(sk, optname, optval, optlen); err = 0; if (needs_rtnl) rtnl_lock(); lock_sock(sk); switch (optname) { case IP_OPTIONS: { struct ip_options_rcu *old, *opt = NULL; if (optlen > 40) goto e_inval; err = ip_options_get_from_user(sock_net(sk), &opt, optval, optlen); if (err) break; old = rcu_dereference_protected(inet->inet_opt, lockdep_sock_is_held(sk)); if (inet->is_icsk) { struct inet_connection_sock *icsk = inet_csk(sk); #if IS_ENABLED(CONFIG_IPV6) if (sk->sk_family == PF_INET || (!((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) && inet->inet_daddr != LOOPBACK4_IPV6)) { #endif if (old) icsk->icsk_ext_hdr_len -= old->opt.optlen; if (opt) icsk->icsk_ext_hdr_len += opt->opt.optlen; icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie); #if IS_ENABLED(CONFIG_IPV6) } #endif } rcu_assign_pointer(inet->inet_opt, opt); if (old) kfree_rcu(old, rcu); break; } case IP_PKTINFO: if (val) inet->cmsg_flags |= IP_CMSG_PKTINFO; else inet->cmsg_flags &= ~IP_CMSG_PKTINFO; break; case IP_RECVTTL: if (val) inet->cmsg_flags |= IP_CMSG_TTL; else inet->cmsg_flags &= ~IP_CMSG_TTL; break; case IP_RECVTOS: if (val) inet->cmsg_flags |= IP_CMSG_TOS; else inet->cmsg_flags &= ~IP_CMSG_TOS; break; case IP_RECVOPTS: if (val) inet->cmsg_flags |= IP_CMSG_RECVOPTS; else inet->cmsg_flags &= ~IP_CMSG_RECVOPTS; break; case IP_RETOPTS: if (val) inet->cmsg_flags |= IP_CMSG_RETOPTS; else inet->cmsg_flags &= ~IP_CMSG_RETOPTS; break; case IP_PASSSEC: if (val) inet->cmsg_flags |= IP_CMSG_PASSSEC; else inet->cmsg_flags &= ~IP_CMSG_PASSSEC; break; case IP_RECVORIGDSTADDR: if (val) inet->cmsg_flags |= IP_CMSG_ORIGDSTADDR; else inet->cmsg_flags &= ~IP_CMSG_ORIGDSTADDR; break; case IP_CHECKSUM: if (val) { if (!(inet->cmsg_flags & IP_CMSG_CHECKSUM)) { inet_inc_convert_csum(sk); inet->cmsg_flags |= IP_CMSG_CHECKSUM; } } else { if (inet->cmsg_flags & IP_CMSG_CHECKSUM) { inet_dec_convert_csum(sk); inet->cmsg_flags &= ~IP_CMSG_CHECKSUM; } } break; case IP_RECVFRAGSIZE: if (sk->sk_type != SOCK_RAW && sk->sk_type != SOCK_DGRAM) goto e_inval; if (val) inet->cmsg_flags |= IP_CMSG_RECVFRAGSIZE; else inet->cmsg_flags &= ~IP_CMSG_RECVFRAGSIZE; break; case IP_TOS: /* This sets both TOS and Precedence */ if (sk->sk_type == SOCK_STREAM) { val &= ~INET_ECN_MASK; val |= inet->tos & INET_ECN_MASK; } if (inet->tos != val) { inet->tos = val; sk->sk_priority = rt_tos2priority(val); sk_dst_reset(sk); } break; case IP_TTL: if (optlen < 1) goto e_inval; if (val != -1 && (val < 1 || val > 255)) goto e_inval; inet->uc_ttl = val; break; case IP_HDRINCL: if (sk->sk_type != SOCK_RAW) { err = -ENOPROTOOPT; break; } inet->hdrincl = val ? 1 : 0; break; case IP_NODEFRAG: if (sk->sk_type != SOCK_RAW) { err = -ENOPROTOOPT; break; } inet->nodefrag = val ? 1 : 0; break; case IP_BIND_ADDRESS_NO_PORT: inet->bind_address_no_port = val ? 1 : 0; break; case IP_MTU_DISCOVER: if (val < IP_PMTUDISC_DONT || val > IP_PMTUDISC_OMIT) goto e_inval; inet->pmtudisc = val; break; case IP_RECVERR: inet->recverr = !!val; if (!val) skb_queue_purge(&sk->sk_error_queue); break; case IP_MULTICAST_TTL: if (sk->sk_type == SOCK_STREAM) goto e_inval; if (optlen < 1) goto e_inval; if (val == -1) val = 1; if (val < 0 || val > 255) goto e_inval; inet->mc_ttl = val; break; case IP_MULTICAST_LOOP: if (optlen < 1) goto e_inval; inet->mc_loop = !!val; break; case IP_UNICAST_IF: { struct net_device *dev = NULL; int ifindex; if (optlen != sizeof(int)) goto e_inval; ifindex = (__force int)ntohl((__force __be32)val); if (ifindex == 0) { inet->uc_index = 0; err = 0; break; } dev = dev_get_by_index(sock_net(sk), ifindex); err = -EADDRNOTAVAIL; if (!dev) break; dev_put(dev); err = -EINVAL; if (sk->sk_bound_dev_if) break; inet->uc_index = ifindex; err = 0; break; } case IP_MULTICAST_IF: { struct ip_mreqn mreq; struct net_device *dev = NULL; if (sk->sk_type == SOCK_STREAM) goto e_inval; /* * Check the arguments are allowable */ if (optlen < sizeof(struct in_addr)) goto e_inval; err = -EFAULT; if (optlen >= sizeof(struct ip_mreqn)) { if (copy_from_user(&mreq, optval, sizeof(mreq))) break; } else { memset(&mreq, 0, sizeof(mreq)); if (optlen >= sizeof(struct ip_mreq)) { if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq))) break; } else if (optlen >= sizeof(struct in_addr)) { if (copy_from_user(&mreq.imr_address, optval, sizeof(struct in_addr))) break; } } if (!mreq.imr_ifindex) { if (mreq.imr_address.s_addr == htonl(INADDR_ANY)) { inet->mc_index = 0; inet->mc_addr = 0; err = 0; break; } dev = ip_dev_find(sock_net(sk), mreq.imr_address.s_addr); if (dev) mreq.imr_ifindex = dev->ifindex; } else dev = dev_get_by_index(sock_net(sk), mreq.imr_ifindex); err = -EADDRNOTAVAIL; if (!dev) break; dev_put(dev); err = -EINVAL; if (sk->sk_bound_dev_if && mreq.imr_ifindex != sk->sk_bound_dev_if) break; inet->mc_index = mreq.imr_ifindex; inet->mc_addr = mreq.imr_address.s_addr; err = 0; break; } case IP_ADD_MEMBERSHIP: case IP_DROP_MEMBERSHIP: { struct ip_mreqn mreq; err = -EPROTO; if (inet_sk(sk)->is_icsk) break; if (optlen < sizeof(struct ip_mreq)) goto e_inval; err = -EFAULT; if (optlen >= sizeof(struct ip_mreqn)) { if (copy_from_user(&mreq, optval, sizeof(mreq))) break; } else { memset(&mreq, 0, sizeof(mreq)); if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq))) break; } if (optname == IP_ADD_MEMBERSHIP) err = ip_mc_join_group(sk, &mreq); else err = ip_mc_leave_group(sk, &mreq); break; } case IP_MSFILTER: { struct ip_msfilter *msf; if (optlen < IP_MSFILTER_SIZE(0)) goto e_inval; if (optlen > sysctl_optmem_max) { err = -ENOBUFS; break; } msf = kmalloc(optlen, GFP_KERNEL); if (!msf) { err = -ENOBUFS; break; } err = -EFAULT; if (copy_from_user(msf, optval, optlen)) { kfree(msf); break; } /* numsrc >= (1G-4) overflow in 32 bits */ if (msf->imsf_numsrc >= 0x3ffffffcU || msf->imsf_numsrc > net->ipv4.sysctl_igmp_max_msf) { kfree(msf); err = -ENOBUFS; break; } if (IP_MSFILTER_SIZE(msf->imsf_numsrc) > optlen) { kfree(msf); err = -EINVAL; break; } err = ip_mc_msfilter(sk, msf, 0); kfree(msf); break; } case IP_BLOCK_SOURCE: case IP_UNBLOCK_SOURCE: case IP_ADD_SOURCE_MEMBERSHIP: case IP_DROP_SOURCE_MEMBERSHIP: { struct ip_mreq_source mreqs; int omode, add; if (optlen != sizeof(struct ip_mreq_source)) goto e_inval; if (copy_from_user(&mreqs, optval, sizeof(mreqs))) { err = -EFAULT; break; } if (optname == IP_BLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 1; } else if (optname == IP_UNBLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 0; } else if (optname == IP_ADD_SOURCE_MEMBERSHIP) { struct ip_mreqn mreq; mreq.imr_multiaddr.s_addr = mreqs.imr_multiaddr; mreq.imr_address.s_addr = mreqs.imr_interface; mreq.imr_ifindex = 0; err = ip_mc_join_group(sk, &mreq); if (err && err != -EADDRINUSE) break; omode = MCAST_INCLUDE; add = 1; } else /* IP_DROP_SOURCE_MEMBERSHIP */ { omode = MCAST_INCLUDE; add = 0; } err = ip_mc_source(add, omode, sk, &mreqs, 0); break; } case MCAST_JOIN_GROUP: case MCAST_LEAVE_GROUP: { struct group_req greq; struct sockaddr_in *psin; struct ip_mreqn mreq; if (optlen < sizeof(struct group_req)) goto e_inval; err = -EFAULT; if (copy_from_user(&greq, optval, sizeof(greq))) break; psin = (struct sockaddr_in *)&greq.gr_group; if (psin->sin_family != AF_INET) goto e_inval; memset(&mreq, 0, sizeof(mreq)); mreq.imr_multiaddr = psin->sin_addr; mreq.imr_ifindex = greq.gr_interface; if (optname == MCAST_JOIN_GROUP) err = ip_mc_join_group(sk, &mreq); else err = ip_mc_leave_group(sk, &mreq); break; } case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_BLOCK_SOURCE: case MCAST_UNBLOCK_SOURCE: { struct group_source_req greqs; struct ip_mreq_source mreqs; struct sockaddr_in *psin; int omode, add; if (optlen != sizeof(struct group_source_req)) goto e_inval; if (copy_from_user(&greqs, optval, sizeof(greqs))) { err = -EFAULT; break; } if (greqs.gsr_group.ss_family != AF_INET || greqs.gsr_source.ss_family != AF_INET) { err = -EADDRNOTAVAIL; break; } psin = (struct sockaddr_in *)&greqs.gsr_group; mreqs.imr_multiaddr = psin->sin_addr.s_addr; psin = (struct sockaddr_in *)&greqs.gsr_source; mreqs.imr_sourceaddr = psin->sin_addr.s_addr; mreqs.imr_interface = 0; /* use index for mc_source */ if (optname == MCAST_BLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 1; } else if (optname == MCAST_UNBLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 0; } else if (optname == MCAST_JOIN_SOURCE_GROUP) { struct ip_mreqn mreq; psin = (struct sockaddr_in *)&greqs.gsr_group; mreq.imr_multiaddr = psin->sin_addr; mreq.imr_address.s_addr = 0; mreq.imr_ifindex = greqs.gsr_interface; err = ip_mc_join_group(sk, &mreq); if (err && err != -EADDRINUSE) break; greqs.gsr_interface = mreq.imr_ifindex; omode = MCAST_INCLUDE; add = 1; } else /* MCAST_LEAVE_SOURCE_GROUP */ { omode = MCAST_INCLUDE; add = 0; } err = ip_mc_source(add, omode, sk, &mreqs, greqs.gsr_interface); break; } case MCAST_MSFILTER: { struct sockaddr_in *psin; struct ip_msfilter *msf = NULL; struct group_filter *gsf = NULL; int msize, i, ifindex; if (optlen < GROUP_FILTER_SIZE(0)) goto e_inval; if (optlen > sysctl_optmem_max) { err = -ENOBUFS; break; } gsf = kmalloc(optlen, GFP_KERNEL); if (!gsf) { err = -ENOBUFS; break; } err = -EFAULT; if (copy_from_user(gsf, optval, optlen)) goto mc_msf_out; /* numsrc >= (4G-140)/128 overflow in 32 bits */ if (gsf->gf_numsrc >= 0x1ffffff || gsf->gf_numsrc > net->ipv4.sysctl_igmp_max_msf) { err = -ENOBUFS; goto mc_msf_out; } if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) { err = -EINVAL; goto mc_msf_out; } msize = IP_MSFILTER_SIZE(gsf->gf_numsrc); msf = kmalloc(msize, GFP_KERNEL); if (!msf) { err = -ENOBUFS; goto mc_msf_out; } ifindex = gsf->gf_interface; psin = (struct sockaddr_in *)&gsf->gf_group; if (psin->sin_family != AF_INET) { err = -EADDRNOTAVAIL; goto mc_msf_out; } msf->imsf_multiaddr = psin->sin_addr.s_addr; msf->imsf_interface = 0; msf->imsf_fmode = gsf->gf_fmode; msf->imsf_numsrc = gsf->gf_numsrc; err = -EADDRNOTAVAIL; for (i = 0; i < gsf->gf_numsrc; ++i) { psin = (struct sockaddr_in *)&gsf->gf_slist[i]; if (psin->sin_family != AF_INET) goto mc_msf_out; msf->imsf_slist[i] = psin->sin_addr.s_addr; } kfree(gsf); gsf = NULL; err = ip_mc_msfilter(sk, msf, ifindex); mc_msf_out: kfree(msf); kfree(gsf); break; } case IP_MULTICAST_ALL: if (optlen < 1) goto e_inval; if (val != 0 && val != 1) goto e_inval; inet->mc_all = val; break; case IP_ROUTER_ALERT: err = ip_ra_control(sk, val ? 1 : 0, NULL); break; case IP_FREEBIND: if (optlen < 1) goto e_inval; inet->freebind = !!val; break; case IP_IPSEC_POLICY: case IP_XFRM_POLICY: err = -EPERM; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) break; err = xfrm_user_policy(sk, optname, optval, optlen); break; case IP_TRANSPARENT: if (!!val && !ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) && !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) { err = -EPERM; break; } if (optlen < 1) goto e_inval; inet->transparent = !!val; break; case IP_MINTTL: if (optlen < 1) goto e_inval; if (val < 0 || val > 255) goto e_inval; inet->min_ttl = val; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); if (needs_rtnl) rtnl_unlock(); return err; e_inval: release_sock(sk); if (needs_rtnl) rtnl_unlock(); return -EINVAL; } /** * ipv4_pktinfo_prepare - transfer some info from rtable to skb * @sk: socket * @skb: buffer * * To support IP_CMSG_PKTINFO option, we store rt_iif and specific * destination in skb->cb[] before dst drop. * This way, receiver doesn't make cache line misses to read rtable. */ void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb) { struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb); bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) || ipv6_sk_rxinfo(sk); if (prepare && skb_rtable(skb)) { /* skb->cb is overloaded: prior to this point it is IP{6}CB * which has interface index (iif) as the first member of the * underlying inet{6}_skb_parm struct. This code then overlays * PKTINFO_SKB_CB and in_pktinfo also has iif as the first * element so the iif is picked up from the prior IPCB. If iif * is the loopback interface, then return the sending interface * (e.g., process binds socket to eth0 for Tx which is * redirected to loopback in the rtable/dst). */ if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX) pktinfo->ipi_ifindex = inet_iif(skb); pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb); } else { pktinfo->ipi_ifindex = 0; pktinfo->ipi_spec_dst.s_addr = 0; } skb_dst_drop(skb); } int ip_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { int err; if (level != SOL_IP) return -ENOPROTOOPT; err = do_ip_setsockopt(sk, level, optname, optval, optlen); #ifdef CONFIG_NETFILTER /* we need to exclude all possible ENOPROTOOPTs except default case */ if (err == -ENOPROTOOPT && optname != IP_HDRINCL && optname != IP_IPSEC_POLICY && optname != IP_XFRM_POLICY && !ip_mroute_opt(optname)) { lock_sock(sk); err = nf_setsockopt(sk, PF_INET, optname, optval, optlen); release_sock(sk); } #endif return err; } EXPORT_SYMBOL(ip_setsockopt); #ifdef CONFIG_COMPAT int compat_ip_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { int err; if (level != SOL_IP) return -ENOPROTOOPT; if (optname >= MCAST_JOIN_GROUP && optname <= MCAST_MSFILTER) return compat_mc_setsockopt(sk, level, optname, optval, optlen, ip_setsockopt); err = do_ip_setsockopt(sk, level, optname, optval, optlen); #ifdef CONFIG_NETFILTER /* we need to exclude all possible ENOPROTOOPTs except default case */ if (err == -ENOPROTOOPT && optname != IP_HDRINCL && optname != IP_IPSEC_POLICY && optname != IP_XFRM_POLICY && !ip_mroute_opt(optname)) { lock_sock(sk); err = compat_nf_setsockopt(sk, PF_INET, optname, optval, optlen); release_sock(sk); } #endif return err; } EXPORT_SYMBOL(compat_ip_setsockopt); #endif /* * Get the options. Note for future reference. The GET of IP options gets * the _received_ ones. The set sets the _sent_ ones. */ static bool getsockopt_needs_rtnl(int optname) { switch (optname) { case IP_MSFILTER: case MCAST_MSFILTER: return true; } return false; } static int do_ip_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen, unsigned int flags) { struct inet_sock *inet = inet_sk(sk); bool needs_rtnl = getsockopt_needs_rtnl(optname); int val, err = 0; int len; if (level != SOL_IP) return -EOPNOTSUPP; if (ip_mroute_opt(optname)) return ip_mroute_getsockopt(sk, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; if (needs_rtnl) rtnl_lock(); lock_sock(sk); switch (optname) { case IP_OPTIONS: { unsigned char optbuf[sizeof(struct ip_options)+40]; struct ip_options *opt = (struct ip_options *)optbuf; struct ip_options_rcu *inet_opt; inet_opt = rcu_dereference_protected(inet->inet_opt, lockdep_sock_is_held(sk)); opt->optlen = 0; if (inet_opt) memcpy(optbuf, &inet_opt->opt, sizeof(struct ip_options) + inet_opt->opt.optlen); release_sock(sk); if (opt->optlen == 0) return put_user(0, optlen); ip_options_undo(opt); len = min_t(unsigned int, len, opt->optlen); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, opt->__data, len)) return -EFAULT; return 0; } case IP_PKTINFO: val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0; break; case IP_RECVTTL: val = (inet->cmsg_flags & IP_CMSG_TTL) != 0; break; case IP_RECVTOS: val = (inet->cmsg_flags & IP_CMSG_TOS) != 0; break; case IP_RECVOPTS: val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0; break; case IP_RETOPTS: val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0; break; case IP_PASSSEC: val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0; break; case IP_RECVORIGDSTADDR: val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0; break; case IP_CHECKSUM: val = (inet->cmsg_flags & IP_CMSG_CHECKSUM) != 0; break; case IP_RECVFRAGSIZE: val = (inet->cmsg_flags & IP_CMSG_RECVFRAGSIZE) != 0; break; case IP_TOS: val = inet->tos; break; case IP_TTL: { struct net *net = sock_net(sk); val = (inet->uc_ttl == -1 ? net->ipv4.sysctl_ip_default_ttl : inet->uc_ttl); break; } case IP_HDRINCL: val = inet->hdrincl; break; case IP_NODEFRAG: val = inet->nodefrag; break; case IP_BIND_ADDRESS_NO_PORT: val = inet->bind_address_no_port; break; case IP_MTU_DISCOVER: val = inet->pmtudisc; break; case IP_MTU: { struct dst_entry *dst; val = 0; dst = sk_dst_get(sk); if (dst) { val = dst_mtu(dst); dst_release(dst); } if (!val) { release_sock(sk); return -ENOTCONN; } break; } case IP_RECVERR: val = inet->recverr; break; case IP_MULTICAST_TTL: val = inet->mc_ttl; break; case IP_MULTICAST_LOOP: val = inet->mc_loop; break; case IP_UNICAST_IF: val = (__force int)htonl((__u32) inet->uc_index); break; case IP_MULTICAST_IF: { struct in_addr addr; len = min_t(unsigned int, len, sizeof(struct in_addr)); addr.s_addr = inet->mc_addr; release_sock(sk); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &addr, len)) return -EFAULT; return 0; } case IP_MSFILTER: { struct ip_msfilter msf; if (len < IP_MSFILTER_SIZE(0)) { err = -EINVAL; goto out; } if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) { err = -EFAULT; goto out; } err = ip_mc_msfget(sk, &msf, (struct ip_msfilter __user *)optval, optlen); goto out; } case MCAST_MSFILTER: { struct group_filter gsf; if (len < GROUP_FILTER_SIZE(0)) { err = -EINVAL; goto out; } if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) { err = -EFAULT; goto out; } err = ip_mc_gsfget(sk, &gsf, (struct group_filter __user *)optval, optlen); goto out; } case IP_MULTICAST_ALL: val = inet->mc_all; break; case IP_PKTOPTIONS: { struct msghdr msg; release_sock(sk); if (sk->sk_type != SOCK_STREAM) return -ENOPROTOOPT; msg.msg_control = (__force void *) optval; msg.msg_controllen = len; msg.msg_flags = flags; if (inet->cmsg_flags & IP_CMSG_PKTINFO) { struct in_pktinfo info; info.ipi_addr.s_addr = inet->inet_rcv_saddr; info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr; info.ipi_ifindex = inet->mc_index; put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info); } if (inet->cmsg_flags & IP_CMSG_TTL) { int hlim = inet->mc_ttl; put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim); } if (inet->cmsg_flags & IP_CMSG_TOS) { int tos = inet->rcv_tos; put_cmsg(&msg, SOL_IP, IP_TOS, sizeof(tos), &tos); } len -= msg.msg_controllen; return put_user(len, optlen); } case IP_FREEBIND: val = inet->freebind; break; case IP_TRANSPARENT: val = inet->transparent; break; case IP_MINTTL: val = inet->min_ttl; break; default: release_sock(sk); return -ENOPROTOOPT; } release_sock(sk); if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) { unsigned char ucval = (unsigned char)val; len = 1; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &ucval, 1)) return -EFAULT; } else { len = min_t(unsigned int, sizeof(int), len); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; } return 0; out: release_sock(sk); if (needs_rtnl) rtnl_unlock(); return err; } int ip_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { int err; err = do_ip_getsockopt(sk, level, optname, optval, optlen, 0); #ifdef CONFIG_NETFILTER /* we need to exclude all possible ENOPROTOOPTs except default case */ if (err == -ENOPROTOOPT && optname != IP_PKTOPTIONS && !ip_mroute_opt(optname)) { int len; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); err = nf_getsockopt(sk, PF_INET, optname, optval, &len); release_sock(sk); if (err >= 0) err = put_user(len, optlen); return err; } #endif return err; } EXPORT_SYMBOL(ip_getsockopt); #ifdef CONFIG_COMPAT int compat_ip_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { int err; if (optname == MCAST_MSFILTER) return compat_mc_getsockopt(sk, level, optname, optval, optlen, ip_getsockopt); err = do_ip_getsockopt(sk, level, optname, optval, optlen, MSG_CMSG_COMPAT); #ifdef CONFIG_NETFILTER /* we need to exclude all possible ENOPROTOOPTs except default case */ if (err == -ENOPROTOOPT && optname != IP_PKTOPTIONS && !ip_mroute_opt(optname)) { int len; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); err = compat_nf_getsockopt(sk, PF_INET, optname, optval, &len); release_sock(sk); if (err >= 0) err = put_user(len, optlen); return err; } #endif return err; } EXPORT_SYMBOL(compat_ip_getsockopt); #endif
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3154_0
crossvul-cpp_data_good_4997_0
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* kdc/kdc_util.c - Utility functions for the KDC implementation */ /* * Copyright 1990,1991,2007,2008,2009 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Copyright (c) 2006-2008, Novell, 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 copyright holder's name is not 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. */ #include "k5-int.h" #include "kdc_util.h" #include "extern.h" #include <stdio.h> #include <ctype.h> #include <syslog.h> #include <kadm5/admin.h> #include "adm_proto.h" #include "net-server.h" #include <limits.h> #ifdef KRBCONF_VAGUE_ERRORS const int vague_errors = 1; #else const int vague_errors = 0; #endif static krb5_error_code kdc_rd_ap_req(kdc_realm_t *kdc_active_realm, krb5_ap_req *apreq, krb5_auth_context auth_context, krb5_db_entry **server, krb5_keyblock **tgskey); static krb5_error_code find_server_key(krb5_context, krb5_db_entry *, krb5_enctype, krb5_kvno, krb5_keyblock **, krb5_kvno *); /* * concatenate first two authdata arrays, returning an allocated replacement. * The replacement should be freed with krb5_free_authdata(). */ krb5_error_code concat_authorization_data(krb5_context context, krb5_authdata **first, krb5_authdata **second, krb5_authdata ***output) { register int i, j; register krb5_authdata **ptr, **retdata; /* count up the entries */ i = 0; if (first) for (ptr = first; *ptr; ptr++) i++; if (second) for (ptr = second; *ptr; ptr++) i++; retdata = (krb5_authdata **)malloc((i+1)*sizeof(*retdata)); if (!retdata) return ENOMEM; retdata[i] = 0; /* null-terminated array */ for (i = 0, j = 0, ptr = first; j < 2 ; ptr = second, j++) while (ptr && *ptr) { /* now walk & copy */ retdata[i] = (krb5_authdata *)malloc(sizeof(*retdata[i])); if (!retdata[i]) { krb5_free_authdata(context, retdata); return ENOMEM; } *retdata[i] = **ptr; if (!(retdata[i]->contents = (krb5_octet *)malloc(retdata[i]->length))) { free(retdata[i]); retdata[i] = 0; krb5_free_authdata(context, retdata); return ENOMEM; } memcpy(retdata[i]->contents, (*ptr)->contents, retdata[i]->length); ptr++; i++; } *output = retdata; return 0; } krb5_boolean is_local_principal(kdc_realm_t *kdc_active_realm, krb5_const_principal princ1) { return krb5_realm_compare(kdc_context, princ1, tgs_server); } /* * Returns TRUE if the kerberos principal is the name of a Kerberos ticket * service. */ krb5_boolean krb5_is_tgs_principal(krb5_const_principal principal) { if (krb5_princ_size(kdc_context, principal) != 2) return FALSE; if (data_eq_string(*krb5_princ_component(kdc_context, principal, 0), KRB5_TGS_NAME)) return TRUE; else return FALSE; } /* Returns TRUE if principal is the name of a cross-realm TGS. */ krb5_boolean is_cross_tgs_principal(krb5_const_principal principal) { if (!krb5_is_tgs_principal(principal)) return FALSE; if (!data_eq(*krb5_princ_component(kdc_context, principal, 1), *krb5_princ_realm(kdc_context, principal))) return TRUE; else return FALSE; } /* * given authentication data (provides seed for checksum), verify checksum * for source data. */ static krb5_error_code comp_cksum(krb5_context kcontext, krb5_data *source, krb5_ticket *ticket, krb5_checksum *his_cksum) { krb5_error_code retval; krb5_boolean valid; if (!krb5_c_valid_cksumtype(his_cksum->checksum_type)) return KRB5KDC_ERR_SUMTYPE_NOSUPP; /* must be collision proof */ if (!krb5_c_is_coll_proof_cksum(his_cksum->checksum_type)) return KRB5KRB_AP_ERR_INAPP_CKSUM; /* verify checksum */ if ((retval = krb5_c_verify_checksum(kcontext, ticket->enc_part2->session, KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM, source, his_cksum, &valid))) return(retval); if (!valid) return(KRB5KRB_AP_ERR_BAD_INTEGRITY); return(0); } /* If a header ticket is decrypted, *ticket_out is filled in even on error. */ krb5_error_code kdc_process_tgs_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, const krb5_fulladdr *from, krb5_data *pkt, krb5_ticket **ticket_out, krb5_db_entry **krbtgt_ptr, krb5_keyblock **tgskey, krb5_keyblock **subkey, krb5_pa_data **pa_tgs_req) { krb5_pa_data * tmppa; krb5_ap_req * apreq; krb5_error_code retval; krb5_authdata **authdata = NULL; krb5_data scratch1; krb5_data * scratch = NULL; krb5_boolean foreign_server = FALSE; krb5_auth_context auth_context = NULL; krb5_authenticator * authenticator = NULL; krb5_checksum * his_cksum = NULL; krb5_db_entry * krbtgt = NULL; krb5_ticket * ticket; *ticket_out = NULL; *krbtgt_ptr = NULL; *tgskey = NULL; tmppa = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_AP_REQ); if (!tmppa) return KRB5KDC_ERR_PADATA_TYPE_NOSUPP; scratch1.length = tmppa->length; scratch1.data = (char *)tmppa->contents; if ((retval = decode_krb5_ap_req(&scratch1, &apreq))) return retval; ticket = apreq->ticket; if (isflagset(apreq->ap_options, AP_OPTS_USE_SESSION_KEY) || isflagset(apreq->ap_options, AP_OPTS_MUTUAL_REQUIRED)) { krb5_klog_syslog(LOG_INFO, _("TGS_REQ: SESSION KEY or MUTUAL")); retval = KRB5KDC_ERR_POLICY; goto cleanup; } /* If the "server" principal in the ticket is not something in the local realm, then we must refuse to service the request if the client claims to be from the local realm. If we don't do this, then some other realm's nasty KDC can claim to be authenticating a client from our realm, and we'll give out tickets concurring with it! we set a flag here for checking below. */ foreign_server = !is_local_principal(kdc_active_realm, apreq->ticket->server); if ((retval = krb5_auth_con_init(kdc_context, &auth_context))) goto cleanup; /* Don't use a replay cache. */ if ((retval = krb5_auth_con_setflags(kdc_context, auth_context, 0))) goto cleanup; if ((retval = krb5_auth_con_setaddrs(kdc_context, auth_context, NULL, from->address)) ) goto cleanup_auth_context; retval = kdc_rd_ap_req(kdc_active_realm, apreq, auth_context, &krbtgt, tgskey); if (retval) goto cleanup_auth_context; /* "invalid flag" tickets can must be used to validate */ if (isflagset(ticket->enc_part2->flags, TKT_FLG_INVALID) && !isflagset(request->kdc_options, KDC_OPT_VALIDATE)) { retval = KRB5KRB_AP_ERR_TKT_INVALID; goto cleanup_auth_context; } if ((retval = krb5_auth_con_getrecvsubkey(kdc_context, auth_context, subkey))) goto cleanup_auth_context; if ((retval = krb5_auth_con_getauthenticator(kdc_context, auth_context, &authenticator))) goto cleanup_auth_context; retval = krb5_find_authdata(kdc_context, ticket->enc_part2->authorization_data, authenticator->authorization_data, KRB5_AUTHDATA_FX_ARMOR, &authdata); if (retval != 0) goto cleanup_authenticator; if (authdata&& authdata[0]) { k5_setmsg(kdc_context, KRB5KDC_ERR_POLICY, "ticket valid only as FAST armor"); retval = KRB5KDC_ERR_POLICY; krb5_free_authdata(kdc_context, authdata); goto cleanup_authenticator; } krb5_free_authdata(kdc_context, authdata); /* Check for a checksum */ if (!(his_cksum = authenticator->checksum)) { retval = KRB5KRB_AP_ERR_INAPP_CKSUM; goto cleanup_authenticator; } /* make sure the client is of proper lineage (see above) */ if (foreign_server && !krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER)) { if (is_local_principal(kdc_active_realm, ticket->enc_part2->client)) { /* someone in a foreign realm claiming to be local */ krb5_klog_syslog(LOG_INFO, _("PROCESS_TGS: failed lineage check")); retval = KRB5KDC_ERR_POLICY; goto cleanup_authenticator; } } /* * Check application checksum vs. tgs request * * We try checksumming the req-body two different ways: first we * try reaching into the raw asn.1 stream (if available), and * checksum that directly; if that fails, then we try encoding * using our local asn.1 library. */ if (pkt && (fetch_asn1_field((unsigned char *) pkt->data, 1, 4, &scratch1) >= 0)) { if (comp_cksum(kdc_context, &scratch1, ticket, his_cksum)) { if (!(retval = encode_krb5_kdc_req_body(request, &scratch))) retval = comp_cksum(kdc_context, scratch, ticket, his_cksum); krb5_free_data(kdc_context, scratch); if (retval) goto cleanup_authenticator; } } *pa_tgs_req = tmppa; *krbtgt_ptr = krbtgt; krbtgt = NULL; cleanup_authenticator: krb5_free_authenticator(kdc_context, authenticator); cleanup_auth_context: krb5_auth_con_free(kdc_context, auth_context); cleanup: if (retval != 0) { krb5_free_keyblock(kdc_context, *tgskey); *tgskey = NULL; } if (apreq->ticket->enc_part2 != NULL) { /* Steal the decrypted ticket pointer, even on error. */ *ticket_out = apreq->ticket; apreq->ticket = NULL; } krb5_free_ap_req(kdc_context, apreq); krb5_db_free_principal(kdc_context, krbtgt); return retval; } /* * This is a KDC wrapper around krb5_rd_req_decoded_anyflag(). * * We can't depend on KDB-as-keytab for handling the AP-REQ here for * optimization reasons: we want to minimize the number of KDB lookups. We'll * need the KDB entry for the TGS principal, and the TGS key used to decrypt * the TGT, elsewhere in the TGS code. * * This function also implements key rollover support for kvno 0 cross-realm * TGTs issued by AD. */ static krb5_error_code kdc_rd_ap_req(kdc_realm_t *kdc_active_realm, krb5_ap_req *apreq, krb5_auth_context auth_context, krb5_db_entry **server, krb5_keyblock **tgskey) { krb5_error_code retval; krb5_enctype search_enctype = apreq->ticket->enc_part.enctype; krb5_boolean match_enctype = 1; krb5_kvno kvno; size_t tries = 3; /* * When we issue tickets we use the first key in the principals' highest * kvno keyset. For non-cross-realm krbtgt principals we want to only * allow the use of the first key of the principal's keyset that matches * the given kvno. */ if (krb5_is_tgs_principal(apreq->ticket->server) && !is_cross_tgs_principal(apreq->ticket->server)) { search_enctype = -1; match_enctype = 0; } retval = kdc_get_server_key(kdc_context, apreq->ticket, KRB5_KDB_FLAG_ALIAS_OK, match_enctype, server, NULL, NULL); if (retval) return retval; *tgskey = NULL; kvno = apreq->ticket->enc_part.kvno; do { krb5_free_keyblock(kdc_context, *tgskey); retval = find_server_key(kdc_context, *server, search_enctype, kvno, tgskey, &kvno); if (retval) continue; /* Make the TGS key available to krb5_rd_req_decoded_anyflag() */ retval = krb5_auth_con_setuseruserkey(kdc_context, auth_context, *tgskey); if (retval) return retval; retval = krb5_rd_req_decoded_anyflag(kdc_context, &auth_context, apreq, apreq->ticket->server, kdc_active_realm->realm_keytab, NULL, NULL); /* If the ticket was decrypted, don't try any more keys. */ if (apreq->ticket->enc_part2 != NULL) break; } while (retval && apreq->ticket->enc_part.kvno == 0 && kvno-- > 1 && --tries > 0); return retval; } /* * The KDC should take the keytab associated with the realm and pass * that to the krb5_rd_req_decoded_anyflag(), but we still need to use * the service (TGS, here) key elsewhere. This approach is faster than * the KDB keytab approach too. * * This is also used by do_tgs_req() for u2u auth. */ krb5_error_code kdc_get_server_key(krb5_context context, krb5_ticket *ticket, unsigned int flags, krb5_boolean match_enctype, krb5_db_entry **server_ptr, krb5_keyblock **key, krb5_kvno *kvno) { krb5_error_code retval; krb5_db_entry * server = NULL; krb5_enctype search_enctype = -1; krb5_kvno search_kvno = -1; if (match_enctype) search_enctype = ticket->enc_part.enctype; if (ticket->enc_part.kvno) search_kvno = ticket->enc_part.kvno; *server_ptr = NULL; retval = krb5_db_get_principal(context, ticket->server, flags, &server); if (retval == KRB5_KDB_NOENTRY) { char *sname; if (!krb5_unparse_name(context, ticket->server, &sname)) { limit_string(sname); krb5_klog_syslog(LOG_ERR, _("TGS_REQ: UNKNOWN SERVER: server='%s'"), sname); free(sname); } return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } else if (retval) return retval; if (server->attributes & KRB5_KDB_DISALLOW_SVR || server->attributes & KRB5_KDB_DISALLOW_ALL_TIX) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto errout; } if (key) { retval = find_server_key(context, server, search_enctype, search_kvno, key, kvno); if (retval) goto errout; } *server_ptr = server; server = NULL; return 0; errout: krb5_db_free_principal(context, server); return retval; } /* * A utility function to get the right key from a KDB entry. Used in handling * of kvno 0 TGTs, for example. */ static krb5_error_code find_server_key(krb5_context context, krb5_db_entry *server, krb5_enctype enctype, krb5_kvno kvno, krb5_keyblock **key_out, krb5_kvno *kvno_out) { krb5_error_code retval; krb5_key_data * server_key; krb5_keyblock * key; *key_out = NULL; retval = krb5_dbe_find_enctype(context, server, enctype, -1, kvno ? (krb5_int32)kvno : -1, &server_key); if (retval) return retval; if (!server_key) return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; if ((key = (krb5_keyblock *)malloc(sizeof *key)) == NULL) return ENOMEM; retval = krb5_dbe_decrypt_key_data(context, NULL, server_key, key, NULL); if (retval) goto errout; if (enctype != -1) { krb5_boolean similar; retval = krb5_c_enctype_compare(context, enctype, key->enctype, &similar); if (retval) goto errout; if (!similar) { retval = KRB5_KDB_NO_PERMITTED_KEY; goto errout; } key->enctype = enctype; } *key_out = key; key = NULL; if (kvno_out) *kvno_out = server_key->key_data_kvno; errout: krb5_free_keyblock(context, key); return retval; } /* * If candidate is the local TGT for realm, set *alias_out to candidate and * *storage_out to NULL. Otherwise, load the local TGT into *storage_out and * set *alias_out to *storage_out. * * In the future we might generalize this to a small per-request principal * cache. For now, it saves a load operation in the common case where the AS * server or TGS header ticket server is the local TGT. */ krb5_error_code get_local_tgt(krb5_context context, const krb5_data *realm, krb5_db_entry *candidate, krb5_db_entry **alias_out, krb5_db_entry **storage_out) { krb5_error_code ret; krb5_principal princ; krb5_db_entry *tgt; *alias_out = NULL; *storage_out = NULL; ret = krb5_build_principal_ext(context, &princ, realm->length, realm->data, KRB5_TGS_NAME_SIZE, KRB5_TGS_NAME, realm->length, realm->data, 0); if (ret) return ret; if (!krb5_principal_compare(context, candidate->princ, princ)) { ret = krb5_db_get_principal(context, princ, 0, &tgt); if (!ret) *storage_out = *alias_out = tgt; } else { *alias_out = candidate; } krb5_free_principal(context, princ); return ret; } /* This probably wants to be updated if you support last_req stuff */ static krb5_last_req_entry nolrentry = { KV5M_LAST_REQ_ENTRY, KRB5_LRQ_NONE, 0 }; static krb5_last_req_entry *nolrarray[] = { &nolrentry, 0 }; krb5_error_code fetch_last_req_info(krb5_db_entry *dbentry, krb5_last_req_entry ***lrentry) { *lrentry = nolrarray; return 0; } /* XXX! This is a temporary place-holder */ krb5_error_code check_hot_list(krb5_ticket *ticket) { return 0; } /* Convert an API error code to a protocol error code. */ int errcode_to_protocol(krb5_error_code code) { int protcode; protcode = code - ERROR_TABLE_BASE_krb5; return (protcode >= 0 && protcode <= 128) ? protcode : KRB_ERR_GENERIC; } /* Return -1 if the AS or TGS request is disallowed due to KDC policy on * anonymous tickets. */ int check_anon(kdc_realm_t *kdc_active_realm, krb5_principal client, krb5_principal server) { /* If restrict_anon is set, reject requests from anonymous to principals * other than the local TGT. */ if (kdc_active_realm->realm_restrict_anon && krb5_principal_compare_any_realm(kdc_context, client, krb5_anonymous_principal()) && !krb5_principal_compare(kdc_context, server, tgs_server)) return -1; return 0; } /* * Routines that validate a AS request; checks a lot of things. :-) * * Returns a Kerberos protocol error number, which is _not_ the same * as a com_err error number! */ #define AS_INVALID_OPTIONS (KDC_OPT_FORWARDED | KDC_OPT_PROXY | \ KDC_OPT_VALIDATE | KDC_OPT_RENEW | \ KDC_OPT_ENC_TKT_IN_SKEY | KDC_OPT_CNAME_IN_ADDL_TKT) int validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = "CLIENT EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "CLIENT KEY EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = "SERVICE EXPIRED"; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "REQUIRED PWCHANGE"; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = "POSTDATE NOT ALLOWED"; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = "PROXIABLE NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "CLIENT LOCKED OUT"; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "SERVICE LOCKED OUT"; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = "SERVICE NOT ALLOWED"; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, client.princ, request->server) != 0) { *status = "ANONYMOUS NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; } int validate_forwardable(krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status) { *status = NULL; if (isflagset(request->kdc_options, KDC_OPT_FORWARDABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_FORWARDABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_FORWARDABLE))) { *status = "FORWARDABLE NOT ALLOWED"; return(KDC_ERR_POLICY); } else return 0; } /* Return KRB5KDC_ERR_POLICY if indicators does not contain the required auth * indicators for server, ENOMEM on allocation error, 0 otherwise. */ krb5_error_code check_indicators(krb5_context context, krb5_db_entry *server, krb5_data *const *indicators) { krb5_error_code ret; char *str = NULL, *copy = NULL, *save, *ind; ret = krb5_dbe_get_string(context, server, KRB5_KDB_SK_REQUIRE_AUTH, &str); if (ret || str == NULL) goto cleanup; copy = strdup(str); if (copy == NULL) { ret = ENOMEM; goto cleanup; } /* Look for any of the space-separated strings in indicators. */ ind = strtok_r(copy, " ", &save); while (ind != NULL) { if (authind_contains(indicators, ind)) goto cleanup; ind = strtok_r(NULL, " ", &save); } ret = KRB5KDC_ERR_POLICY; k5_setmsg(context, ret, _("Required auth indicators not present in ticket: %s"), str); cleanup: krb5_dbe_free_string(context, str); free(copy); return ret; } #define ASN1_ID_CLASS (0xc0) #define ASN1_ID_TYPE (0x20) #define ASN1_ID_TAG (0x1f) #define ASN1_CLASS_UNIV (0) #define ASN1_CLASS_APP (1) #define ASN1_CLASS_CTX (2) #define ASN1_CLASS_PRIV (3) #define asn1_id_constructed(x) (x & ASN1_ID_TYPE) #define asn1_id_primitive(x) (!asn1_id_constructed(x)) #define asn1_id_class(x) ((x & ASN1_ID_CLASS) >> 6) #define asn1_id_tag(x) (x & ASN1_ID_TAG) /* * asn1length - return encoded length of value. * * passed a pointer into the asn.1 stream, which is updated * to point right after the length bits. * * returns -1 on failure. */ static int asn1length(unsigned char **astream) { int length; /* resulting length */ int sublen; /* sublengths */ int blen; /* bytes of length */ unsigned char *p; /* substring searching */ if (**astream & 0x80) { blen = **astream & 0x7f; if (blen > 3) { return(-1); } for (++*astream, length = 0; blen; ++*astream, blen--) { length = (length << 8) | **astream; } if (length == 0) { /* indefinite length, figure out by hand */ p = *astream; p++; while (1) { /* compute value length. */ if ((sublen = asn1length(&p)) < 0) { return(-1); } p += sublen; /* check for termination */ if ((!*p++) && (!*p)) { p++; break; } } length = p - *astream; } } else { length = **astream; ++*astream; } return(length); } /* * fetch_asn1_field - return raw asn.1 stream of subfield. * * this routine is passed a context-dependent tag number and "level" and returns * the size and length of the corresponding level subfield. * * levels and are numbered starting from 1. * * returns 0 on success, -1 otherwise. */ int fetch_asn1_field(unsigned char *astream, unsigned int level, unsigned int field, krb5_data *data) { unsigned char *estream; /* end of stream */ int classes; /* # classes seen so far this level */ unsigned int levels = 0; /* levels seen so far */ int lastlevel = 1000; /* last level seen */ int length; /* various lengths */ int tag; /* tag number */ unsigned char savelen; /* saved length of our field */ classes = -1; /* we assume that the first identifier/length will tell us how long the entire stream is. */ astream++; estream = astream; if ((length = asn1length(&astream)) < 0) { return(-1); } estream += length; /* search down the stream, checking identifiers. we process identifiers until we hit the "level" we want, and then process that level for our subfield, always making sure we don't go off the end of the stream. */ while (astream < estream) { if (!asn1_id_constructed(*astream)) { return(-1); } if (asn1_id_class(*astream) == ASN1_CLASS_CTX) { if ((tag = (int)asn1_id_tag(*astream)) <= lastlevel) { levels++; classes = -1; } lastlevel = tag; if (levels == level) { /* in our context-dependent class, is this the one we're looking for ? */ if (tag == (int)field) { /* return length and data */ astream++; savelen = *astream; if ((length = asn1length(&astream)) < 0) { return(-1); } data->length = length; /* if the field length is indefinite, we will have to subtract two (terminating octets) from the length returned since we don't want to pass any info from the "wrapper" back. asn1length will always return the *total* length of the field, not just what's contained in it */ if ((savelen & 0xff) == 0x80) { data->length -=2 ; } data->data = (char *)astream; return(0); } else if (tag <= classes) { /* we've seen this class before, something must be wrong */ return(-1); } else { classes = tag; } } } /* if we're not on our level yet, process this value. otherwise skip over it */ astream++; if ((length = asn1length(&astream)) < 0) { return(-1); } if (levels == level) { astream += length; } } return(-1); } /* Return true if we believe server can support enctype as a session key. */ static krb5_boolean dbentry_supports_enctype(kdc_realm_t *kdc_active_realm, krb5_db_entry *server, krb5_enctype enctype) { krb5_error_code retval; krb5_key_data *datap; char *etypes_str = NULL; krb5_enctype default_enctypes[1] = { 0 }; krb5_enctype *etypes = NULL; krb5_boolean in_list; /* Look up the supported session key enctypes list in the KDB. */ retval = krb5_dbe_get_string(kdc_context, server, KRB5_KDB_SK_SESSION_ENCTYPES, &etypes_str); if (retval == 0 && etypes_str != NULL && *etypes_str != '\0') { /* Pass a fake profile key for tracing of unrecognized tokens. */ retval = krb5int_parse_enctype_list(kdc_context, "KDB-session_etypes", etypes_str, default_enctypes, &etypes); if (retval == 0 && etypes != NULL && etypes[0]) { in_list = k5_etypes_contains(etypes, enctype); free(etypes_str); free(etypes); return in_list; } /* Fall through on error or empty list */ } free(etypes_str); free(etypes); /* If configured to, assume every server without a session_enctypes * attribute supports DES_CBC_CRC. */ if (kdc_active_realm->realm_assume_des_crc_sess && enctype == ENCTYPE_DES_CBC_CRC) return TRUE; /* Due to an ancient interop problem, assume nothing supports des-cbc-md5 * unless there's a session_enctypes explicitly saying that it does. */ if (enctype == ENCTYPE_DES_CBC_MD5) return FALSE; /* Assume the server supports any enctype it has a long-term key for. */ return !krb5_dbe_find_enctype(kdc_context, server, enctype, -1, 0, &datap); } /* * This function returns the keytype which should be selected for the * session key. It is based on the ordered list which the user * requested, and what the KDC and the application server can support. */ krb5_enctype select_session_keytype(kdc_realm_t *kdc_active_realm, krb5_db_entry *server, int nktypes, krb5_enctype *ktype) { int i; for (i = 0; i < nktypes; i++) { if (!krb5_c_valid_enctype(ktype[i])) continue; if (!krb5_is_permitted_enctype(kdc_context, ktype[i])) continue; if (dbentry_supports_enctype(kdc_active_realm, server, ktype[i])) return ktype[i]; } return 0; } /* * Limit strings to a "reasonable" length to prevent crowding out of * other useful information in the log entry */ #define NAME_LENGTH_LIMIT 128 void limit_string(char *name) { int i; if (!name) return; if (strlen(name) < NAME_LENGTH_LIMIT) return; i = NAME_LENGTH_LIMIT-4; name[i++] = '.'; name[i++] = '.'; name[i++] = '.'; name[i] = '\0'; return; } /* * L10_2 = log10(2**x), rounded up; log10(2) ~= 0.301. */ #define L10_2(x) ((int)(((x * 301) + 999) / 1000)) /* * Max length of sprintf("%ld") for an int of type T; includes leading * minus sign and terminating NUL. */ #define D_LEN(t) (L10_2(sizeof(t) * CHAR_BIT) + 2) void ktypes2str(char *s, size_t len, int nktypes, krb5_enctype *ktype) { int i; char stmp[D_LEN(krb5_enctype) + 1]; char *p; if (nktypes < 0 || len < (sizeof(" etypes {...}") + D_LEN(int))) { *s = '\0'; return; } snprintf(s, len, "%d etypes {", nktypes); for (i = 0; i < nktypes; i++) { snprintf(stmp, sizeof(stmp), "%s%ld", i ? " " : "", (long)ktype[i]); if (strlen(s) + strlen(stmp) + sizeof("}") > len) break; strlcat(s, stmp, len); } if (i < nktypes) { /* * We broke out of the loop. Try to truncate the list. */ p = s + strlen(s); while (p - s + sizeof("...}") > len) { while (p > s && *p != ' ' && *p != '{') *p-- = '\0'; if (p > s && *p == ' ') { *p-- = '\0'; continue; } } strlcat(s, "...", len); } strlcat(s, "}", len); return; } void rep_etypes2str(char *s, size_t len, krb5_kdc_rep *rep) { char stmp[sizeof("ses=") + D_LEN(krb5_enctype)]; if (len < (3 * D_LEN(krb5_enctype) + sizeof("etypes {rep= tkt= ses=}"))) { *s = '\0'; return; } snprintf(s, len, "etypes {rep=%ld", (long)rep->enc_part.enctype); if (rep->ticket != NULL) { snprintf(stmp, sizeof(stmp), " tkt=%ld", (long)rep->ticket->enc_part.enctype); strlcat(s, stmp, len); } if (rep->ticket != NULL && rep->ticket->enc_part2 != NULL && rep->ticket->enc_part2->session != NULL) { snprintf(stmp, sizeof(stmp), " ses=%ld", (long)rep->ticket->enc_part2->session->enctype); strlcat(s, stmp, len); } strlcat(s, "}", len); return; } static krb5_error_code verify_for_user_checksum(krb5_context context, krb5_keyblock *key, krb5_pa_for_user *req) { krb5_error_code code; int i; krb5_int32 name_type; char *p; krb5_data data; krb5_boolean valid = FALSE; if (!krb5_c_is_keyed_cksum(req->cksum.checksum_type)) { return KRB5KRB_AP_ERR_INAPP_CKSUM; } /* * Checksum is over name type and string components of * client principal name and auth_package. */ data.length = 4; for (i = 0; i < krb5_princ_size(context, req->user); i++) { data.length += krb5_princ_component(context, req->user, i)->length; } data.length += krb5_princ_realm(context, req->user)->length; data.length += req->auth_package.length; p = data.data = malloc(data.length); if (data.data == NULL) { return ENOMEM; } name_type = krb5_princ_type(context, req->user); p[0] = (name_type >> 0 ) & 0xFF; p[1] = (name_type >> 8 ) & 0xFF; p[2] = (name_type >> 16) & 0xFF; p[3] = (name_type >> 24) & 0xFF; p += 4; for (i = 0; i < krb5_princ_size(context, req->user); i++) { if (krb5_princ_component(context, req->user, i)->length > 0) { memcpy(p, krb5_princ_component(context, req->user, i)->data, krb5_princ_component(context, req->user, i)->length); } p += krb5_princ_component(context, req->user, i)->length; } if (krb5_princ_realm(context, req->user)->length > 0) { memcpy(p, krb5_princ_realm(context, req->user)->data, krb5_princ_realm(context, req->user)->length); } p += krb5_princ_realm(context, req->user)->length; if (req->auth_package.length > 0) memcpy(p, req->auth_package.data, req->auth_package.length); p += req->auth_package.length; code = krb5_c_verify_checksum(context, key, KRB5_KEYUSAGE_APP_DATA_CKSUM, &data, &req->cksum, &valid); if (code == 0 && valid == FALSE) code = KRB5KRB_AP_ERR_MODIFIED; free(data.data); return code; } /* * Legacy protocol transition (Windows 2003 and above) */ static krb5_error_code kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) return code; code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; } static krb5_error_code verify_s4u_x509_user_checksum(krb5_context context, krb5_keyblock *key, krb5_data *req_data, krb5_int32 kdc_req_nonce, krb5_pa_s4u_x509_user *req) { krb5_error_code code; krb5_data scratch; krb5_boolean valid = FALSE; if (enctype_requires_etype_info_2(key->enctype) && !krb5_c_is_keyed_cksum(req->cksum.checksum_type)) return KRB5KRB_AP_ERR_INAPP_CKSUM; if (req->user_id.nonce != kdc_req_nonce) return KRB5KRB_AP_ERR_MODIFIED; /* * Verify checksum over the encoded userid. If that fails, * re-encode, and verify that. This is similar to the * behaviour in kdc_process_tgs_req(). */ if (fetch_asn1_field((unsigned char *)req_data->data, 1, 0, &scratch) < 0) return ASN1_PARSE_ERROR; code = krb5_c_verify_checksum(context, key, KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST, &scratch, &req->cksum, &valid); if (code != 0) return code; if (valid == FALSE) { krb5_data *data; code = encode_krb5_s4u_userid(&req->user_id, &data); if (code != 0) return code; code = krb5_c_verify_checksum(context, key, KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST, data, &req->cksum, &valid); krb5_free_data(context, data); if (code != 0) return code; } return valid ? 0 : KRB5KRB_AP_ERR_MODIFIED; } /* * New protocol transition request (Windows 2008 and above) */ static krb5_error_code kdc_process_s4u_x509_user(krb5_context context, krb5_kdc_req *request, krb5_pa_data *pa_data, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user); if (code) return code; code = verify_s4u_x509_user_checksum(context, tgs_subkey ? tgs_subkey : tgs_session, &req_data, request->nonce, *s4u_x509_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_s4u_x509_user(context, *s4u_x509_user); *s4u_x509_user = NULL; return code; } if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 || (*s4u_x509_user)->user_id.subject_cert.length != 0) { *status = "INVALID_S4U2SELF_REQUEST"; krb5_free_pa_s4u_x509_user(context, *s4u_x509_user); *s4u_x509_user = NULL; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } return 0; } krb5_error_code kdc_make_s4u2self_rep(krb5_context context, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user *req_s4u_user, krb5_kdc_rep *reply, krb5_enc_kdc_rep_part *reply_encpart) { krb5_error_code code; krb5_data *data = NULL; krb5_pa_s4u_x509_user rep_s4u_user; krb5_pa_data padata; krb5_enctype enctype; krb5_keyusage usage; memset(&rep_s4u_user, 0, sizeof(rep_s4u_user)); rep_s4u_user.user_id.nonce = req_s4u_user->user_id.nonce; rep_s4u_user.user_id.user = req_s4u_user->user_id.user; rep_s4u_user.user_id.options = req_s4u_user->user_id.options & KRB5_S4U_OPTS_USE_REPLY_KEY_USAGE; code = encode_krb5_s4u_userid(&rep_s4u_user.user_id, &data); if (code != 0) goto cleanup; if (req_s4u_user->user_id.options & KRB5_S4U_OPTS_USE_REPLY_KEY_USAGE) usage = KRB5_KEYUSAGE_PA_S4U_X509_USER_REPLY; else usage = KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST; code = krb5_c_make_checksum(context, req_s4u_user->cksum.checksum_type, tgs_subkey != NULL ? tgs_subkey : tgs_session, usage, data, &rep_s4u_user.cksum); if (code != 0) goto cleanup; krb5_free_data(context, data); data = NULL; code = encode_krb5_pa_s4u_x509_user(&rep_s4u_user, &data); if (code != 0) goto cleanup; padata.magic = KV5M_PA_DATA; padata.pa_type = KRB5_PADATA_S4U_X509_USER; padata.length = data->length; padata.contents = (krb5_octet *)data->data; code = add_pa_data_element(context, &padata, &reply->padata, FALSE); if (code != 0) goto cleanup; free(data); data = NULL; if (tgs_subkey != NULL) enctype = tgs_subkey->enctype; else enctype = tgs_session->enctype; /* * Owing to a bug in Windows, unkeyed checksums were used for older * enctypes, including rc4-hmac. A forthcoming workaround for this * includes the checksum bytes in the encrypted padata. */ if ((req_s4u_user->user_id.options & KRB5_S4U_OPTS_USE_REPLY_KEY_USAGE) && enctype_requires_etype_info_2(enctype) == FALSE) { padata.length = req_s4u_user->cksum.length + rep_s4u_user.cksum.length; padata.contents = malloc(padata.length); if (padata.contents == NULL) { code = ENOMEM; goto cleanup; } memcpy(padata.contents, req_s4u_user->cksum.contents, req_s4u_user->cksum.length); memcpy(&padata.contents[req_s4u_user->cksum.length], rep_s4u_user.cksum.contents, rep_s4u_user.cksum.length); code = add_pa_data_element(context,&padata, &reply_encpart->enc_padata, FALSE); if (code != 0) { free(padata.contents); goto cleanup; } } cleanup: if (rep_s4u_user.cksum.contents != NULL) krb5_free_checksum_contents(context, &rep_s4u_user.cksum); krb5_free_data(context, data); return code; } /* * Protocol transition (S4U2Self) */ krb5_error_code kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_const_principal client_princ, const krb5_db_entry *server, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_timestamp kdc_time, krb5_pa_s4u_x509_user **s4u_x509_user, krb5_db_entry **princ_ptr, const char **status) { krb5_error_code code; krb5_pa_data *pa_data; int flags; krb5_db_entry *princ; *princ_ptr = NULL; pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_S4U_X509_USER); if (pa_data != NULL) { code = kdc_process_s4u_x509_user(kdc_context, request, pa_data, tgs_subkey, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else { pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER); if (pa_data != NULL) { code = kdc_process_for_user(kdc_active_realm, pa_data, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else return 0; } /* * We need to compare the client name in the TGT with the requested * server name. Supporting server name aliases without assuming a * global name service makes this difficult to do. * * The comparison below handles the following cases (note that the * term "principal name" below excludes the realm). * * (1) The requested service is a host-based service with two name * components, in which case we assume the principal name to * contain sufficient qualifying information. The realm is * ignored for the purpose of comparison. * * (2) The requested service name is an enterprise principal name: * the service principal name is compared with the unparsed * form of the client name (including its realm). * * (3) The requested service is some other name type: an exact * match is required. * * An alternative would be to look up the server once again with * FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact * match between the returned name and client_princ. However, this * assumes that the client set FLAG_CANONICALIZE when requesting * the TGT and that we have a global name service. */ flags = 0; switch (krb5_princ_type(kdc_context, request->server)) { case KRB5_NT_SRV_HST: /* (1) */ if (krb5_princ_size(kdc_context, request->server) == 2) flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM; break; case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */ flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE; break; default: /* (3) */ break; } if (!krb5_principal_compare_flags(kdc_context, request->server, client_princ, flags)) { *status = "INVALID_S4U2SELF_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */ } /* * Protocol transition is mutually exclusive with renew/forward/etc * as well as user-to-user and constrained delegation. This check * is also made in validate_as_request(). * * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KRB5KDC_ERR_BADOPTION; } /* * Do not attempt to lookup principals in foreign realms. */ if (is_local_principal(kdc_active_realm, (*s4u_x509_user)->user_id.user)) { krb5_db_entry no_server; krb5_pa_data **e_data = NULL; code = krb5_db_get_principal(kdc_context, (*s4u_x509_user)->user_id.user, KRB5_KDB_FLAG_INCLUDE_PAC, &princ); if (code == KRB5_KDB_NOENTRY) { *status = "UNKNOWN_S4U2SELF_PRINCIPAL"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } else if (code) { *status = "LOOKING_UP_S4U2SELF_PRINCIPAL"; return code; /* caller can free for_user */ } memset(&no_server, 0, sizeof(no_server)); code = validate_as_request(kdc_active_realm, request, *princ, no_server, kdc_time, status, &e_data); if (code) { krb5_db_free_principal(kdc_context, princ); krb5_free_pa_data(kdc_context, e_data); return code; } *princ_ptr = princ; } return 0; } static krb5_error_code check_allowed_to_delegate_to(krb5_context context, krb5_const_principal client, const krb5_db_entry *server, krb5_const_principal proxy) { /* Can't get a TGT (otherwise it would be unconstrained delegation) */ if (krb5_is_tgs_principal(proxy)) return KRB5KDC_ERR_POLICY; /* Must be in same realm */ if (!krb5_realm_compare(context, server->princ, proxy)) return KRB5KDC_ERR_POLICY; return krb5_db_check_allowed_to_delegate(context, client, server, proxy); } krb5_error_code kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, const krb5_enc_tkt_part *t2enc, const krb5_db_entry *server, krb5_const_principal server_princ, krb5_const_principal proxy_princ, const char **status) { krb5_error_code errcode; /* * Constrained delegation is mutually exclusive with renew/forward/etc. * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) { return KRB5KDC_ERR_BADOPTION; } /* Ensure that evidence ticket server matches TGT client */ if (!krb5_principal_compare(kdc_context, server->princ, /* after canon */ server_princ)) { return KRB5KDC_ERR_SERVER_NOMATCH; } if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) { *status = "EVIDENCE_TKT_NOT_FORWARDABLE"; return KRB5_TKT_NOT_FORWARDABLE; } /* Backend policy check */ errcode = check_allowed_to_delegate_to(kdc_context, t2enc->client, server, proxy_princ); if (errcode) { *status = "NOT_ALLOWED_TO_DELEGATE"; return errcode; } return 0; } krb5_error_code kdc_check_transited_list(kdc_realm_t *kdc_active_realm, const krb5_data *trans, const krb5_data *realm1, const krb5_data *realm2) { krb5_error_code code; /* Check against the KDB module. Treat this answer as authoritative if the * method is supported and doesn't explicitly pass control. */ code = krb5_db_check_transited_realms(kdc_context, trans, realm1, realm2); if (code != KRB5_PLUGIN_OP_NOTSUPP && code != KRB5_PLUGIN_NO_HANDLE) return code; /* Check using krb5.conf [capaths] or hierarchical relationships. */ return krb5_check_transited_list(kdc_context, trans, realm1, realm2); } krb5_error_code validate_transit_path(krb5_context context, krb5_const_principal client, krb5_db_entry *server, krb5_db_entry *header_srv) { /* Incoming */ if (isflagset(server->attributes, KRB5_KDB_XREALM_NON_TRANSITIVE)) { return KRB5KDC_ERR_PATH_NOT_ACCEPTED; } /* Outgoing */ if (isflagset(header_srv->attributes, KRB5_KDB_XREALM_NON_TRANSITIVE) && (!krb5_principal_compare(context, server->princ, header_srv->princ) || !krb5_realm_compare(context, client, header_srv->princ))) { return KRB5KDC_ERR_PATH_NOT_ACCEPTED; } return 0; } krb5_boolean enctype_requires_etype_info_2(krb5_enctype enctype) { switch(enctype) { case ENCTYPE_DES_CBC_CRC: case ENCTYPE_DES_CBC_MD4: case ENCTYPE_DES_CBC_MD5: case ENCTYPE_DES3_CBC_SHA1: case ENCTYPE_DES3_CBC_RAW: case ENCTYPE_ARCFOUR_HMAC: case ENCTYPE_ARCFOUR_HMAC_EXP : return 0; default: return krb5_c_valid_enctype(enctype); } } /* XXX where are the generic helper routines for this? */ krb5_error_code add_pa_data_element(krb5_context context, krb5_pa_data *padata, krb5_pa_data ***inout_padata, krb5_boolean copy) { int i; krb5_pa_data **p; if (*inout_padata != NULL) { for (i = 0; (*inout_padata)[i] != NULL; i++) ; } else i = 0; p = realloc(*inout_padata, (i + 2) * sizeof(krb5_pa_data *)); if (p == NULL) return ENOMEM; *inout_padata = p; p[i] = (krb5_pa_data *)malloc(sizeof(krb5_pa_data)); if (p[i] == NULL) return ENOMEM; *(p[i]) = *padata; p[i + 1] = NULL; if (copy) { p[i]->contents = (krb5_octet *)malloc(padata->length); if (p[i]->contents == NULL) { free(p[i]); p[i] = NULL; return ENOMEM; } memcpy(p[i]->contents, padata->contents, padata->length); } return 0; } void kdc_get_ticket_endtime(kdc_realm_t *kdc_active_realm, krb5_timestamp starttime, krb5_timestamp endtime, krb5_timestamp till, krb5_db_entry *client, krb5_db_entry *server, krb5_timestamp *out_endtime) { krb5_timestamp until, life; if (till == 0) till = kdc_infinity; until = min(till, endtime); life = until - starttime; if (client != NULL && client->max_life != 0) life = min(life, client->max_life); if (server->max_life != 0) life = min(life, server->max_life); if (kdc_active_realm->realm_maxlife != 0) life = min(life, kdc_active_realm->realm_maxlife); *out_endtime = starttime + life; } /* * Set tkt->renew_till to the requested renewable lifetime as modified by * policy. Set the TKT_FLG_RENEWABLE flag if we set a nonzero renew_till. * client and tgt may be NULL. */ void kdc_get_ticket_renewtime(kdc_realm_t *realm, krb5_kdc_req *request, krb5_enc_tkt_part *tgt, krb5_db_entry *client, krb5_db_entry *server, krb5_enc_tkt_part *tkt) { krb5_timestamp rtime, max_rlife; tkt->times.renew_till = 0; /* Don't issue renewable tickets if the client or server don't allow it, * or if this is a TGS request and the TGT isn't renewable. */ if (server->attributes & KRB5_KDB_DISALLOW_RENEWABLE) return; if (client != NULL && (client->attributes & KRB5_KDB_DISALLOW_RENEWABLE)) return; if (tgt != NULL && !(tgt->flags & TKT_FLG_RENEWABLE)) return; /* Determine the requested renewable time. */ if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) rtime = request->rtime ? request->rtime : kdc_infinity; else if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) && tkt->times.endtime < request->till) rtime = request->till; else return; /* Truncate it to the allowable renewable time. */ if (tgt != NULL) rtime = min(rtime, tgt->times.renew_till); max_rlife = min(server->max_renewable_life, realm->realm_maxrlife); if (client != NULL) max_rlife = min(max_rlife, client->max_renewable_life); rtime = min(rtime, tkt->times.starttime + max_rlife); /* Make the ticket renewable if the truncated requested time is larger than * the ticket end time. */ if (rtime > tkt->times.endtime) { setflag(tkt->flags, TKT_FLG_RENEWABLE); tkt->times.renew_till = rtime; } } /** * Handle protected negotiation of FAST using enc_padata * - If ENCPADATA_REQ_ENC_PA_REP is present, then: * - Return ENCPADATA_REQ_ENC_PA_REP with checksum of AS-REQ from client * - Include PADATA_FX_FAST in the enc_padata to indicate FAST * @pre @c out_enc_padata has space for at least two more padata * @param index in/out index into @c out_enc_padata for next item */ krb5_error_code kdc_handle_protected_negotiation(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, const krb5_keyblock *reply_key, krb5_pa_data ***out_enc_padata) { krb5_error_code retval = 0; krb5_checksum checksum; krb5_data *out = NULL; krb5_pa_data pa, *pa_in; pa_in = krb5int_find_pa_data(context, request->padata, KRB5_ENCPADATA_REQ_ENC_PA_REP); if (pa_in == NULL) return 0; pa.magic = KV5M_PA_DATA; pa.pa_type = KRB5_ENCPADATA_REQ_ENC_PA_REP; memset(&checksum, 0, sizeof(checksum)); retval = krb5_c_make_checksum(context,0, reply_key, KRB5_KEYUSAGE_AS_REQ, req_pkt, &checksum); if (retval != 0) goto cleanup; retval = encode_krb5_checksum(&checksum, &out); if (retval != 0) goto cleanup; pa.contents = (krb5_octet *) out->data; pa.length = out->length; retval = add_pa_data_element(context, &pa, out_enc_padata, FALSE); if (retval) goto cleanup; out->data = NULL; pa.magic = KV5M_PA_DATA; pa.pa_type = KRB5_PADATA_FX_FAST; pa.length = 0; pa.contents = NULL; retval = add_pa_data_element(context, &pa, out_enc_padata, FALSE); cleanup: if (checksum.contents) krb5_free_checksum_contents(context, &checksum); if (out != NULL) krb5_free_data(context, out); return retval; } /* * Although the KDC doesn't call this function directly, * process_tcp_connection_read() in net-server.c does call it. */ krb5_error_code make_toolong_error (void *handle, krb5_data **out) { krb5_error errpkt; krb5_error_code retval; krb5_data *scratch; struct server_handle *h = handle; retval = krb5_us_timeofday(h->kdc_err_context, &errpkt.stime, &errpkt.susec); if (retval) return retval; errpkt.error = KRB_ERR_FIELD_TOOLONG; errpkt.server = h->kdc_realmlist[0]->realm_tgsprinc; errpkt.client = NULL; errpkt.cusec = 0; errpkt.ctime = 0; errpkt.text.length = 0; errpkt.text.data = 0; errpkt.e_data.length = 0; errpkt.e_data.data = 0; scratch = malloc(sizeof(*scratch)); if (scratch == NULL) return ENOMEM; retval = krb5_mk_error(h->kdc_err_context, &errpkt, scratch); if (retval) { free(scratch); return retval; } *out = scratch; return 0; } void reset_for_hangup(void *ctx) { int k; struct server_handle *h = ctx; for (k = 0; k < h->kdc_numrealms; k++) krb5_db_refresh_config(h->kdc_realmlist[k]->realm_context); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_4997_0
crossvul-cpp_data_good_863_0
/* $Id: upnpredirect.c,v 1.95 2018/07/06 12:05:48 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 <stdlib.h> #include <string.h> #include <syslog.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <net/if.h> #include <arpa/inet.h> #include <stdio.h> #include <ctype.h> #include <unistd.h> #include "macros.h" #include "config.h" #include "upnpredirect.h" #include "upnpglobalvars.h" #include "upnpevents.h" #include "portinuse.h" #include "upnputils.h" #if defined(USE_NETFILTER) #include "netfilter/iptcrdr.h" #endif #if defined(USE_PF) #include "pf/obsdrdr.h" #endif #if defined(USE_IPF) #include "ipf/ipfrdr.h" #endif #if defined(USE_IPFW) #include "ipfw/ipfwrdr.h" #endif #ifdef USE_MINIUPNPDCTL #include <stdio.h> #include <unistd.h> #endif #ifdef ENABLE_LEASEFILE #include <sys/stat.h> #endif /* from <inttypes.h> */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* proto_atoi() * convert the string "UDP" or "TCP" to IPPROTO_UDP and IPPROTO_UDP */ static int proto_atoi(const char * protocol) { int proto = IPPROTO_TCP; if(strcasecmp(protocol, "UDP") == 0) proto = IPPROTO_UDP; #ifdef IPPROTO_UDPLITE else if(strcasecmp(protocol, "UDPLITE") == 0) proto = IPPROTO_UDPLITE; #endif /* IPPROTO_UDPLITE */ return proto; } /* proto_itoa() * convert IPPROTO_UDP, IPPROTO_UDP, etc. to "UDP", "TCP" */ static const char * proto_itoa(int proto) { const char * protocol; switch(proto) { case IPPROTO_UDP: protocol = "UDP"; break; case IPPROTO_TCP: protocol = "TCP"; break; #ifdef IPPROTO_UDPLITE case IPPROTO_UDPLITE: protocol = "UDPLITE"; break; #endif /* IPPROTO_UDPLITE */ default: protocol = "*UNKNOWN*"; } return protocol; } #ifdef ENABLE_LEASEFILE static int lease_file_add(unsigned short eport, const char * iaddr, unsigned short iport, int proto, const char * desc, unsigned int timestamp) { FILE * fd; if (lease_file == NULL) return 0; fd = fopen( lease_file, "a"); if (fd==NULL) { syslog(LOG_ERR, "could not open lease file: %s", lease_file); return -1; } /* convert our time to unix time * if LEASEFILE_USE_REMAINING_TIME is defined, only the remaining time is stored */ if (timestamp != 0) { timestamp -= upnp_time(); #ifndef LEASEFILE_USE_REMAINING_TIME timestamp += time(NULL); #endif } fprintf(fd, "%s:%hu:%s:%hu:%u:%s\n", proto_itoa(proto), eport, iaddr, iport, timestamp, desc); fclose(fd); return 0; } static int lease_file_remove(unsigned short eport, int proto) { FILE* fd, *fdt; int tmp; char buf[512]; char str[32]; char tmpfilename[128]; int str_size, buf_size; if (lease_file == NULL) return 0; if (strlen( lease_file) + 7 > sizeof(tmpfilename)) { syslog(LOG_ERR, "Lease filename is too long"); return -1; } snprintf( tmpfilename, sizeof(tmpfilename), "%sXXXXXX", lease_file); fd = fopen( lease_file, "r"); if (fd==NULL) { return 0; } snprintf( str, sizeof(str), "%s:%u", proto_itoa(proto), eport); str_size = strlen(str); tmp = mkstemp(tmpfilename); if (tmp==-1) { fclose(fd); syslog(LOG_ERR, "could not open temporary lease file"); return -1; } fchmod(tmp, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); fdt = fdopen(tmp, "a"); buf[sizeof(buf)-1] = 0; while( fgets(buf, sizeof(buf)-1, fd) != NULL) { buf_size = strlen(buf); if (buf_size < str_size || strncmp(str, buf, str_size)!=0) { fwrite(buf, buf_size, 1, fdt); } } fclose(fdt); fclose(fd); if (rename(tmpfilename, lease_file) < 0) { syslog(LOG_ERR, "could not rename temporary lease file to %s", lease_file); remove(tmpfilename); } return 0; } /* reload_from_lease_file() * read lease_file and add the rules contained */ int reload_from_lease_file() { FILE * fd; char * p; unsigned short eport, iport; char * proto; char * iaddr; char * desc; char * rhost; unsigned int leaseduration; unsigned int timestamp; time_t current_time; #ifndef LEASEFILE_USE_REMAINING_TIME time_t current_unix_time; #endif char line[128]; int r; if(!lease_file) return -1; fd = fopen( lease_file, "r"); if (fd==NULL) { syslog(LOG_ERR, "could not open lease file: %s", lease_file); return -1; } if(unlink(lease_file) < 0) { syslog(LOG_WARNING, "could not unlink file %s : %m", lease_file); } current_time = upnp_time(); #ifndef LEASEFILE_USE_REMAINING_TIME current_unix_time = time(NULL); #endif while(fgets(line, sizeof(line), fd)) { syslog(LOG_DEBUG, "parsing lease file line '%s'", line); proto = line; p = strchr(line, ':'); if(!p) { syslog(LOG_ERR, "unrecognized data in lease file"); continue; } *(p++) = '\0'; iaddr = strchr(p, ':'); if(!iaddr) { syslog(LOG_ERR, "unrecognized data in lease file"); continue; } *(iaddr++) = '\0'; eport = (unsigned short)atoi(p); p = strchr(iaddr, ':'); if(!p) { syslog(LOG_ERR, "unrecognized data in lease file"); continue; } *(p++) = '\0'; iport = (unsigned short)atoi(p); p = strchr(p, ':'); if(!p) { syslog(LOG_ERR, "unrecognized data in lease file"); continue; } *(p++) = '\0'; desc = strchr(p, ':'); if(!desc) { syslog(LOG_ERR, "unrecognized data in lease file"); continue; } *(desc++) = '\0'; /*timestamp = (unsigned int)atoi(p);*/ timestamp = (unsigned int)strtoul(p, NULL, 10); /* trim description */ while(isspace(*desc)) desc++; p = desc; while(*(p+1)) p++; while(isspace(*p) && (p > desc)) *(p--) = '\0'; if(timestamp > 0) { #ifdef LEASEFILE_USE_REMAINING_TIME leaseduration = timestamp; timestamp += current_time; /* convert to our time */ #else if(timestamp <= (unsigned int)current_unix_time) { syslog(LOG_NOTICE, "already expired lease in lease file"); continue; } else { leaseduration = timestamp - current_unix_time; timestamp = leaseduration + current_time; /* convert to our time */ } #endif } else { leaseduration = 0; /* default value */ } rhost = NULL; r = upnp_redirect(rhost, eport, iaddr, iport, proto, desc, leaseduration); if(r == -1) { syslog(LOG_ERR, "Failed to redirect %hu -> %s:%hu protocol %s", eport, iaddr, iport, proto); } else if(r == -2) { /* Add the redirection again to the lease file */ lease_file_add(eport, iaddr, iport, proto_atoi(proto), desc, timestamp); } } fclose(fd); return 0; } #ifdef LEASEFILE_USE_REMAINING_TIME void lease_file_rewrite(void) { int index; unsigned short eport, iport; int proto; char iaddr[32]; char desc[64]; char rhost[40]; unsigned int timestamp; if (lease_file == NULL) return; remove(lease_file); for(index = 0; ; index++) { if(get_redirect_rule_by_index(index, 0/*ifname*/, &eport, iaddr, sizeof(iaddr), &iport, &proto, desc, sizeof(desc), rhost, sizeof(rhost), &timestamp, 0, 0) < 0) break; if(lease_file_add(eport, iaddr, iport, proto, desc, timestamp) < 0) break; } } #endif #endif /* upnp_redirect() * calls OS/fw dependent implementation of the redirection. * protocol should be the string "TCP" or "UDP" * returns: 0 on success * -1 failed to redirect * -2 already redirected * -3 permission check failed * -4 already redirected (other mechanism) */ int upnp_redirect(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, const char * protocol, const char * desc, unsigned int leaseduration) { int proto, r; char iaddr_old[32]; char rhost_old[32]; unsigned short iport_old; struct in_addr address; unsigned int timestamp; proto = proto_atoi(protocol); if(inet_aton(iaddr, &address) <= 0) { syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr); return -1; } if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm, eport, address, iport)) { syslog(LOG_INFO, "redirection permission check failed for " "%hu->%s:%hu %s", eport, iaddr, iport, protocol); return -3; } if (desc == NULL) desc = ""; /* assume empty description */ /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) * - 2.2.20.PortMappingDescription : * Overwriting Previous / Existing Port Mappings: * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient * are exactly the same as an existing mapping, the existing mapping values * for InternalPort, PortMappingDescription, PortMappingEnabled and * PortMappingLeaseDuration are overwritten. * Rejecting a New Port Mapping: * In cases where the RemoteHost, ExternalPort and PortMappingProtocol * are the same as an existing mapping, but the InternalClient is * different, the action is rejected with an appropriate error. * Add or Reject New Port Mapping behavior based on vendor implementation: * In cases where the ExternalPort, PortMappingProtocol and InternalClient * are the same, but RemoteHost is different, the vendor can choose to * support both mappings simultaneously, or reject the second mapping * with an appropriate error. * * - 2.4.16.AddPortMapping * This action creates a new port mapping or overwrites an existing * mapping with the same internal client. If the ExternalPort and * PortMappingProtocol pair is already mapped to another internal client, * an error is returned. * * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010) * Protocol ExternalPort RemoteHost InternalClient Result * = = ≠ ≠ Failure * = = ≠ = Failure or success * (vendor specific) * = = = ≠ Failure * = = = = Success (overwrite) */ rhost_old[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto, iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0, rhost_old, sizeof(rhost_old), &timestamp, 0, 0); if(r == 0) { if(strcmp(iaddr, iaddr_old)==0 && ((rhost == NULL && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, rhost_old) == 0)))) { syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; if(iport != iport_old) { r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp); } else { r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp); } #ifdef ENABLE_LEASEFILE if(r == 0) { lease_file_remove(eport, proto); lease_file_add(eport, iaddr, iport, proto, desc, timestamp); } #endif /* ENABLE_LEASEFILE */ return r; } else { syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); return -2; } #ifdef CHECK_PORTINUSE } else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) { syslog(LOG_INFO, "port %hu protocol %s already in use", eport, protocol); return -4; #endif /* CHECK_PORTINUSE */ } else { timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s", eport, iaddr, iport, protocol, desc); return upnp_redirect_internal(rhost, eport, iaddr, iport, proto, desc, timestamp); } } int upnp_redirect_internal(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, int proto, const char * desc, unsigned int timestamp) { /*syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s", eport, iaddr, iport, protocol, desc); */ if(disable_port_forwarding) return -1; if(add_redirect_rule2(ext_if_name, rhost, eport, iaddr, iport, proto, desc, timestamp) < 0) { return -1; } #ifdef ENABLE_LEASEFILE lease_file_add( eport, iaddr, iport, proto, desc, timestamp); #endif /* syslog(LOG_INFO, "creating pass rule to %s:%hu protocol %s for: %s", iaddr, iport, protocol, desc);*/ if(add_filter_rule2(ext_if_name, rhost, iaddr, eport, iport, proto, desc) < 0) { /* clean up the redirect rule */ #if !defined(__linux__) delete_redirect_rule(ext_if_name, eport, proto); #endif return -1; } if(timestamp > 0) { if(!nextruletoclean_timestamp || (timestamp < nextruletoclean_timestamp)) nextruletoclean_timestamp = timestamp; } #ifdef ENABLE_EVENTS /* the number of port mappings changed, we must * inform the subscribers */ upnp_event_var_change_notify(EWanIPC); #endif return 0; } /* Firewall independent code which call the FW dependent code. */ int upnp_get_redirection_infos(unsigned short eport, const char * protocol, unsigned short * iport, char * iaddr, int iaddrlen, char * desc, int desclen, char * rhost, int rhostlen, unsigned int * leaseduration) { int r; unsigned int timestamp; time_t current_time; if(desc && (desclen > 0)) desc[0] = '\0'; if(rhost && (rhostlen > 0)) rhost[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto_atoi(protocol), iaddr, iaddrlen, iport, desc, desclen, rhost, rhostlen, &timestamp, 0, 0); if(r == 0 && timestamp > 0 && timestamp > (unsigned int)(current_time = upnp_time())) { *leaseduration = timestamp - current_time; } else { *leaseduration = 0; } return r; } int upnp_get_redirection_infos_by_index(int index, unsigned short * eport, char * protocol, unsigned short * iport, char * iaddr, int iaddrlen, char * desc, int desclen, char * rhost, int rhostlen, unsigned int * leaseduration) { /*char ifname[IFNAMSIZ];*/ int proto = 0; unsigned int timestamp; time_t current_time; if(desc && (desclen > 0)) desc[0] = '\0'; if(rhost && (rhostlen > 0)) rhost[0] = '\0'; if(get_redirect_rule_by_index(index, 0/*ifname*/, eport, iaddr, iaddrlen, iport, &proto, desc, desclen, rhost, rhostlen, &timestamp, 0, 0) < 0) return -1; else { current_time = upnp_time(); *leaseduration = (timestamp > (unsigned int)current_time) ? (timestamp - current_time) : 0; if(proto == IPPROTO_TCP) memcpy(protocol, "TCP", 4); #ifdef IPPROTO_UDPLITE else if(proto == IPPROTO_UDPLITE) memcpy(protocol, "UDPLITE", 8); #endif /* IPPROTO_UDPLITE */ else memcpy(protocol, "UDP", 4); return 0; } } /* called from natpmp.c too */ int _upnp_delete_redir(unsigned short eport, int proto) { int r; #if defined(__linux__) r = delete_redirect_and_filter_rules(eport, proto); #elif defined(USE_PF) r = delete_redirect_and_filter_rules(ext_if_name, eport, proto); #else r = delete_redirect_rule(ext_if_name, eport, proto); delete_filter_rule(ext_if_name, eport, proto); #endif #ifdef ENABLE_LEASEFILE lease_file_remove( eport, proto); #endif #ifdef ENABLE_EVENTS upnp_event_var_change_notify(EWanIPC); #endif return r; } int upnp_delete_redirection(unsigned short eport, const char * protocol) { syslog(LOG_INFO, "removing redirect rule port %hu %s", eport, protocol); return _upnp_delete_redir(eport, proto_atoi(protocol)); } /* upnp_get_portmapping_number_of_entries() * TODO: improve this code. */ int upnp_get_portmapping_number_of_entries() { int n = 0, r = 0; unsigned short eport, iport; char protocol[4], iaddr[32], desc[64], rhost[32]; unsigned int leaseduration; do { protocol[0] = '\0'; iaddr[0] = '\0'; desc[0] = '\0'; r = upnp_get_redirection_infos_by_index(n, &eport, protocol, &iport, iaddr, sizeof(iaddr), desc, sizeof(desc), rhost, sizeof(rhost), &leaseduration); n++; } while(r==0); return (n-1); } /* functions used to remove unused rules * As a side effect, delete expired rules (based on LeaseDuration) */ struct rule_state * get_upnp_rules_state_list(int max_rules_number_target) { /*char ifname[IFNAMSIZ];*/ int proto; unsigned short iport; unsigned int timestamp; struct rule_state * tmp; struct rule_state * list = 0; struct rule_state * * p; int i = 0; time_t current_time; /*ifname[0] = '\0';*/ tmp = malloc(sizeof(struct rule_state)); if(!tmp) return 0; current_time = upnp_time(); nextruletoclean_timestamp = 0; while(get_redirect_rule_by_index(i, /*ifname*/0, &tmp->eport, 0, 0, &iport, &proto, 0, 0, 0,0, &timestamp, &tmp->packets, &tmp->bytes) >= 0) { tmp->to_remove = 0; if(timestamp > 0) { /* need to remove this port mapping ? */ if(timestamp <= (unsigned int)current_time) tmp->to_remove = 1; else if((nextruletoclean_timestamp <= (unsigned int)current_time) || (timestamp < nextruletoclean_timestamp)) nextruletoclean_timestamp = timestamp; } tmp->proto = (short)proto; /* add tmp to list */ tmp->next = list; list = tmp; /* prepare next iteration */ i++; tmp = malloc(sizeof(struct rule_state)); if(!tmp) break; } #ifdef PCP_PEER i=0; while(get_peer_rule_by_index(i, /*ifname*/0, &tmp->eport, 0, 0, &iport, &proto, 0, 0, 0,0,0, &timestamp, &tmp->packets, &tmp->bytes) >= 0) { tmp->to_remove = 0; if(timestamp > 0) { /* need to remove this port mapping ? */ if(timestamp <= (unsigned int)current_time) tmp->to_remove = 1; else if((nextruletoclean_timestamp <= (unsigned int)current_time) || (timestamp < nextruletoclean_timestamp)) nextruletoclean_timestamp = timestamp; } tmp->proto = (short)proto; /* add tmp to list */ tmp->next = list; list = tmp; /* prepare next iteration */ i++; tmp = malloc(sizeof(struct rule_state)); if(!tmp) break; } #endif free(tmp); /* remove the redirections that need to be removed */ for(p = &list, tmp = list; tmp; tmp = *p) { if(tmp->to_remove) { syslog(LOG_NOTICE, "remove port mapping %hu %s because it has expired", tmp->eport, proto_itoa(tmp->proto)); _upnp_delete_redir(tmp->eport, tmp->proto); *p = tmp->next; free(tmp); i--; } else { p = &(tmp->next); } } /* return empty list if not enough redirections */ if(i<=max_rules_number_target) while(list) { tmp = list; list = tmp->next; free(tmp); } /* return list */ return list; } void remove_unused_rules(struct rule_state * list) { char ifname[IFNAMSIZ]; unsigned short iport; struct rule_state * tmp; u_int64_t packets; u_int64_t bytes; unsigned int timestamp; int n = 0; while(list) { /* remove the rule if no traffic has used it */ if(get_redirect_rule(ifname, list->eport, list->proto, 0, 0, &iport, 0, 0, 0, 0, &timestamp, &packets, &bytes) >= 0) { if(packets == list->packets && bytes == list->bytes) { syslog(LOG_DEBUG, "removing unused mapping %hu %s : still " "%" PRIu64 "packets %" PRIu64 "bytes", list->eport, proto_itoa(list->proto), packets, bytes); _upnp_delete_redir(list->eport, list->proto); n++; } } tmp = list; list = tmp->next; free(tmp); } if(n>0) syslog(LOG_NOTICE, "removed %d unused rules", n); } /* upnp_get_portmappings_in_range() * return a list of all "external" ports for which a port * mapping exists */ unsigned short * upnp_get_portmappings_in_range(unsigned short startport, unsigned short endport, const char * protocol, unsigned int * number) { int proto; proto = proto_atoi(protocol); if(!number) return NULL; return get_portmappings_in_range(startport, endport, proto, number); } /* stuff for miniupnpdctl */ #ifdef USE_MINIUPNPDCTL void write_ruleset_details(int s) { int proto = 0; unsigned short eport, iport; char desc[64]; char iaddr[32]; char rhost[32]; unsigned int timestamp; u_int64_t packets; u_int64_t bytes; int i = 0; char buffer[256]; int n; write(s, "Ruleset :\n", 10); while(get_redirect_rule_by_index(i, 0/*ifname*/, &eport, iaddr, sizeof(iaddr), &iport, &proto, desc, sizeof(desc), rhost, sizeof(rhost), &timestamp, &packets, &bytes) >= 0) { n = snprintf(buffer, sizeof(buffer), "%2d %s %s:%hu->%s:%hu " "'%s' %u %" PRIu64 " %" PRIu64 "\n", /*"'%s' %llu %llu\n",*/ i, proto_itoa(proto), rhost, eport, iaddr, iport, desc, timestamp, packets, bytes); write(s, buffer, n); i++; } } #endif
./CrossVul/dataset_final_sorted/CWE-476/c/good_863_0
crossvul-cpp_data_bad_4834_0
/********************************************************************\ * BitlBee -- An IRC to other IM-networks gateway * * * * Copyright 2010 Wilmer van der Gaast <wilmer@gaast.net> * \********************************************************************/ /* 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 with the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL; if not, write to the Free Software Foundation, Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110-1301 USA */ #define BITLBEE_CORE #include "bitlbee.h" #include "ft.h" file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } } gboolean imcb_file_recv_start(struct im_connection *ic, file_transfer_t *ft) { bee_t *bee = ic->bee; if (bee->ui->ft_out_start) { return bee->ui->ft_out_start(ic, ft); } else { return FALSE; } } void imcb_file_canceled(struct im_connection *ic, file_transfer_t *file, char *reason) { bee_t *bee = ic->bee; if (file->canceled) { file->canceled(file, reason); } if (bee->ui->ft_close) { bee->ui->ft_close(ic, file); } } void imcb_file_finished(struct im_connection *ic, file_transfer_t *file) { bee_t *bee = ic->bee; if (bee->ui->ft_finished) { bee->ui->ft_finished(ic, file); } }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_4834_0
crossvul-cpp_data_good_1223_1
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2007 Oracle. All rights reserved. */ #include <linux/kernel.h> #include <linux/bio.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/fsnotify.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/time.h> #include <linux/string.h> #include <linux/backing-dev.h> #include <linux/mount.h> #include <linux/namei.h> #include <linux/writeback.h> #include <linux/compat.h> #include <linux/security.h> #include <linux/xattr.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/blkdev.h> #include <linux/uuid.h> #include <linux/btrfs.h> #include <linux/uaccess.h> #include <linux/iversion.h> #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "btrfs_inode.h" #include "print-tree.h" #include "volumes.h" #include "locking.h" #include "inode-map.h" #include "backref.h" #include "rcu-string.h" #include "send.h" #include "dev-replace.h" #include "props.h" #include "sysfs.h" #include "qgroup.h" #include "tree-log.h" #include "compression.h" #ifdef CONFIG_64BIT /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI * structures are incorrect, as the timespec structure from userspace * is 4 bytes too small. We define these alternatives here to teach * the kernel about the 32-bit struct packing. */ struct btrfs_ioctl_timespec_32 { __u64 sec; __u32 nsec; } __attribute__ ((__packed__)); struct btrfs_ioctl_received_subvol_args_32 { char uuid[BTRFS_UUID_SIZE]; /* in */ __u64 stransid; /* in */ __u64 rtransid; /* out */ struct btrfs_ioctl_timespec_32 stime; /* in */ struct btrfs_ioctl_timespec_32 rtime; /* out */ __u64 flags; /* in */ __u64 reserved[16]; /* in */ } __attribute__ ((__packed__)); #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \ struct btrfs_ioctl_received_subvol_args_32) #endif #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT) struct btrfs_ioctl_send_args_32 { __s64 send_fd; /* in */ __u64 clone_sources_count; /* in */ compat_uptr_t clone_sources; /* in */ __u64 parent_root; /* in */ __u64 flags; /* in */ __u64 reserved[4]; /* in */ } __attribute__ ((__packed__)); #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \ struct btrfs_ioctl_send_args_32) #endif static int btrfs_clone(struct inode *src, struct inode *inode, u64 off, u64 olen, u64 olen_aligned, u64 destoff, int no_time_update); /* Mask out flags that are inappropriate for the given type of inode. */ static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode, unsigned int flags) { if (S_ISDIR(inode->i_mode)) return flags; else if (S_ISREG(inode->i_mode)) return flags & ~FS_DIRSYNC_FL; else return flags & (FS_NODUMP_FL | FS_NOATIME_FL); } /* * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS * ioctl. */ static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags) { unsigned int iflags = 0; if (flags & BTRFS_INODE_SYNC) iflags |= FS_SYNC_FL; if (flags & BTRFS_INODE_IMMUTABLE) iflags |= FS_IMMUTABLE_FL; if (flags & BTRFS_INODE_APPEND) iflags |= FS_APPEND_FL; if (flags & BTRFS_INODE_NODUMP) iflags |= FS_NODUMP_FL; if (flags & BTRFS_INODE_NOATIME) iflags |= FS_NOATIME_FL; if (flags & BTRFS_INODE_DIRSYNC) iflags |= FS_DIRSYNC_FL; if (flags & BTRFS_INODE_NODATACOW) iflags |= FS_NOCOW_FL; if (flags & BTRFS_INODE_NOCOMPRESS) iflags |= FS_NOCOMP_FL; else if (flags & BTRFS_INODE_COMPRESS) iflags |= FS_COMPR_FL; return iflags; } /* * Update inode->i_flags based on the btrfs internal flags. */ void btrfs_sync_inode_flags_to_i_flags(struct inode *inode) { struct btrfs_inode *binode = BTRFS_I(inode); unsigned int new_fl = 0; if (binode->flags & BTRFS_INODE_SYNC) new_fl |= S_SYNC; if (binode->flags & BTRFS_INODE_IMMUTABLE) new_fl |= S_IMMUTABLE; if (binode->flags & BTRFS_INODE_APPEND) new_fl |= S_APPEND; if (binode->flags & BTRFS_INODE_NOATIME) new_fl |= S_NOATIME; if (binode->flags & BTRFS_INODE_DIRSYNC) new_fl |= S_DIRSYNC; set_mask_bits(&inode->i_flags, S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC, new_fl); } static int btrfs_ioctl_getflags(struct file *file, void __user *arg) { struct btrfs_inode *binode = BTRFS_I(file_inode(file)); unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags); if (copy_to_user(arg, &flags, sizeof(flags))) return -EFAULT; return 0; } /* Check if @flags are a supported and valid set of FS_*_FL flags */ static int check_fsflags(unsigned int flags) { if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \ FS_NOATIME_FL | FS_NODUMP_FL | \ FS_SYNC_FL | FS_DIRSYNC_FL | \ FS_NOCOMP_FL | FS_COMPR_FL | FS_NOCOW_FL)) return -EOPNOTSUPP; if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL)) return -EINVAL; return 0; } static int btrfs_ioctl_setflags(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_inode *binode = BTRFS_I(inode); struct btrfs_root *root = binode->root; struct btrfs_trans_handle *trans; unsigned int fsflags, old_fsflags; int ret; u64 old_flags; unsigned int old_i_flags; umode_t mode; if (!inode_owner_or_capable(inode)) return -EPERM; if (btrfs_root_readonly(root)) return -EROFS; if (copy_from_user(&fsflags, arg, sizeof(fsflags))) return -EFAULT; ret = check_fsflags(fsflags); if (ret) return ret; ret = mnt_want_write_file(file); if (ret) return ret; inode_lock(inode); old_flags = binode->flags; old_i_flags = inode->i_flags; mode = inode->i_mode; fsflags = btrfs_mask_fsflags_for_type(inode, fsflags); old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags); if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) { if (!capable(CAP_LINUX_IMMUTABLE)) { ret = -EPERM; goto out_unlock; } } if (fsflags & FS_SYNC_FL) binode->flags |= BTRFS_INODE_SYNC; else binode->flags &= ~BTRFS_INODE_SYNC; if (fsflags & FS_IMMUTABLE_FL) binode->flags |= BTRFS_INODE_IMMUTABLE; else binode->flags &= ~BTRFS_INODE_IMMUTABLE; if (fsflags & FS_APPEND_FL) binode->flags |= BTRFS_INODE_APPEND; else binode->flags &= ~BTRFS_INODE_APPEND; if (fsflags & FS_NODUMP_FL) binode->flags |= BTRFS_INODE_NODUMP; else binode->flags &= ~BTRFS_INODE_NODUMP; if (fsflags & FS_NOATIME_FL) binode->flags |= BTRFS_INODE_NOATIME; else binode->flags &= ~BTRFS_INODE_NOATIME; if (fsflags & FS_DIRSYNC_FL) binode->flags |= BTRFS_INODE_DIRSYNC; else binode->flags &= ~BTRFS_INODE_DIRSYNC; if (fsflags & FS_NOCOW_FL) { if (S_ISREG(mode)) { /* * It's safe to turn csums off here, no extents exist. * Otherwise we want the flag to reflect the real COW * status of the file and will not set it. */ if (inode->i_size == 0) binode->flags |= BTRFS_INODE_NODATACOW | BTRFS_INODE_NODATASUM; } else { binode->flags |= BTRFS_INODE_NODATACOW; } } else { /* * Revert back under same assumptions as above */ if (S_ISREG(mode)) { if (inode->i_size == 0) binode->flags &= ~(BTRFS_INODE_NODATACOW | BTRFS_INODE_NODATASUM); } else { binode->flags &= ~BTRFS_INODE_NODATACOW; } } /* * The COMPRESS flag can only be changed by users, while the NOCOMPRESS * flag may be changed automatically if compression code won't make * things smaller. */ if (fsflags & FS_NOCOMP_FL) { binode->flags &= ~BTRFS_INODE_COMPRESS; binode->flags |= BTRFS_INODE_NOCOMPRESS; ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0); if (ret && ret != -ENODATA) goto out_drop; } else if (fsflags & FS_COMPR_FL) { const char *comp; if (IS_SWAPFILE(inode)) { ret = -ETXTBSY; goto out_unlock; } binode->flags |= BTRFS_INODE_COMPRESS; binode->flags &= ~BTRFS_INODE_NOCOMPRESS; comp = btrfs_compress_type2str(fs_info->compress_type); if (!comp || comp[0] == 0) comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB); ret = btrfs_set_prop(inode, "btrfs.compression", comp, strlen(comp), 0); if (ret) goto out_drop; } else { ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0); if (ret && ret != -ENODATA) goto out_drop; binode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS); } trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_drop; } btrfs_sync_inode_flags_to_i_flags(inode); inode_inc_iversion(inode); inode->i_ctime = current_time(inode); ret = btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans); out_drop: if (ret) { binode->flags = old_flags; inode->i_flags = old_i_flags; } out_unlock: inode_unlock(inode); mnt_drop_write_file(file); return ret; } /* * Translate btrfs internal inode flags to xflags as expected by the * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are * silently dropped. */ static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags) { unsigned int xflags = 0; if (flags & BTRFS_INODE_APPEND) xflags |= FS_XFLAG_APPEND; if (flags & BTRFS_INODE_IMMUTABLE) xflags |= FS_XFLAG_IMMUTABLE; if (flags & BTRFS_INODE_NOATIME) xflags |= FS_XFLAG_NOATIME; if (flags & BTRFS_INODE_NODUMP) xflags |= FS_XFLAG_NODUMP; if (flags & BTRFS_INODE_SYNC) xflags |= FS_XFLAG_SYNC; return xflags; } /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */ static int check_xflags(unsigned int flags) { if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME | FS_XFLAG_NODUMP | FS_XFLAG_SYNC)) return -EOPNOTSUPP; return 0; } /* * Set the xflags from the internal inode flags. The remaining items of fsxattr * are zeroed. */ static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg) { struct btrfs_inode *binode = BTRFS_I(file_inode(file)); struct fsxattr fa; memset(&fa, 0, sizeof(fa)); fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags); if (copy_to_user(arg, &fa, sizeof(fa))) return -EFAULT; return 0; } static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_inode *binode = BTRFS_I(inode); struct btrfs_root *root = binode->root; struct btrfs_trans_handle *trans; struct fsxattr fa; unsigned old_flags; unsigned old_i_flags; int ret = 0; if (!inode_owner_or_capable(inode)) return -EPERM; if (btrfs_root_readonly(root)) return -EROFS; memset(&fa, 0, sizeof(fa)); if (copy_from_user(&fa, arg, sizeof(fa))) return -EFAULT; ret = check_xflags(fa.fsx_xflags); if (ret) return ret; if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0) return -EOPNOTSUPP; ret = mnt_want_write_file(file); if (ret) return ret; inode_lock(inode); old_flags = binode->flags; old_i_flags = inode->i_flags; /* We need the capabilities to change append-only or immutable inode */ if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) || (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) && !capable(CAP_LINUX_IMMUTABLE)) { ret = -EPERM; goto out_unlock; } if (fa.fsx_xflags & FS_XFLAG_SYNC) binode->flags |= BTRFS_INODE_SYNC; else binode->flags &= ~BTRFS_INODE_SYNC; if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE) binode->flags |= BTRFS_INODE_IMMUTABLE; else binode->flags &= ~BTRFS_INODE_IMMUTABLE; if (fa.fsx_xflags & FS_XFLAG_APPEND) binode->flags |= BTRFS_INODE_APPEND; else binode->flags &= ~BTRFS_INODE_APPEND; if (fa.fsx_xflags & FS_XFLAG_NODUMP) binode->flags |= BTRFS_INODE_NODUMP; else binode->flags &= ~BTRFS_INODE_NODUMP; if (fa.fsx_xflags & FS_XFLAG_NOATIME) binode->flags |= BTRFS_INODE_NOATIME; else binode->flags &= ~BTRFS_INODE_NOATIME; /* 1 item for the inode */ trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_unlock; } btrfs_sync_inode_flags_to_i_flags(inode); inode_inc_iversion(inode); inode->i_ctime = current_time(inode); ret = btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans); out_unlock: if (ret) { binode->flags = old_flags; inode->i_flags = old_i_flags; } inode_unlock(inode); mnt_drop_write_file(file); return ret; } static int btrfs_ioctl_getversion(struct file *file, int __user *arg) { struct inode *inode = file_inode(file); return put_user(inode->i_generation, arg); } static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_device *device; struct request_queue *q; struct fstrim_range range; u64 minlen = ULLONG_MAX; u64 num_devices = 0; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; rcu_read_lock(); list_for_each_entry_rcu(device, &fs_info->fs_devices->devices, dev_list) { if (!device->bdev) continue; q = bdev_get_queue(device->bdev); if (blk_queue_discard(q)) { num_devices++; minlen = min_t(u64, q->limits.discard_granularity, minlen); } } rcu_read_unlock(); if (!num_devices) return -EOPNOTSUPP; if (copy_from_user(&range, arg, sizeof(range))) return -EFAULT; /* * NOTE: Don't truncate the range using super->total_bytes. Bytenr of * block group is in the logical address space, which can be any * sectorsize aligned bytenr in the range [0, U64_MAX]. */ if (range.len < fs_info->sb->s_blocksize) return -EINVAL; range.minlen = max(range.minlen, minlen); ret = btrfs_trim_fs(fs_info, &range); if (ret < 0) return ret; if (copy_to_user(arg, &range, sizeof(range))) return -EFAULT; return 0; } int btrfs_is_empty_uuid(u8 *uuid) { int i; for (i = 0; i < BTRFS_UUID_SIZE; i++) { if (uuid[i]) return 0; } return 1; } static noinline int create_subvol(struct inode *dir, struct dentry *dentry, const char *name, int namelen, u64 *async_transid, struct btrfs_qgroup_inherit *inherit) { struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); struct btrfs_trans_handle *trans; struct btrfs_key key; struct btrfs_root_item *root_item; struct btrfs_inode_item *inode_item; struct extent_buffer *leaf; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *new_root; struct btrfs_block_rsv block_rsv; struct timespec64 cur_time = current_time(dir); struct inode *inode; int ret; int err; u64 objectid; u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID; u64 index = 0; uuid_le new_uuid; root_item = kzalloc(sizeof(*root_item), GFP_KERNEL); if (!root_item) return -ENOMEM; ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid); if (ret) goto fail_free; /* * Don't create subvolume whose level is not zero. Or qgroup will be * screwed up since it assumes subvolume qgroup's level to be 0. */ if (btrfs_qgroup_level(objectid)) { ret = -ENOSPC; goto fail_free; } btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP); /* * The same as the snapshot creation, please see the comment * of create_snapshot(). */ ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false); if (ret) goto fail_free; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); btrfs_subvolume_release_metadata(fs_info, &block_rsv); goto fail_free; } trans->block_rsv = &block_rsv; trans->bytes_reserved = block_rsv.size; ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit); if (ret) goto fail; leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0); if (IS_ERR(leaf)) { ret = PTR_ERR(leaf); goto fail; } btrfs_mark_buffer_dirty(leaf); inode_item = &root_item->inode; btrfs_set_stack_inode_generation(inode_item, 1); btrfs_set_stack_inode_size(inode_item, 3); btrfs_set_stack_inode_nlink(inode_item, 1); btrfs_set_stack_inode_nbytes(inode_item, fs_info->nodesize); btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755); btrfs_set_root_flags(root_item, 0); btrfs_set_root_limit(root_item, 0); btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT); btrfs_set_root_bytenr(root_item, leaf->start); btrfs_set_root_generation(root_item, trans->transid); btrfs_set_root_level(root_item, 0); btrfs_set_root_refs(root_item, 1); btrfs_set_root_used(root_item, leaf->len); btrfs_set_root_last_snapshot(root_item, 0); btrfs_set_root_generation_v2(root_item, btrfs_root_generation(root_item)); uuid_le_gen(&new_uuid); memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE); btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec); btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec); root_item->ctime = root_item->otime; btrfs_set_root_ctransid(root_item, trans->transid); btrfs_set_root_otransid(root_item, trans->transid); btrfs_tree_unlock(leaf); free_extent_buffer(leaf); leaf = NULL; btrfs_set_root_dirid(root_item, new_dirid); key.objectid = objectid; key.offset = 0; key.type = BTRFS_ROOT_ITEM_KEY; ret = btrfs_insert_root(trans, fs_info->tree_root, &key, root_item); if (ret) goto fail; key.offset = (u64)-1; new_root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(new_root)) { ret = PTR_ERR(new_root); btrfs_abort_transaction(trans, ret); goto fail; } btrfs_record_root_in_trans(trans, new_root); ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid); if (ret) { /* We potentially lose an unused inode item here */ btrfs_abort_transaction(trans, ret); goto fail; } mutex_lock(&new_root->objectid_mutex); new_root->highest_objectid = new_dirid; mutex_unlock(&new_root->objectid_mutex); /* * insert the directory item */ ret = btrfs_set_inode_index(BTRFS_I(dir), &index); if (ret) { btrfs_abort_transaction(trans, ret); goto fail; } ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key, BTRFS_FT_DIR, index); if (ret) { btrfs_abort_transaction(trans, ret); goto fail; } btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2); ret = btrfs_update_inode(trans, root, dir); BUG_ON(ret); ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid, btrfs_ino(BTRFS_I(dir)), index, name, namelen); BUG_ON(ret); ret = btrfs_uuid_tree_add(trans, root_item->uuid, BTRFS_UUID_KEY_SUBVOL, objectid); if (ret) btrfs_abort_transaction(trans, ret); fail: kfree(root_item); trans->block_rsv = NULL; trans->bytes_reserved = 0; btrfs_subvolume_release_metadata(fs_info, &block_rsv); if (async_transid) { *async_transid = trans->transid; err = btrfs_commit_transaction_async(trans, 1); if (err) err = btrfs_commit_transaction(trans); } else { err = btrfs_commit_transaction(trans); } if (err && !ret) ret = err; if (!ret) { inode = btrfs_lookup_dentry(dir, dentry); if (IS_ERR(inode)) return PTR_ERR(inode); d_instantiate(dentry, inode); } return ret; fail_free: kfree(root_item); return ret; } static int create_snapshot(struct btrfs_root *root, struct inode *dir, struct dentry *dentry, u64 *async_transid, bool readonly, struct btrfs_qgroup_inherit *inherit) { struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); struct inode *inode; struct btrfs_pending_snapshot *pending_snapshot; struct btrfs_trans_handle *trans; int ret; bool snapshot_force_cow = false; if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state)) return -EINVAL; if (atomic_read(&root->nr_swapfiles)) { btrfs_warn(fs_info, "cannot snapshot subvolume with active swapfile"); return -ETXTBSY; } pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL); if (!pending_snapshot) return -ENOMEM; pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item), GFP_KERNEL); pending_snapshot->path = btrfs_alloc_path(); if (!pending_snapshot->root_item || !pending_snapshot->path) { ret = -ENOMEM; goto free_pending; } /* * Force new buffered writes to reserve space even when NOCOW is * possible. This is to avoid later writeback (running dealloc) to * fallback to COW mode and unexpectedly fail with ENOSPC. */ atomic_inc(&root->will_be_snapshotted); smp_mb__after_atomic(); /* wait for no snapshot writes */ wait_event(root->subv_writers->wait, percpu_counter_sum(&root->subv_writers->counter) == 0); ret = btrfs_start_delalloc_snapshot(root); if (ret) goto dec_and_free; /* * All previous writes have started writeback in NOCOW mode, so now * we force future writes to fallback to COW mode during snapshot * creation. */ atomic_inc(&root->snapshot_force_cow); snapshot_force_cow = true; btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1); btrfs_init_block_rsv(&pending_snapshot->block_rsv, BTRFS_BLOCK_RSV_TEMP); /* * 1 - parent dir inode * 2 - dir entries * 1 - root item * 2 - root ref/backref * 1 - root of snapshot * 1 - UUID item */ ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root, &pending_snapshot->block_rsv, 8, false); if (ret) goto dec_and_free; pending_snapshot->dentry = dentry; pending_snapshot->root = root; pending_snapshot->readonly = readonly; pending_snapshot->dir = dir; pending_snapshot->inherit = inherit; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto fail; } spin_lock(&fs_info->trans_lock); list_add(&pending_snapshot->list, &trans->transaction->pending_snapshots); spin_unlock(&fs_info->trans_lock); if (async_transid) { *async_transid = trans->transid; ret = btrfs_commit_transaction_async(trans, 1); if (ret) ret = btrfs_commit_transaction(trans); } else { ret = btrfs_commit_transaction(trans); } if (ret) goto fail; ret = pending_snapshot->error; if (ret) goto fail; ret = btrfs_orphan_cleanup(pending_snapshot->snap); if (ret) goto fail; inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry); if (IS_ERR(inode)) { ret = PTR_ERR(inode); goto fail; } d_instantiate(dentry, inode); ret = 0; fail: btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv); dec_and_free: if (snapshot_force_cow) atomic_dec(&root->snapshot_force_cow); if (atomic_dec_and_test(&root->will_be_snapshotted)) wake_up_var(&root->will_be_snapshotted); free_pending: kfree(pending_snapshot->root_item); btrfs_free_path(pending_snapshot->path); kfree(pending_snapshot); return ret; } /* copy of may_delete in fs/namei.c() * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do anything with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir) { int error; if (d_really_is_negative(victim)) return -ENOENT; BUG_ON(d_inode(victim->d_parent) != dir); audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) || IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim))) return -EPERM; if (isdir) { if (!d_is_dir(victim)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (d_is_dir(victim)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* copy of may_create in fs/namei.c() */ static inline int btrfs_may_create(struct inode *dir, struct dentry *child) { if (d_really_is_positive(child)) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * Create a new subvolume below @parent. This is largely modeled after * sys_mkdirat and vfs_mkdir, but we only do a single component lookup * inside this filesystem so it's quite a bit simpler. */ static noinline int btrfs_mksubvol(const struct path *parent, const char *name, int namelen, struct btrfs_root *snap_src, u64 *async_transid, bool readonly, struct btrfs_qgroup_inherit *inherit) { struct inode *dir = d_inode(parent->dentry); struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb); struct dentry *dentry; int error; error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT); if (error == -EINTR) return error; dentry = lookup_one_len(name, parent->dentry, namelen); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_unlock; error = btrfs_may_create(dir, dentry); if (error) goto out_dput; /* * even if this name doesn't exist, we may get hash collisions. * check for them now when we can safely fail */ error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root, dir->i_ino, name, namelen); if (error) goto out_dput; down_read(&fs_info->subvol_sem); if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0) goto out_up_read; if (snap_src) { error = create_snapshot(snap_src, dir, dentry, async_transid, readonly, inherit); } else { error = create_subvol(dir, dentry, name, namelen, async_transid, inherit); } if (!error) fsnotify_mkdir(dir, dentry); out_up_read: up_read(&fs_info->subvol_sem); out_dput: dput(dentry); out_unlock: inode_unlock(dir); return error; } /* * When we're defragging a range, we don't want to kick it off again * if it is really just waiting for delalloc to send it down. * If we find a nice big extent or delalloc range for the bytes in the * file you want to defrag, we return 0 to let you know to skip this * part of the file */ static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh) { struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; u64 end; read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE); read_unlock(&em_tree->lock); if (em) { end = extent_map_end(em); free_extent_map(em); if (end - offset > thresh) return 0; } /* if we already have a nice delalloc here, just stop */ thresh /= 2; end = count_range_bits(io_tree, &offset, offset + thresh, thresh, EXTENT_DELALLOC, 1); if (end >= thresh) return 0; return 1; } /* * helper function to walk through a file and find extents * newer than a specific transid, and smaller than thresh. * * This is used by the defragging code to find new and small * extents */ static int find_new_extents(struct btrfs_root *root, struct inode *inode, u64 newer_than, u64 *off, u32 thresh) { struct btrfs_path *path; struct btrfs_key min_key; struct extent_buffer *leaf; struct btrfs_file_extent_item *extent; int type; int ret; u64 ino = btrfs_ino(BTRFS_I(inode)); path = btrfs_alloc_path(); if (!path) return -ENOMEM; min_key.objectid = ino; min_key.type = BTRFS_EXTENT_DATA_KEY; min_key.offset = *off; while (1) { ret = btrfs_search_forward(root, &min_key, path, newer_than); if (ret != 0) goto none; process_slot: if (min_key.objectid != ino) goto none; if (min_key.type != BTRFS_EXTENT_DATA_KEY) goto none; leaf = path->nodes[0]; extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); type = btrfs_file_extent_type(leaf, extent); if (type == BTRFS_FILE_EXTENT_REG && btrfs_file_extent_num_bytes(leaf, extent) < thresh && check_defrag_in_cache(inode, min_key.offset, thresh)) { *off = min_key.offset; btrfs_free_path(path); return 0; } path->slots[0]++; if (path->slots[0] < btrfs_header_nritems(leaf)) { btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]); goto process_slot; } if (min_key.offset == (u64)-1) goto none; min_key.offset++; btrfs_release_path(path); } none: btrfs_free_path(path); return -ENOENT; } static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em; u64 len = PAGE_SIZE; /* * hopefully we have this extent in the tree already, try without * the full extent lock */ read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, start, len); read_unlock(&em_tree->lock); if (!em) { struct extent_state *cached = NULL; u64 end = start + len - 1; /* get the big lock and read metadata off disk */ lock_extent_bits(io_tree, start, end, &cached); em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0); unlock_extent_cached(io_tree, start, end, &cached); if (IS_ERR(em)) return NULL; } return em; } static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em) { struct extent_map *next; bool ret = true; /* this is the last extent */ if (em->start + em->len >= i_size_read(inode)) return false; next = defrag_lookup_extent(inode, em->start + em->len); if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE) ret = false; else if ((em->block_start + em->block_len == next->block_start) && (em->block_len > SZ_128K && next->block_len > SZ_128K)) ret = false; free_extent_map(next); return ret; } static int should_defrag_range(struct inode *inode, u64 start, u32 thresh, u64 *last_len, u64 *skip, u64 *defrag_end, int compress) { struct extent_map *em; int ret = 1; bool next_mergeable = true; bool prev_mergeable = true; /* * make sure that once we start defragging an extent, we keep on * defragging it */ if (start < *defrag_end) return 1; *skip = 0; em = defrag_lookup_extent(inode, start); if (!em) return 0; /* this will cover holes, and inline extents */ if (em->block_start >= EXTENT_MAP_LAST_BYTE) { ret = 0; goto out; } if (!*defrag_end) prev_mergeable = false; next_mergeable = defrag_check_next_extent(inode, em); /* * we hit a real extent, if it is big or the next extent is not a * real extent, don't bother defragging it */ if (!compress && (*last_len == 0 || *last_len >= thresh) && (em->len >= thresh || (!next_mergeable && !prev_mergeable))) ret = 0; out: /* * last_len ends up being a counter of how many bytes we've defragged. * every time we choose not to defrag an extent, we reset *last_len * so that the next tiny extent will force a defrag. * * The end result of this is that tiny extents before a single big * extent will force at least part of that big extent to be defragged. */ if (ret) { *defrag_end = extent_map_end(em); } else { *last_len = 0; *skip = extent_map_end(em); *defrag_end = 0; } free_extent_map(em); return ret; } /* * it doesn't do much good to defrag one or two pages * at a time. This pulls in a nice chunk of pages * to COW and defrag. * * It also makes sure the delalloc code has enough * dirty data to avoid making new small extents as part * of the defrag * * It's a good idea to start RA on this range * before calling this. */ static int cluster_pages_for_defrag(struct inode *inode, struct page **pages, unsigned long start_index, unsigned long num_pages) { unsigned long file_end; u64 isize = i_size_read(inode); u64 page_start; u64 page_end; u64 page_cnt; int ret; int i; int i_done; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; struct extent_io_tree *tree; struct extent_changeset *data_reserved = NULL; gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping); file_end = (isize - 1) >> PAGE_SHIFT; if (!isize || start_index > file_end) return 0; page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1); ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start_index << PAGE_SHIFT, page_cnt << PAGE_SHIFT); if (ret) return ret; i_done = 0; tree = &BTRFS_I(inode)->io_tree; /* step one, lock all the pages */ for (i = 0; i < page_cnt; i++) { struct page *page; again: page = find_or_create_page(inode->i_mapping, start_index + i, mask); if (!page) break; page_start = page_offset(page); page_end = page_start + PAGE_SIZE - 1; while (1) { lock_extent_bits(tree, page_start, page_end, &cached_state); ordered = btrfs_lookup_ordered_extent(inode, page_start); unlock_extent_cached(tree, page_start, page_end, &cached_state); if (!ordered) break; unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); lock_page(page); /* * we unlocked the page above, so we need check if * it was released or not. */ if (page->mapping != inode->i_mapping) { unlock_page(page); put_page(page); goto again; } } if (!PageUptodate(page)) { btrfs_readpage(NULL, page); lock_page(page); if (!PageUptodate(page)) { unlock_page(page); put_page(page); ret = -EIO; break; } } if (page->mapping != inode->i_mapping) { unlock_page(page); put_page(page); goto again; } pages[i] = page; i_done++; } if (!i_done || ret) goto out; if (!(inode->i_sb->s_flags & SB_ACTIVE)) goto out; /* * so now we have a nice long stream of locked * and up to date pages, lets wait on them */ for (i = 0; i < i_done; i++) wait_on_page_writeback(pages[i]); page_start = page_offset(pages[0]); page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE; lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state); clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state); if (i_done != page_cnt) { spin_lock(&BTRFS_I(inode)->lock); btrfs_mod_outstanding_extents(BTRFS_I(inode), 1); spin_unlock(&BTRFS_I(inode)->lock); btrfs_delalloc_release_space(inode, data_reserved, start_index << PAGE_SHIFT, (page_cnt - i_done) << PAGE_SHIFT, true); } set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state); unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state); for (i = 0; i < i_done; i++) { clear_page_dirty_for_io(pages[i]); ClearPageChecked(pages[i]); set_page_extent_mapped(pages[i]); set_page_dirty(pages[i]); unlock_page(pages[i]); put_page(pages[i]); } btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT, false); extent_changeset_free(data_reserved); return i_done; out: for (i = 0; i < i_done; i++) { unlock_page(pages[i]); put_page(pages[i]); } btrfs_delalloc_release_space(inode, data_reserved, start_index << PAGE_SHIFT, page_cnt << PAGE_SHIFT, true); btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT, true); extent_changeset_free(data_reserved); return ret; } int btrfs_defrag_file(struct inode *inode, struct file *file, struct btrfs_ioctl_defrag_range_args *range, u64 newer_than, unsigned long max_to_defrag) { struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct file_ra_state *ra = NULL; unsigned long last_index; u64 isize = i_size_read(inode); u64 last_len = 0; u64 skip = 0; u64 defrag_end = 0; u64 newer_off = range->start; unsigned long i; unsigned long ra_index = 0; int ret; int defrag_count = 0; int compress_type = BTRFS_COMPRESS_ZLIB; u32 extent_thresh = range->extent_thresh; unsigned long max_cluster = SZ_256K >> PAGE_SHIFT; unsigned long cluster = max_cluster; u64 new_align = ~((u64)SZ_128K - 1); struct page **pages = NULL; bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS; if (isize == 0) return 0; if (range->start >= isize) return -EINVAL; if (do_compress) { if (range->compress_type > BTRFS_COMPRESS_TYPES) return -EINVAL; if (range->compress_type) compress_type = range->compress_type; } if (extent_thresh == 0) extent_thresh = SZ_256K; /* * If we were not given a file, allocate a readahead context. As * readahead is just an optimization, defrag will work without it so * we don't error out. */ if (!file) { ra = kzalloc(sizeof(*ra), GFP_KERNEL); if (ra) file_ra_state_init(ra, inode->i_mapping); } else { ra = &file->f_ra; } pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out_ra; } /* find the last page to defrag */ if (range->start + range->len > range->start) { last_index = min_t(u64, isize - 1, range->start + range->len - 1) >> PAGE_SHIFT; } else { last_index = (isize - 1) >> PAGE_SHIFT; } if (newer_than) { ret = find_new_extents(root, inode, newer_than, &newer_off, SZ_64K); if (!ret) { range->start = newer_off; /* * we always align our defrag to help keep * the extents in the file evenly spaced */ i = (newer_off & new_align) >> PAGE_SHIFT; } else goto out_ra; } else { i = range->start >> PAGE_SHIFT; } if (!max_to_defrag) max_to_defrag = last_index - i + 1; /* * make writeback starts from i, so the defrag range can be * written sequentially. */ if (i < inode->i_mapping->writeback_index) inode->i_mapping->writeback_index = i; while (i <= last_index && defrag_count < max_to_defrag && (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) { /* * make sure we stop running if someone unmounts * the FS */ if (!(inode->i_sb->s_flags & SB_ACTIVE)) break; if (btrfs_defrag_cancelled(fs_info)) { btrfs_debug(fs_info, "defrag_file cancelled"); ret = -EAGAIN; break; } if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT, extent_thresh, &last_len, &skip, &defrag_end, do_compress)){ unsigned long next; /* * the should_defrag function tells us how much to skip * bump our counter by the suggested amount */ next = DIV_ROUND_UP(skip, PAGE_SIZE); i = max(i + 1, next); continue; } if (!newer_than) { cluster = (PAGE_ALIGN(defrag_end) >> PAGE_SHIFT) - i; cluster = min(cluster, max_cluster); } else { cluster = max_cluster; } if (i + cluster > ra_index) { ra_index = max(i, ra_index); if (ra) page_cache_sync_readahead(inode->i_mapping, ra, file, ra_index, cluster); ra_index += cluster; } inode_lock(inode); if (IS_SWAPFILE(inode)) { ret = -ETXTBSY; } else { if (do_compress) BTRFS_I(inode)->defrag_compress = compress_type; ret = cluster_pages_for_defrag(inode, pages, i, cluster); } if (ret < 0) { inode_unlock(inode); goto out_ra; } defrag_count += ret; balance_dirty_pages_ratelimited(inode->i_mapping); inode_unlock(inode); if (newer_than) { if (newer_off == (u64)-1) break; if (ret > 0) i += ret; newer_off = max(newer_off + 1, (u64)i << PAGE_SHIFT); ret = find_new_extents(root, inode, newer_than, &newer_off, SZ_64K); if (!ret) { range->start = newer_off; i = (newer_off & new_align) >> PAGE_SHIFT; } else { break; } } else { if (ret > 0) { i += ret; last_len += ret << PAGE_SHIFT; } else { i++; last_len = 0; } } } if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) { filemap_flush(inode->i_mapping); if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &BTRFS_I(inode)->runtime_flags)) filemap_flush(inode->i_mapping); } if (range->compress_type == BTRFS_COMPRESS_LZO) { btrfs_set_fs_incompat(fs_info, COMPRESS_LZO); } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) { btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD); } ret = defrag_count; out_ra: if (do_compress) { inode_lock(inode); BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE; inode_unlock(inode); } if (!file) kfree(ra); kfree(pages); return ret; } static noinline int btrfs_ioctl_resize(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); u64 new_size; u64 old_size; u64 devid = 1; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_vol_args *vol_args; struct btrfs_trans_handle *trans; struct btrfs_device *device = NULL; char *sizestr; char *retptr; char *devstr = NULL; int ret = 0; int mod = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { mnt_drop_write_file(file); return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; } vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; sizestr = vol_args->name; devstr = strchr(sizestr, ':'); if (devstr) { sizestr = devstr + 1; *devstr = '\0'; devstr = vol_args->name; ret = kstrtoull(devstr, 10, &devid); if (ret) goto out_free; if (!devid) { ret = -EINVAL; goto out_free; } btrfs_info(fs_info, "resizing devid %llu", devid); } device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true); if (!device) { btrfs_info(fs_info, "resizer unable to find device %llu", devid); ret = -ENODEV; goto out_free; } if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { btrfs_info(fs_info, "resizer unable to apply on readonly device %llu", devid); ret = -EPERM; goto out_free; } if (!strcmp(sizestr, "max")) new_size = device->bdev->bd_inode->i_size; else { if (sizestr[0] == '-') { mod = -1; sizestr++; } else if (sizestr[0] == '+') { mod = 1; sizestr++; } new_size = memparse(sizestr, &retptr); if (*retptr != '\0' || new_size == 0) { ret = -EINVAL; goto out_free; } } if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { ret = -EPERM; goto out_free; } old_size = btrfs_device_get_total_bytes(device); if (mod < 0) { if (new_size > old_size) { ret = -EINVAL; goto out_free; } new_size = old_size - new_size; } else if (mod > 0) { if (new_size > ULLONG_MAX - old_size) { ret = -ERANGE; goto out_free; } new_size = old_size + new_size; } if (new_size < SZ_256M) { ret = -EINVAL; goto out_free; } if (new_size > device->bdev->bd_inode->i_size) { ret = -EFBIG; goto out_free; } new_size = round_down(new_size, fs_info->sectorsize); btrfs_info_in_rcu(fs_info, "new size for %s is %llu", rcu_str_deref(device->name), new_size); if (new_size > old_size) { trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_free; } ret = btrfs_grow_device(trans, device, new_size); btrfs_commit_transaction(trans); } else if (new_size < old_size) { ret = btrfs_shrink_device(device, new_size); } /* equal, nothing need to do */ out_free: kfree(vol_args); out: clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); mnt_drop_write_file(file); return ret; } static noinline int btrfs_ioctl_snap_create_transid(struct file *file, const char *name, unsigned long fd, int subvol, u64 *transid, bool readonly, struct btrfs_qgroup_inherit *inherit) { int namelen; int ret = 0; if (!S_ISDIR(file_inode(file)->i_mode)) return -ENOTDIR; ret = mnt_want_write_file(file); if (ret) goto out; namelen = strlen(name); if (strchr(name, '/')) { ret = -EINVAL; goto out_drop_write; } if (name[0] == '.' && (namelen == 1 || (name[1] == '.' && namelen == 2))) { ret = -EEXIST; goto out_drop_write; } if (subvol) { ret = btrfs_mksubvol(&file->f_path, name, namelen, NULL, transid, readonly, inherit); } else { struct fd src = fdget(fd); struct inode *src_inode; if (!src.file) { ret = -EINVAL; goto out_drop_write; } src_inode = file_inode(src.file); if (src_inode->i_sb != file_inode(file)->i_sb) { btrfs_info(BTRFS_I(file_inode(file))->root->fs_info, "Snapshot src from another FS"); ret = -EXDEV; } else if (!inode_owner_or_capable(src_inode)) { /* * Subvolume creation is not restricted, but snapshots * are limited to own subvolumes only */ ret = -EPERM; } else { ret = btrfs_mksubvol(&file->f_path, name, namelen, BTRFS_I(src_inode)->root, transid, readonly, inherit); } fdput(src); } out_drop_write: mnt_drop_write_file(file); out: return ret; } static noinline int btrfs_ioctl_snap_create(struct file *file, void __user *arg, int subvol) { struct btrfs_ioctl_vol_args *vol_args; int ret; if (!S_ISDIR(file_inode(file)->i_mode)) return -ENOTDIR; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) return PTR_ERR(vol_args); vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; ret = btrfs_ioctl_snap_create_transid(file, vol_args->name, vol_args->fd, subvol, NULL, false, NULL); kfree(vol_args); return ret; } static noinline int btrfs_ioctl_snap_create_v2(struct file *file, void __user *arg, int subvol) { struct btrfs_ioctl_vol_args_v2 *vol_args; int ret; u64 transid = 0; u64 *ptr = NULL; bool readonly = false; struct btrfs_qgroup_inherit *inherit = NULL; if (!S_ISDIR(file_inode(file)->i_mode)) return -ENOTDIR; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) return PTR_ERR(vol_args); vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0'; if (vol_args->flags & ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY | BTRFS_SUBVOL_QGROUP_INHERIT)) { ret = -EOPNOTSUPP; goto free_args; } if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC) ptr = &transid; if (vol_args->flags & BTRFS_SUBVOL_RDONLY) readonly = true; if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) { if (vol_args->size > PAGE_SIZE) { ret = -EINVAL; goto free_args; } inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size); if (IS_ERR(inherit)) { ret = PTR_ERR(inherit); goto free_args; } } ret = btrfs_ioctl_snap_create_transid(file, vol_args->name, vol_args->fd, subvol, ptr, readonly, inherit); if (ret) goto free_inherit; if (ptr && copy_to_user(arg + offsetof(struct btrfs_ioctl_vol_args_v2, transid), ptr, sizeof(*ptr))) ret = -EFAULT; free_inherit: kfree(inherit); free_args: kfree(vol_args); return ret; } static noinline int btrfs_ioctl_subvol_getflags(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; u64 flags = 0; if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) return -EINVAL; down_read(&fs_info->subvol_sem); if (btrfs_root_readonly(root)) flags |= BTRFS_SUBVOL_RDONLY; up_read(&fs_info->subvol_sem); if (copy_to_user(arg, &flags, sizeof(flags))) ret = -EFAULT; return ret; } static noinline int btrfs_ioctl_subvol_setflags(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; u64 root_flags; u64 flags; int ret = 0; if (!inode_owner_or_capable(inode)) return -EPERM; ret = mnt_want_write_file(file); if (ret) goto out; if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) { ret = -EINVAL; goto out_drop_write; } if (copy_from_user(&flags, arg, sizeof(flags))) { ret = -EFAULT; goto out_drop_write; } if (flags & BTRFS_SUBVOL_CREATE_ASYNC) { ret = -EINVAL; goto out_drop_write; } if (flags & ~BTRFS_SUBVOL_RDONLY) { ret = -EOPNOTSUPP; goto out_drop_write; } down_write(&fs_info->subvol_sem); /* nothing to do */ if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root)) goto out_drop_sem; root_flags = btrfs_root_flags(&root->root_item); if (flags & BTRFS_SUBVOL_RDONLY) { btrfs_set_root_flags(&root->root_item, root_flags | BTRFS_ROOT_SUBVOL_RDONLY); } else { /* * Block RO -> RW transition if this subvolume is involved in * send */ spin_lock(&root->root_item_lock); if (root->send_in_progress == 0) { btrfs_set_root_flags(&root->root_item, root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY); spin_unlock(&root->root_item_lock); } else { spin_unlock(&root->root_item_lock); btrfs_warn(fs_info, "Attempt to set subvolume %llu read-write during send", root->root_key.objectid); ret = -EPERM; goto out_drop_sem; } } trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_reset; } ret = btrfs_update_root(trans, fs_info->tree_root, &root->root_key, &root->root_item); if (ret < 0) { btrfs_end_transaction(trans); goto out_reset; } ret = btrfs_commit_transaction(trans); out_reset: if (ret) btrfs_set_root_flags(&root->root_item, root_flags); out_drop_sem: up_write(&fs_info->subvol_sem); out_drop_write: mnt_drop_write_file(file); out: return ret; } static noinline int key_in_sk(struct btrfs_key *key, struct btrfs_ioctl_search_key *sk) { struct btrfs_key test; int ret; test.objectid = sk->min_objectid; test.type = sk->min_type; test.offset = sk->min_offset; ret = btrfs_comp_cpu_keys(key, &test); if (ret < 0) return 0; test.objectid = sk->max_objectid; test.type = sk->max_type; test.offset = sk->max_offset; ret = btrfs_comp_cpu_keys(key, &test); if (ret > 0) return 0; return 1; } static noinline int copy_to_sk(struct btrfs_path *path, struct btrfs_key *key, struct btrfs_ioctl_search_key *sk, size_t *buf_size, char __user *ubuf, unsigned long *sk_offset, int *num_found) { u64 found_transid; struct extent_buffer *leaf; struct btrfs_ioctl_search_header sh; struct btrfs_key test; unsigned long item_off; unsigned long item_len; int nritems; int i; int slot; int ret = 0; leaf = path->nodes[0]; slot = path->slots[0]; nritems = btrfs_header_nritems(leaf); if (btrfs_header_generation(leaf) > sk->max_transid) { i = nritems; goto advance_key; } found_transid = btrfs_header_generation(leaf); for (i = slot; i < nritems; i++) { item_off = btrfs_item_ptr_offset(leaf, i); item_len = btrfs_item_size_nr(leaf, i); btrfs_item_key_to_cpu(leaf, key, i); if (!key_in_sk(key, sk)) continue; if (sizeof(sh) + item_len > *buf_size) { if (*num_found) { ret = 1; goto out; } /* * return one empty item back for v1, which does not * handle -EOVERFLOW */ *buf_size = sizeof(sh) + item_len; item_len = 0; ret = -EOVERFLOW; } if (sizeof(sh) + item_len + *sk_offset > *buf_size) { ret = 1; goto out; } sh.objectid = key->objectid; sh.offset = key->offset; sh.type = key->type; sh.len = item_len; sh.transid = found_transid; /* copy search result header */ if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) { ret = -EFAULT; goto out; } *sk_offset += sizeof(sh); if (item_len) { char __user *up = ubuf + *sk_offset; /* copy the item */ if (read_extent_buffer_to_user(leaf, up, item_off, item_len)) { ret = -EFAULT; goto out; } *sk_offset += item_len; } (*num_found)++; if (ret) /* -EOVERFLOW from above */ goto out; if (*num_found >= sk->nr_items) { ret = 1; goto out; } } advance_key: ret = 0; test.objectid = sk->max_objectid; test.type = sk->max_type; test.offset = sk->max_offset; if (btrfs_comp_cpu_keys(key, &test) >= 0) ret = 1; else if (key->offset < (u64)-1) key->offset++; else if (key->type < (u8)-1) { key->offset = 0; key->type++; } else if (key->objectid < (u64)-1) { key->offset = 0; key->type = 0; key->objectid++; } else ret = 1; out: /* * 0: all items from this leaf copied, continue with next * 1: * more items can be copied, but unused buffer is too small * * all items were found * Either way, it will stops the loop which iterates to the next * leaf * -EOVERFLOW: item was to large for buffer * -EFAULT: could not copy extent buffer back to userspace */ return ret; } static noinline int search_ioctl(struct inode *inode, struct btrfs_ioctl_search_key *sk, size_t *buf_size, char __user *ubuf) { struct btrfs_fs_info *info = btrfs_sb(inode->i_sb); struct btrfs_root *root; struct btrfs_key key; struct btrfs_path *path; int ret; int num_found = 0; unsigned long sk_offset = 0; if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) { *buf_size = sizeof(struct btrfs_ioctl_search_header); return -EOVERFLOW; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; if (sk->tree_id == 0) { /* search the root of the inode that was passed */ root = BTRFS_I(inode)->root; } else { key.objectid = sk->tree_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; root = btrfs_read_fs_root_no_name(info, &key); if (IS_ERR(root)) { btrfs_free_path(path); return PTR_ERR(root); } } key.objectid = sk->min_objectid; key.type = sk->min_type; key.offset = sk->min_offset; while (1) { ret = btrfs_search_forward(root, &key, path, sk->min_transid); if (ret != 0) { if (ret > 0) ret = 0; goto err; } ret = copy_to_sk(path, &key, sk, buf_size, ubuf, &sk_offset, &num_found); btrfs_release_path(path); if (ret) break; } if (ret > 0) ret = 0; err: sk->nr_items = num_found; btrfs_free_path(path); return ret; } static noinline int btrfs_ioctl_tree_search(struct file *file, void __user *argp) { struct btrfs_ioctl_search_args __user *uargs; struct btrfs_ioctl_search_key sk; struct inode *inode; int ret; size_t buf_size; if (!capable(CAP_SYS_ADMIN)) return -EPERM; uargs = (struct btrfs_ioctl_search_args __user *)argp; if (copy_from_user(&sk, &uargs->key, sizeof(sk))) return -EFAULT; buf_size = sizeof(uargs->buf); inode = file_inode(file); ret = search_ioctl(inode, &sk, &buf_size, uargs->buf); /* * In the origin implementation an overflow is handled by returning a * search header with a len of zero, so reset ret. */ if (ret == -EOVERFLOW) ret = 0; if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk))) ret = -EFAULT; return ret; } static noinline int btrfs_ioctl_tree_search_v2(struct file *file, void __user *argp) { struct btrfs_ioctl_search_args_v2 __user *uarg; struct btrfs_ioctl_search_args_v2 args; struct inode *inode; int ret; size_t buf_size; const size_t buf_limit = SZ_16M; if (!capable(CAP_SYS_ADMIN)) return -EPERM; /* copy search header and buffer size */ uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp; if (copy_from_user(&args, uarg, sizeof(args))) return -EFAULT; buf_size = args.buf_size; /* limit result size to 16MB */ if (buf_size > buf_limit) buf_size = buf_limit; inode = file_inode(file); ret = search_ioctl(inode, &args.key, &buf_size, (char __user *)(&uarg->buf[0])); if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key))) ret = -EFAULT; else if (ret == -EOVERFLOW && copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size))) ret = -EFAULT; return ret; } /* * Search INODE_REFs to identify path name of 'dirid' directory * in a 'tree_id' tree. and sets path name to 'name'. */ static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info, u64 tree_id, u64 dirid, char *name) { struct btrfs_root *root; struct btrfs_key key; char *ptr; int ret = -1; int slot; int len; int total_len = 0; struct btrfs_inode_ref *iref; struct extent_buffer *l; struct btrfs_path *path; if (dirid == BTRFS_FIRST_FREE_OBJECTID) { name[0]='\0'; return 0; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1]; key.objectid = tree_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; root = btrfs_read_fs_root_no_name(info, &key); if (IS_ERR(root)) { ret = PTR_ERR(root); goto out; } key.objectid = dirid; key.type = BTRFS_INODE_REF_KEY; key.offset = (u64)-1; while (1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; else if (ret > 0) { ret = btrfs_previous_item(root, path, dirid, BTRFS_INODE_REF_KEY); if (ret < 0) goto out; else if (ret > 0) { ret = -ENOENT; goto out; } } l = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(l, &key, slot); iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref); len = btrfs_inode_ref_name_len(l, iref); ptr -= len + 1; total_len += len + 1; if (ptr < name) { ret = -ENAMETOOLONG; goto out; } *(ptr + len) = '/'; read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len); if (key.offset == BTRFS_FIRST_FREE_OBJECTID) break; btrfs_release_path(path); key.objectid = key.offset; key.offset = (u64)-1; dirid = key.objectid; } memmove(name, ptr, total_len); name[total_len] = '\0'; ret = 0; out: btrfs_free_path(path); return ret; } static int btrfs_search_path_in_tree_user(struct inode *inode, struct btrfs_ioctl_ino_lookup_user_args *args) { struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; struct super_block *sb = inode->i_sb; struct btrfs_key upper_limit = BTRFS_I(inode)->location; u64 treeid = BTRFS_I(inode)->root->root_key.objectid; u64 dirid = args->dirid; unsigned long item_off; unsigned long item_len; struct btrfs_inode_ref *iref; struct btrfs_root_ref *rref; struct btrfs_root *root; struct btrfs_path *path; struct btrfs_key key, key2; struct extent_buffer *leaf; struct inode *temp_inode; char *ptr; int slot; int len; int total_len = 0; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; /* * If the bottom subvolume does not exist directly under upper_limit, * construct the path in from the bottom up. */ if (dirid != upper_limit.objectid) { ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1]; key.objectid = treeid; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(root)) { ret = PTR_ERR(root); goto out; } key.objectid = dirid; key.type = BTRFS_INODE_REF_KEY; key.offset = (u64)-1; while (1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { goto out; } else if (ret > 0) { ret = btrfs_previous_item(root, path, dirid, BTRFS_INODE_REF_KEY); if (ret < 0) { goto out; } else if (ret > 0) { ret = -ENOENT; goto out; } } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref); len = btrfs_inode_ref_name_len(leaf, iref); ptr -= len + 1; total_len += len + 1; if (ptr < args->path) { ret = -ENAMETOOLONG; goto out; } *(ptr + len) = '/'; read_extent_buffer(leaf, ptr, (unsigned long)(iref + 1), len); /* Check the read+exec permission of this directory */ ret = btrfs_previous_item(root, path, dirid, BTRFS_INODE_ITEM_KEY); if (ret < 0) { goto out; } else if (ret > 0) { ret = -ENOENT; goto out; } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key2, slot); if (key2.objectid != dirid) { ret = -ENOENT; goto out; } temp_inode = btrfs_iget(sb, &key2, root, NULL); if (IS_ERR(temp_inode)) { ret = PTR_ERR(temp_inode); goto out; } ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC); iput(temp_inode); if (ret) { ret = -EACCES; goto out; } if (key.offset == upper_limit.objectid) break; if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) { ret = -EACCES; goto out; } btrfs_release_path(path); key.objectid = key.offset; key.offset = (u64)-1; dirid = key.objectid; } memmove(args->path, ptr, total_len); args->path[total_len] = '\0'; btrfs_release_path(path); } /* Get the bottom subvolume's name from ROOT_REF */ root = fs_info->tree_root; key.objectid = treeid; key.type = BTRFS_ROOT_REF_KEY; key.offset = args->treeid; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { goto out; } else if (ret > 0) { ret = -ENOENT; goto out; } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); item_off = btrfs_item_ptr_offset(leaf, slot); item_len = btrfs_item_size_nr(leaf, slot); /* Check if dirid in ROOT_REF corresponds to passed dirid */ rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref); if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) { ret = -EINVAL; goto out; } /* Copy subvolume's name */ item_off += sizeof(struct btrfs_root_ref); item_len -= sizeof(struct btrfs_root_ref); read_extent_buffer(leaf, args->name, item_off, item_len); args->name[item_len] = 0; out: btrfs_free_path(path); return ret; } static noinline int btrfs_ioctl_ino_lookup(struct file *file, void __user *argp) { struct btrfs_ioctl_ino_lookup_args *args; struct inode *inode; int ret = 0; args = memdup_user(argp, sizeof(*args)); if (IS_ERR(args)) return PTR_ERR(args); inode = file_inode(file); /* * Unprivileged query to obtain the containing subvolume root id. The * path is reset so it's consistent with btrfs_search_path_in_tree. */ if (args->treeid == 0) args->treeid = BTRFS_I(inode)->root->root_key.objectid; if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) { args->name[0] = 0; goto out; } if (!capable(CAP_SYS_ADMIN)) { ret = -EPERM; goto out; } ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info, args->treeid, args->objectid, args->name); out: if (ret == 0 && copy_to_user(argp, args, sizeof(*args))) ret = -EFAULT; kfree(args); return ret; } /* * Version of ino_lookup ioctl (unprivileged) * * The main differences from ino_lookup ioctl are: * * 1. Read + Exec permission will be checked using inode_permission() during * path construction. -EACCES will be returned in case of failure. * 2. Path construction will be stopped at the inode number which corresponds * to the fd with which this ioctl is called. If constructed path does not * exist under fd's inode, -EACCES will be returned. * 3. The name of bottom subvolume is also searched and filled. */ static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp) { struct btrfs_ioctl_ino_lookup_user_args *args; struct inode *inode; int ret; args = memdup_user(argp, sizeof(*args)); if (IS_ERR(args)) return PTR_ERR(args); inode = file_inode(file); if (args->dirid == BTRFS_FIRST_FREE_OBJECTID && BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) { /* * The subvolume does not exist under fd with which this is * called */ kfree(args); return -EACCES; } ret = btrfs_search_path_in_tree_user(inode, args); if (ret == 0 && copy_to_user(argp, args, sizeof(*args))) ret = -EFAULT; kfree(args); return ret; } /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */ static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp) { struct btrfs_ioctl_get_subvol_info_args *subvol_info; struct btrfs_fs_info *fs_info; struct btrfs_root *root; struct btrfs_path *path; struct btrfs_key key; struct btrfs_root_item *root_item; struct btrfs_root_ref *rref; struct extent_buffer *leaf; unsigned long item_off; unsigned long item_len; struct inode *inode; int slot; int ret = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL); if (!subvol_info) { btrfs_free_path(path); return -ENOMEM; } inode = file_inode(file); fs_info = BTRFS_I(inode)->root->fs_info; /* Get root_item of inode's subvolume */ key.objectid = BTRFS_I(inode)->root->root_key.objectid; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(root)) { ret = PTR_ERR(root); goto out; } root_item = &root->root_item; subvol_info->treeid = key.objectid; subvol_info->generation = btrfs_root_generation(root_item); subvol_info->flags = btrfs_root_flags(root_item); memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE); memcpy(subvol_info->parent_uuid, root_item->parent_uuid, BTRFS_UUID_SIZE); memcpy(subvol_info->received_uuid, root_item->received_uuid, BTRFS_UUID_SIZE); subvol_info->ctransid = btrfs_root_ctransid(root_item); subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime); subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime); subvol_info->otransid = btrfs_root_otransid(root_item); subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime); subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime); subvol_info->stransid = btrfs_root_stransid(root_item); subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime); subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime); subvol_info->rtransid = btrfs_root_rtransid(root_item); subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime); subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime); if (key.objectid != BTRFS_FS_TREE_OBJECTID) { /* Search root tree for ROOT_BACKREF of this subvolume */ root = fs_info->tree_root; key.type = BTRFS_ROOT_BACKREF_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { goto out; } else if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) { ret = btrfs_next_leaf(root, path); if (ret < 0) { goto out; } else if (ret > 0) { ret = -EUCLEAN; goto out; } } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.objectid == subvol_info->treeid && key.type == BTRFS_ROOT_BACKREF_KEY) { subvol_info->parent_id = key.offset; rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref); subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref); item_off = btrfs_item_ptr_offset(leaf, slot) + sizeof(struct btrfs_root_ref); item_len = btrfs_item_size_nr(leaf, slot) - sizeof(struct btrfs_root_ref); read_extent_buffer(leaf, subvol_info->name, item_off, item_len); } else { ret = -ENOENT; goto out; } } if (copy_to_user(argp, subvol_info, sizeof(*subvol_info))) ret = -EFAULT; out: btrfs_free_path(path); kzfree(subvol_info); return ret; } /* * Return ROOT_REF information of the subvolume containing this inode * except the subvolume name. */ static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp) { struct btrfs_ioctl_get_subvol_rootref_args *rootrefs; struct btrfs_root_ref *rref; struct btrfs_root *root; struct btrfs_path *path; struct btrfs_key key; struct extent_buffer *leaf; struct inode *inode; u64 objectid; int slot; int ret; u8 found; path = btrfs_alloc_path(); if (!path) return -ENOMEM; rootrefs = memdup_user(argp, sizeof(*rootrefs)); if (IS_ERR(rootrefs)) { btrfs_free_path(path); return PTR_ERR(rootrefs); } inode = file_inode(file); root = BTRFS_I(inode)->root->fs_info->tree_root; objectid = BTRFS_I(inode)->root->root_key.objectid; key.objectid = objectid; key.type = BTRFS_ROOT_REF_KEY; key.offset = rootrefs->min_treeid; found = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { goto out; } else if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) { ret = btrfs_next_leaf(root, path); if (ret < 0) { goto out; } else if (ret > 0) { ret = -EUCLEAN; goto out; } } while (1) { leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) { ret = 0; goto out; } if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) { ret = -EOVERFLOW; goto out; } rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref); rootrefs->rootref[found].treeid = key.offset; rootrefs->rootref[found].dirid = btrfs_root_ref_dirid(leaf, rref); found++; ret = btrfs_next_item(root, path); if (ret < 0) { goto out; } else if (ret > 0) { ret = -EUCLEAN; goto out; } } out: if (!ret || ret == -EOVERFLOW) { rootrefs->num_items = found; /* update min_treeid for next search */ if (found) rootrefs->min_treeid = rootrefs->rootref[found - 1].treeid + 1; if (copy_to_user(argp, rootrefs, sizeof(*rootrefs))) ret = -EFAULT; } kfree(rootrefs); btrfs_free_path(path); return ret; } static noinline int btrfs_ioctl_snap_destroy(struct file *file, void __user *arg) { struct dentry *parent = file->f_path.dentry; struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb); struct dentry *dentry; struct inode *dir = d_inode(parent); struct inode *inode; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *dest = NULL; struct btrfs_ioctl_vol_args *vol_args; int namelen; int err = 0; if (!S_ISDIR(dir->i_mode)) return -ENOTDIR; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) return PTR_ERR(vol_args); vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; namelen = strlen(vol_args->name); if (strchr(vol_args->name, '/') || strncmp(vol_args->name, "..", namelen) == 0) { err = -EINVAL; goto out; } err = mnt_want_write_file(file); if (err) goto out; err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT); if (err == -EINTR) goto out_drop_write; dentry = lookup_one_len(vol_args->name, parent, namelen); if (IS_ERR(dentry)) { err = PTR_ERR(dentry); goto out_unlock_dir; } if (d_really_is_negative(dentry)) { err = -ENOENT; goto out_dput; } inode = d_inode(dentry); dest = BTRFS_I(inode)->root; if (!capable(CAP_SYS_ADMIN)) { /* * Regular user. Only allow this with a special mount * option, when the user has write+exec access to the * subvol root, and when rmdir(2) would have been * allowed. * * Note that this is _not_ check that the subvol is * empty or doesn't contain data that we wouldn't * otherwise be able to delete. * * Users who want to delete empty subvols should try * rmdir(2). */ err = -EPERM; if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED)) goto out_dput; /* * Do not allow deletion if the parent dir is the same * as the dir to be deleted. That means the ioctl * must be called on the dentry referencing the root * of the subvol, not a random directory contained * within it. */ err = -EINVAL; if (root == dest) goto out_dput; err = inode_permission(inode, MAY_WRITE | MAY_EXEC); if (err) goto out_dput; } /* check if subvolume may be deleted by a user */ err = btrfs_may_delete(dir, dentry, 1); if (err) goto out_dput; if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) { err = -EINVAL; goto out_dput; } inode_lock(inode); err = btrfs_delete_subvolume(dir, dentry); inode_unlock(inode); if (!err) d_delete(dentry); out_dput: dput(dentry); out_unlock_dir: inode_unlock(dir); out_drop_write: mnt_drop_write_file(file); out: kfree(vol_args); return err; } static int btrfs_ioctl_defrag(struct file *file, void __user *argp) { struct inode *inode = file_inode(file); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_defrag_range_args *range; int ret; ret = mnt_want_write_file(file); if (ret) return ret; if (btrfs_root_readonly(root)) { ret = -EROFS; goto out; } switch (inode->i_mode & S_IFMT) { case S_IFDIR: if (!capable(CAP_SYS_ADMIN)) { ret = -EPERM; goto out; } ret = btrfs_defrag_root(root); break; case S_IFREG: /* * Note that this does not check the file descriptor for write * access. This prevents defragmenting executables that are * running and allows defrag on files open in read-only mode. */ if (!capable(CAP_SYS_ADMIN) && inode_permission(inode, MAY_WRITE)) { ret = -EPERM; goto out; } range = kzalloc(sizeof(*range), GFP_KERNEL); if (!range) { ret = -ENOMEM; goto out; } if (argp) { if (copy_from_user(range, argp, sizeof(*range))) { ret = -EFAULT; kfree(range); goto out; } /* compression requires us to start the IO */ if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) { range->flags |= BTRFS_DEFRAG_RANGE_START_IO; range->extent_thresh = (u32)-1; } } else { /* the rest are all set to zero by kzalloc */ range->len = (u64)-1; } ret = btrfs_defrag_file(file_inode(file), file, range, BTRFS_OLDEST_GENERATION, 0); if (ret > 0) ret = 0; kfree(range); break; default: ret = -EINVAL; } out: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_vol_args *vol_args; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; ret = btrfs_init_new_device(fs_info, vol_args->name); if (!ret) btrfs_info(fs_info, "disk added %s", vol_args->name); kfree(vol_args); out: clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); return ret; } static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_ioctl_vol_args_v2 *vol_args; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto err_drop; } /* Check for compatibility reject unknown flags */ if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) { ret = -EOPNOTSUPP; goto out; } if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; goto out; } if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) { ret = btrfs_rm_device(fs_info, NULL, vol_args->devid); } else { vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0'; ret = btrfs_rm_device(fs_info, vol_args->name, 0); } clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); if (!ret) { if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) btrfs_info(fs_info, "device deleted: id %llu", vol_args->devid); else btrfs_info(fs_info, "device deleted: %s", vol_args->name); } out: kfree(vol_args); err_drop: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_ioctl_vol_args *vol_args; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; goto out_drop_write; } vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; ret = btrfs_rm_device(fs_info, vol_args->name, 0); if (!ret) btrfs_info(fs_info, "disk deleted %s", vol_args->name); kfree(vol_args); out: clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); out_drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_fs_info_args *fi_args; struct btrfs_device *device; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; int ret = 0; fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL); if (!fi_args) return -ENOMEM; rcu_read_lock(); fi_args->num_devices = fs_devices->num_devices; list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) { if (device->devid > fi_args->max_id) fi_args->max_id = device->devid; } rcu_read_unlock(); memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid)); fi_args->nodesize = fs_info->nodesize; fi_args->sectorsize = fs_info->sectorsize; fi_args->clone_alignment = fs_info->sectorsize; if (copy_to_user(arg, fi_args, sizeof(*fi_args))) ret = -EFAULT; kfree(fi_args); return ret; } static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_dev_info_args *di_args; struct btrfs_device *dev; int ret = 0; char *s_uuid = NULL; di_args = memdup_user(arg, sizeof(*di_args)); if (IS_ERR(di_args)) return PTR_ERR(di_args); if (!btrfs_is_empty_uuid(di_args->uuid)) s_uuid = di_args->uuid; rcu_read_lock(); dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid, NULL, true); if (!dev) { ret = -ENODEV; goto out; } di_args->devid = dev->devid; di_args->bytes_used = btrfs_device_get_bytes_used(dev); di_args->total_bytes = btrfs_device_get_total_bytes(dev); memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid)); if (dev->name) { strncpy(di_args->path, rcu_str_deref(dev->name), sizeof(di_args->path) - 1); di_args->path[sizeof(di_args->path) - 1] = 0; } else { di_args->path[0] = '\0'; } out: rcu_read_unlock(); if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args))) ret = -EFAULT; kfree(di_args); return ret; } static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2) { inode_unlock(inode1); inode_unlock(inode2); } static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2) { if (inode1 < inode2) swap(inode1, inode2); inode_lock_nested(inode1, I_MUTEX_PARENT); inode_lock_nested(inode2, I_MUTEX_CHILD); } static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1, struct inode *inode2, u64 loff2, u64 len) { unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1); unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1); } static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1, struct inode *inode2, u64 loff2, u64 len) { if (inode1 < inode2) { swap(inode1, inode2); swap(loff1, loff2); } else if (inode1 == inode2 && loff2 < loff1) { swap(loff1, loff2); } lock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1); lock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1); } static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen, struct inode *dst, u64 dst_loff) { u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize; int ret; u64 len = olen; if (loff + len == src->i_size) len = ALIGN(src->i_size, bs) - loff; /* * For same inode case we don't want our length pushed out past i_size * as comparing that data range makes no sense. * * This effectively means we require aligned extents for the single * inode case, whereas the other cases allow an unaligned length so long * as it ends at i_size. */ if (dst == src && len != olen) return -EINVAL; /* * Lock destination range to serialize with concurrent readpages() and * source range to serialize with relocation. */ btrfs_double_extent_lock(src, loff, dst, dst_loff, len); ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1); btrfs_double_extent_unlock(src, loff, dst, dst_loff, len); return ret; } #define BTRFS_MAX_DEDUPE_LEN SZ_16M static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen, struct inode *dst, u64 dst_loff) { int ret; u64 i, tail_len, chunk_count; tail_len = olen % BTRFS_MAX_DEDUPE_LEN; chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN); for (i = 0; i < chunk_count; i++) { ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN, dst, dst_loff); if (ret) return ret; loff += BTRFS_MAX_DEDUPE_LEN; dst_loff += BTRFS_MAX_DEDUPE_LEN; } if (tail_len > 0) ret = btrfs_extent_same_range(src, loff, tail_len, dst, dst_loff); return ret; } static int clone_finish_inode_update(struct btrfs_trans_handle *trans, struct inode *inode, u64 endoff, const u64 destoff, const u64 olen, int no_time_update) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret; inode_inc_iversion(inode); if (!no_time_update) inode->i_mtime = inode->i_ctime = current_time(inode); /* * We round up to the block size at eof when determining which * extents to clone above, but shouldn't round up the file size. */ if (endoff > destoff + olen) endoff = destoff + olen; if (endoff > inode->i_size) btrfs_i_size_write(BTRFS_I(inode), endoff); ret = btrfs_update_inode(trans, root, inode); if (ret) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } ret = btrfs_end_transaction(trans); out: return ret; } static void clone_update_extent_map(struct btrfs_inode *inode, const struct btrfs_trans_handle *trans, const struct btrfs_path *path, const u64 hole_offset, const u64 hole_len) { struct extent_map_tree *em_tree = &inode->extent_tree; struct extent_map *em; int ret; em = alloc_extent_map(); if (!em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags); return; } if (path) { struct btrfs_file_extent_item *fi; fi = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_file_extent_item); btrfs_extent_item_to_extent_map(inode, path, fi, false, em); em->generation = -1; if (btrfs_file_extent_type(path->nodes[0], fi) == BTRFS_FILE_EXTENT_INLINE) set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags); } else { em->start = hole_offset; em->len = hole_len; em->ram_bytes = em->len; em->orig_start = hole_offset; em->block_start = EXTENT_MAP_HOLE; em->block_len = 0; em->orig_block_len = 0; em->compress_type = BTRFS_COMPRESS_NONE; em->generation = trans->transid; } while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 1); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); } if (ret) set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags); } /* * Make sure we do not end up inserting an inline extent into a file that has * already other (non-inline) extents. If a file has an inline extent it can * not have any other extents and the (single) inline extent must start at the * file offset 0. Failing to respect these rules will lead to file corruption, * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc * * We can have extents that have been already written to disk or we can have * dirty ranges still in delalloc, in which case the extent maps and items are * created only when we run delalloc, and the delalloc ranges might fall outside * the range we are currently locking in the inode's io tree. So we check the * inode's i_size because of that (i_size updates are done while holding the * i_mutex, which we are holding here). * We also check to see if the inode has a size not greater than "datal" but has * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are * protected against such concurrent fallocate calls by the i_mutex). * * If the file has no extents but a size greater than datal, do not allow the * copy because we would need turn the inline extent into a non-inline one (even * with NO_HOLES enabled). If we find our destination inode only has one inline * extent, just overwrite it with the source inline extent if its size is less * than the source extent's size, or we could copy the source inline extent's * data into the destination inode's inline extent if the later is greater then * the former. */ static int clone_copy_inline_extent(struct inode *dst, struct btrfs_trans_handle *trans, struct btrfs_path *path, struct btrfs_key *new_key, const u64 drop_start, const u64 datal, const u64 skip, const u64 size, char *inline_data) { struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb); struct btrfs_root *root = BTRFS_I(dst)->root; const u64 aligned_end = ALIGN(new_key->offset + datal, fs_info->sectorsize); int ret; struct btrfs_key key; if (new_key->offset > 0) return -EOPNOTSUPP; key.objectid = btrfs_ino(BTRFS_I(dst)); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { return ret; } else if (ret > 0) { if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) { ret = btrfs_next_leaf(root, path); if (ret < 0) return ret; else if (ret > 0) goto copy_inline_extent; } btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); if (key.objectid == btrfs_ino(BTRFS_I(dst)) && key.type == BTRFS_EXTENT_DATA_KEY) { ASSERT(key.offset > 0); return -EOPNOTSUPP; } } else if (i_size_read(dst) <= datal) { struct btrfs_file_extent_item *ei; u64 ext_len; /* * If the file size is <= datal, make sure there are no other * extents following (can happen do to an fallocate call with * the flag FALLOC_FL_KEEP_SIZE). */ ei = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_file_extent_item); /* * If it's an inline extent, it can not have other extents * following it. */ if (btrfs_file_extent_type(path->nodes[0], ei) == BTRFS_FILE_EXTENT_INLINE) goto copy_inline_extent; ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei); if (ext_len > aligned_end) return -EOPNOTSUPP; ret = btrfs_next_item(root, path); if (ret < 0) { return ret; } else if (ret == 0) { btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); if (key.objectid == btrfs_ino(BTRFS_I(dst)) && key.type == BTRFS_EXTENT_DATA_KEY) return -EOPNOTSUPP; } } copy_inline_extent: /* * We have no extent items, or we have an extent at offset 0 which may * or may not be inlined. All these cases are dealt the same way. */ if (i_size_read(dst) > datal) { /* * If the destination inode has an inline extent... * This would require copying the data from the source inline * extent into the beginning of the destination's inline extent. * But this is really complex, both extents can be compressed * or just one of them, which would require decompressing and * re-compressing data (which could increase the new compressed * size, not allowing the compressed data to fit anymore in an * inline extent). * So just don't support this case for now (it should be rare, * we are not really saving space when cloning inline extents). */ return -EOPNOTSUPP; } btrfs_release_path(path); ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1); if (ret) return ret; ret = btrfs_insert_empty_item(trans, root, path, new_key, size); if (ret) return ret; if (skip) { const u32 start = btrfs_file_extent_calc_inline_size(0); memmove(inline_data + start, inline_data + start + skip, datal); } write_extent_buffer(path->nodes[0], inline_data, btrfs_item_ptr_offset(path->nodes[0], path->slots[0]), size); inode_add_bytes(dst, datal); return 0; } /** * btrfs_clone() - clone a range from inode file to another * * @src: Inode to clone from * @inode: Inode to clone to * @off: Offset within source to start clone from * @olen: Original length, passed by user, of range to clone * @olen_aligned: Block-aligned value of olen * @destoff: Offset within @inode to start clone * @no_time_update: Whether to update mtime/ctime on the target inode */ static int btrfs_clone(struct inode *src, struct inode *inode, const u64 off, const u64 olen, const u64 olen_aligned, const u64 destoff, int no_time_update) { struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_path *path = NULL; struct extent_buffer *leaf; struct btrfs_trans_handle *trans; char *buf = NULL; struct btrfs_key key; u32 nritems; int slot; int ret; const u64 len = olen_aligned; u64 last_dest_end = destoff; ret = -ENOMEM; buf = kvmalloc(fs_info->nodesize, GFP_KERNEL); if (!buf) return ret; path = btrfs_alloc_path(); if (!path) { kvfree(buf); return ret; } path->reada = READA_FORWARD; /* clone data */ key.objectid = btrfs_ino(BTRFS_I(src)); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = off; while (1) { u64 next_key_min_offset = key.offset + 1; /* * note the key will change type as we walk through the * tree. */ path->leave_spinning = 1; ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path, 0, 0); if (ret < 0) goto out; /* * First search, if no extent item that starts at offset off was * found but the previous item is an extent item, it's possible * it might overlap our target range, therefore process it. */ if (key.offset == off && ret > 0 && path->slots[0] > 0) { btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1); if (key.type == BTRFS_EXTENT_DATA_KEY) path->slots[0]--; } nritems = btrfs_header_nritems(path->nodes[0]); process_slot: if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(BTRFS_I(src)->root, path); if (ret < 0) goto out; if (ret > 0) break; nritems = btrfs_header_nritems(path->nodes[0]); } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.type > BTRFS_EXTENT_DATA_KEY || key.objectid != btrfs_ino(BTRFS_I(src))) break; if (key.type == BTRFS_EXTENT_DATA_KEY) { struct btrfs_file_extent_item *extent; int type; u32 size; struct btrfs_key new_key; u64 disko = 0, diskl = 0; u64 datao = 0, datal = 0; u8 comp; u64 drop_start; extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); comp = btrfs_file_extent_compression(leaf, extent); type = btrfs_file_extent_type(leaf, extent); if (type == BTRFS_FILE_EXTENT_REG || type == BTRFS_FILE_EXTENT_PREALLOC) { disko = btrfs_file_extent_disk_bytenr(leaf, extent); diskl = btrfs_file_extent_disk_num_bytes(leaf, extent); datao = btrfs_file_extent_offset(leaf, extent); datal = btrfs_file_extent_num_bytes(leaf, extent); } else if (type == BTRFS_FILE_EXTENT_INLINE) { /* take upper bound, may be compressed */ datal = btrfs_file_extent_ram_bytes(leaf, extent); } /* * The first search might have left us at an extent * item that ends before our target range's start, can * happen if we have holes and NO_HOLES feature enabled. */ if (key.offset + datal <= off) { path->slots[0]++; goto process_slot; } else if (key.offset >= off + len) { break; } next_key_min_offset = key.offset + datal; size = btrfs_item_size_nr(leaf, slot); read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); btrfs_release_path(path); path->leave_spinning = 0; memcpy(&new_key, &key, sizeof(new_key)); new_key.objectid = btrfs_ino(BTRFS_I(inode)); if (off <= key.offset) new_key.offset = key.offset + destoff - off; else new_key.offset = destoff; /* * Deal with a hole that doesn't have an extent item * that represents it (NO_HOLES feature enabled). * This hole is either in the middle of the cloning * range or at the beginning (fully overlaps it or * partially overlaps it). */ if (new_key.offset != last_dest_end) drop_start = last_dest_end; else drop_start = new_key.offset; /* * 1 - adjusting old extent (we may have to split it) * 1 - add new extent * 1 - inode update */ trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } if (type == BTRFS_FILE_EXTENT_REG || type == BTRFS_FILE_EXTENT_PREALLOC) { /* * a | --- range to clone ---| b * | ------------- extent ------------- | */ /* subtract range b */ if (key.offset + datal > off + len) datal = off + len - key.offset; /* subtract range a */ if (off > key.offset) { datao += off - key.offset; datal -= off - key.offset; } ret = btrfs_drop_extents(trans, root, inode, drop_start, new_key.offset + datal, 1); if (ret) { if (ret != -EOPNOTSUPP) btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } ret = btrfs_insert_empty_item(trans, root, path, &new_key, size); if (ret) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } leaf = path->nodes[0]; slot = path->slots[0]; write_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); /* disko == 0 means it's a hole */ if (!disko) datao = 0; btrfs_set_file_extent_offset(leaf, extent, datao); btrfs_set_file_extent_num_bytes(leaf, extent, datal); if (disko) { inode_add_bytes(inode, datal); ret = btrfs_inc_extent_ref(trans, root, disko, diskl, 0, root->root_key.objectid, btrfs_ino(BTRFS_I(inode)), new_key.offset - datao); if (ret) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } } } else if (type == BTRFS_FILE_EXTENT_INLINE) { u64 skip = 0; u64 trim = 0; if (off > key.offset) { skip = off - key.offset; new_key.offset += skip; } if (key.offset + datal > off + len) trim = key.offset + datal - (off + len); if (comp && (skip || trim)) { ret = -EINVAL; btrfs_end_transaction(trans); goto out; } size -= skip + trim; datal -= skip + trim; ret = clone_copy_inline_extent(inode, trans, path, &new_key, drop_start, datal, skip, size, buf); if (ret) { if (ret != -EOPNOTSUPP) btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } leaf = path->nodes[0]; slot = path->slots[0]; } /* If we have an implicit hole (NO_HOLES feature). */ if (drop_start < new_key.offset) clone_update_extent_map(BTRFS_I(inode), trans, NULL, drop_start, new_key.offset - drop_start); clone_update_extent_map(BTRFS_I(inode), trans, path, 0, 0); btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); last_dest_end = ALIGN(new_key.offset + datal, fs_info->sectorsize); ret = clone_finish_inode_update(trans, inode, last_dest_end, destoff, olen, no_time_update); if (ret) goto out; if (new_key.offset + datal >= destoff + len) break; } btrfs_release_path(path); key.offset = next_key_min_offset; if (fatal_signal_pending(current)) { ret = -EINTR; goto out; } } ret = 0; if (last_dest_end < destoff + len) { /* * We have an implicit hole (NO_HOLES feature is enabled) that * fully or partially overlaps our cloning range at its end. */ btrfs_release_path(path); /* * 1 - remove extent(s) * 1 - inode update */ trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } ret = btrfs_drop_extents(trans, root, inode, last_dest_end, destoff + len, 1); if (ret) { if (ret != -EOPNOTSUPP) btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } clone_update_extent_map(BTRFS_I(inode), trans, NULL, last_dest_end, destoff + len - last_dest_end); ret = clone_finish_inode_update(trans, inode, destoff + len, destoff, olen, no_time_update); } out: btrfs_free_path(path); kvfree(buf); return ret; } static noinline int btrfs_clone_files(struct file *file, struct file *file_src, u64 off, u64 olen, u64 destoff) { struct inode *inode = file_inode(file); struct inode *src = file_inode(file_src); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); int ret; u64 len = olen; u64 bs = fs_info->sb->s_blocksize; /* * TODO: * - split compressed inline extents. annoying: we need to * decompress into destination's address_space (the file offset * may change, so source mapping won't do), then recompress (or * otherwise reinsert) a subrange. * * - split destination inode's inline extents. The inline extents can * be either compressed or non-compressed. */ /* * VFS's generic_remap_file_range_prep() protects us from cloning the * eof block into the middle of a file, which would result in corruption * if the file size is not blocksize aligned. So we don't need to check * for that case here. */ if (off + len == src->i_size) len = ALIGN(src->i_size, bs) - off; if (destoff > inode->i_size) { const u64 wb_start = ALIGN_DOWN(inode->i_size, bs); ret = btrfs_cont_expand(inode, inode->i_size, destoff); if (ret) return ret; /* * We may have truncated the last block if the inode's size is * not sector size aligned, so we need to wait for writeback to * complete before proceeding further, otherwise we can race * with cloning and attempt to increment a reference to an * extent that no longer exists (writeback completed right after * we found the previous extent covering eof and before we * attempted to increment its reference count). */ ret = btrfs_wait_ordered_range(inode, wb_start, destoff - wb_start); if (ret) return ret; } /* * Lock destination range to serialize with concurrent readpages() and * source range to serialize with relocation. */ btrfs_double_extent_lock(src, off, inode, destoff, len); ret = btrfs_clone(src, inode, off, olen, len, destoff, 0); btrfs_double_extent_unlock(src, off, inode, destoff, len); /* * Truncate page cache pages so that future reads will see the cloned * data immediately and not the previous data. */ truncate_inode_pages_range(&inode->i_data, round_down(destoff, PAGE_SIZE), round_up(destoff + len, PAGE_SIZE) - 1); return ret; } static int btrfs_remap_file_range_prep(struct file *file_in, loff_t pos_in, struct file *file_out, loff_t pos_out, loff_t *len, unsigned int remap_flags) { struct inode *inode_in = file_inode(file_in); struct inode *inode_out = file_inode(file_out); u64 bs = BTRFS_I(inode_out)->root->fs_info->sb->s_blocksize; bool same_inode = inode_out == inode_in; u64 wb_len; int ret; if (!(remap_flags & REMAP_FILE_DEDUP)) { struct btrfs_root *root_out = BTRFS_I(inode_out)->root; if (btrfs_root_readonly(root_out)) return -EROFS; if (file_in->f_path.mnt != file_out->f_path.mnt || inode_in->i_sb != inode_out->i_sb) return -EXDEV; } if (same_inode) inode_lock(inode_in); else btrfs_double_inode_lock(inode_in, inode_out); /* don't make the dst file partly checksummed */ if ((BTRFS_I(inode_in)->flags & BTRFS_INODE_NODATASUM) != (BTRFS_I(inode_out)->flags & BTRFS_INODE_NODATASUM)) { ret = -EINVAL; goto out_unlock; } /* * Now that the inodes are locked, we need to start writeback ourselves * and can not rely on the writeback from the VFS's generic helper * generic_remap_file_range_prep() because: * * 1) For compression we must call filemap_fdatawrite_range() range * twice (btrfs_fdatawrite_range() does it for us), and the generic * helper only calls it once; * * 2) filemap_fdatawrite_range(), called by the generic helper only * waits for the writeback to complete, i.e. for IO to be done, and * not for the ordered extents to complete. We need to wait for them * to complete so that new file extent items are in the fs tree. */ if (*len == 0 && !(remap_flags & REMAP_FILE_DEDUP)) wb_len = ALIGN(inode_in->i_size, bs) - ALIGN_DOWN(pos_in, bs); else wb_len = ALIGN(*len, bs); /* * Since we don't lock ranges, wait for ongoing lockless dio writes (as * any in progress could create its ordered extents after we wait for * existing ordered extents below). */ inode_dio_wait(inode_in); if (!same_inode) inode_dio_wait(inode_out); ret = btrfs_wait_ordered_range(inode_in, ALIGN_DOWN(pos_in, bs), wb_len); if (ret < 0) goto out_unlock; ret = btrfs_wait_ordered_range(inode_out, ALIGN_DOWN(pos_out, bs), wb_len); if (ret < 0) goto out_unlock; ret = generic_remap_file_range_prep(file_in, pos_in, file_out, pos_out, len, remap_flags); if (ret < 0 || *len == 0) goto out_unlock; return 0; out_unlock: if (same_inode) inode_unlock(inode_in); else btrfs_double_inode_unlock(inode_in, inode_out); return ret; } loff_t btrfs_remap_file_range(struct file *src_file, loff_t off, struct file *dst_file, loff_t destoff, loff_t len, unsigned int remap_flags) { struct inode *src_inode = file_inode(src_file); struct inode *dst_inode = file_inode(dst_file); bool same_inode = dst_inode == src_inode; int ret; if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY)) return -EINVAL; ret = btrfs_remap_file_range_prep(src_file, off, dst_file, destoff, &len, remap_flags); if (ret < 0 || len == 0) return ret; if (remap_flags & REMAP_FILE_DEDUP) ret = btrfs_extent_same(src_inode, off, len, dst_inode, destoff); else ret = btrfs_clone_files(dst_file, src_file, off, len, destoff); if (same_inode) inode_unlock(src_inode); else btrfs_double_inode_unlock(src_inode, dst_inode); return ret < 0 ? ret : len; } static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_root *new_root; struct btrfs_dir_item *di; struct btrfs_trans_handle *trans; struct btrfs_path *path; struct btrfs_key location; struct btrfs_disk_key disk_key; u64 objectid = 0; u64 dir_id; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (copy_from_user(&objectid, argp, sizeof(objectid))) { ret = -EFAULT; goto out; } if (!objectid) objectid = BTRFS_FS_TREE_OBJECTID; location.objectid = objectid; location.type = BTRFS_ROOT_ITEM_KEY; location.offset = (u64)-1; new_root = btrfs_read_fs_root_no_name(fs_info, &location); if (IS_ERR(new_root)) { ret = PTR_ERR(new_root); goto out; } if (!is_fstree(new_root->root_key.objectid)) { ret = -ENOENT; goto out; } path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->leave_spinning = 1; trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { btrfs_free_path(path); ret = PTR_ERR(trans); goto out; } dir_id = btrfs_super_root_dir(fs_info->super_copy); di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path, dir_id, "default", 7, 1); if (IS_ERR_OR_NULL(di)) { btrfs_free_path(path); btrfs_end_transaction(trans); btrfs_err(fs_info, "Umm, you don't have the default diritem, this isn't going to work"); ret = -ENOENT; goto out; } btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key); btrfs_set_dir_item_key(path->nodes[0], di, &disk_key); btrfs_mark_buffer_dirty(path->nodes[0]); btrfs_free_path(path); btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL); btrfs_end_transaction(trans); out: mnt_drop_write_file(file); return ret; } static void get_block_group_info(struct list_head *groups_list, struct btrfs_ioctl_space_info *space) { struct btrfs_block_group_cache *block_group; space->total_bytes = 0; space->used_bytes = 0; space->flags = 0; list_for_each_entry(block_group, groups_list, list) { space->flags = block_group->flags; space->total_bytes += block_group->key.offset; space->used_bytes += btrfs_block_group_used(&block_group->item); } } static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_space_args space_args; struct btrfs_ioctl_space_info space; struct btrfs_ioctl_space_info *dest; struct btrfs_ioctl_space_info *dest_orig; struct btrfs_ioctl_space_info __user *user_dest; struct btrfs_space_info *info; static const u64 types[] = { BTRFS_BLOCK_GROUP_DATA, BTRFS_BLOCK_GROUP_SYSTEM, BTRFS_BLOCK_GROUP_METADATA, BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA }; int num_types = 4; int alloc_size; int ret = 0; u64 slot_count = 0; int i, c; if (copy_from_user(&space_args, (struct btrfs_ioctl_space_args __user *)arg, sizeof(space_args))) return -EFAULT; for (i = 0; i < num_types; i++) { struct btrfs_space_info *tmp; info = NULL; rcu_read_lock(); list_for_each_entry_rcu(tmp, &fs_info->space_info, list) { if (tmp->flags == types[i]) { info = tmp; break; } } rcu_read_unlock(); if (!info) continue; down_read(&info->groups_sem); for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) { if (!list_empty(&info->block_groups[c])) slot_count++; } up_read(&info->groups_sem); } /* * Global block reserve, exported as a space_info */ slot_count++; /* space_slots == 0 means they are asking for a count */ if (space_args.space_slots == 0) { space_args.total_spaces = slot_count; goto out; } slot_count = min_t(u64, space_args.space_slots, slot_count); alloc_size = sizeof(*dest) * slot_count; /* we generally have at most 6 or so space infos, one for each raid * level. So, a whole page should be more than enough for everyone */ if (alloc_size > PAGE_SIZE) return -ENOMEM; space_args.total_spaces = 0; dest = kmalloc(alloc_size, GFP_KERNEL); if (!dest) return -ENOMEM; dest_orig = dest; /* now we have a buffer to copy into */ for (i = 0; i < num_types; i++) { struct btrfs_space_info *tmp; if (!slot_count) break; info = NULL; rcu_read_lock(); list_for_each_entry_rcu(tmp, &fs_info->space_info, list) { if (tmp->flags == types[i]) { info = tmp; break; } } rcu_read_unlock(); if (!info) continue; down_read(&info->groups_sem); for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) { if (!list_empty(&info->block_groups[c])) { get_block_group_info(&info->block_groups[c], &space); memcpy(dest, &space, sizeof(space)); dest++; space_args.total_spaces++; slot_count--; } if (!slot_count) break; } up_read(&info->groups_sem); } /* * Add global block reserve */ if (slot_count) { struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv; spin_lock(&block_rsv->lock); space.total_bytes = block_rsv->size; space.used_bytes = block_rsv->size - block_rsv->reserved; spin_unlock(&block_rsv->lock); space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV; memcpy(dest, &space, sizeof(space)); space_args.total_spaces++; } user_dest = (struct btrfs_ioctl_space_info __user *) (arg + sizeof(struct btrfs_ioctl_space_args)); if (copy_to_user(user_dest, dest_orig, alloc_size)) ret = -EFAULT; kfree(dest_orig); out: if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args))) ret = -EFAULT; return ret; } static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root, void __user *argp) { struct btrfs_trans_handle *trans; u64 transid; int ret; trans = btrfs_attach_transaction_barrier(root); if (IS_ERR(trans)) { if (PTR_ERR(trans) != -ENOENT) return PTR_ERR(trans); /* No running transaction, don't bother */ transid = root->fs_info->last_trans_committed; goto out; } transid = trans->transid; ret = btrfs_commit_transaction_async(trans, 0); if (ret) { btrfs_end_transaction(trans); return ret; } out: if (argp) if (copy_to_user(argp, &transid, sizeof(transid))) return -EFAULT; return 0; } static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info, void __user *argp) { u64 transid; if (argp) { if (copy_from_user(&transid, argp, sizeof(transid))) return -EFAULT; } else { transid = 0; /* current trans */ } return btrfs_wait_for_commit(fs_info, transid); } static long btrfs_ioctl_scrub(struct file *file, void __user *arg) { struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb); struct btrfs_ioctl_scrub_args *sa; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); if (!(sa->flags & BTRFS_SCRUB_READONLY)) { ret = mnt_want_write_file(file); if (ret) goto out; } ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end, &sa->progress, sa->flags & BTRFS_SCRUB_READONLY, 0); if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; if (!(sa->flags & BTRFS_SCRUB_READONLY)) mnt_drop_write_file(file); out: kfree(sa); return ret; } static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; return btrfs_scrub_cancel(fs_info); } static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_scrub_args *sa; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress); if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; kfree(sa); return ret; } static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_get_dev_stats *sa; int ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) { kfree(sa); return -EPERM; } ret = btrfs_get_dev_stats(fs_info, sa); if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; kfree(sa); return ret; } static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_dev_replace_args *p; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; p = memdup_user(arg, sizeof(*p)); if (IS_ERR(p)) return PTR_ERR(p); switch (p->cmd) { case BTRFS_IOCTL_DEV_REPLACE_CMD_START: if (sb_rdonly(fs_info->sb)) { ret = -EROFS; goto out; } if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; } else { ret = btrfs_dev_replace_by_ioctl(fs_info, p); clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); } break; case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS: btrfs_dev_replace_status(fs_info, p); ret = 0; break; case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL: p->result = btrfs_dev_replace_cancel(fs_info); ret = 0; break; default: ret = -EINVAL; break; } if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p))) ret = -EFAULT; out: kfree(p); return ret; } static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg) { int ret = 0; int i; u64 rel_ptr; int size; struct btrfs_ioctl_ino_path_args *ipa = NULL; struct inode_fs_paths *ipath = NULL; struct btrfs_path *path; if (!capable(CAP_DAC_READ_SEARCH)) return -EPERM; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } ipa = memdup_user(arg, sizeof(*ipa)); if (IS_ERR(ipa)) { ret = PTR_ERR(ipa); ipa = NULL; goto out; } size = min_t(u32, ipa->size, 4096); ipath = init_ipath(size, root, path); if (IS_ERR(ipath)) { ret = PTR_ERR(ipath); ipath = NULL; goto out; } ret = paths_from_inode(ipa->inum, ipath); if (ret < 0) goto out; for (i = 0; i < ipath->fspath->elem_cnt; ++i) { rel_ptr = ipath->fspath->val[i] - (u64)(unsigned long)ipath->fspath->val; ipath->fspath->val[i] = rel_ptr; } ret = copy_to_user((void __user *)(unsigned long)ipa->fspath, ipath->fspath, size); if (ret) { ret = -EFAULT; goto out; } out: btrfs_free_path(path); free_ipath(ipath); kfree(ipa); return ret; } static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx) { struct btrfs_data_container *inodes = ctx; const size_t c = 3 * sizeof(u64); if (inodes->bytes_left >= c) { inodes->bytes_left -= c; inodes->val[inodes->elem_cnt] = inum; inodes->val[inodes->elem_cnt + 1] = offset; inodes->val[inodes->elem_cnt + 2] = root; inodes->elem_cnt += 3; } else { inodes->bytes_missing += c - inodes->bytes_left; inodes->bytes_left = 0; inodes->elem_missed += 3; } return 0; } static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info, void __user *arg, int version) { int ret = 0; int size; struct btrfs_ioctl_logical_ino_args *loi; struct btrfs_data_container *inodes = NULL; struct btrfs_path *path = NULL; bool ignore_offset; if (!capable(CAP_SYS_ADMIN)) return -EPERM; loi = memdup_user(arg, sizeof(*loi)); if (IS_ERR(loi)) return PTR_ERR(loi); if (version == 1) { ignore_offset = false; size = min_t(u32, loi->size, SZ_64K); } else { /* All reserved bits must be 0 for now */ if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) { ret = -EINVAL; goto out_loi; } /* Only accept flags we have defined so far */ if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) { ret = -EINVAL; goto out_loi; } ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET; size = min_t(u32, loi->size, SZ_16M); } path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } inodes = init_data_container(size); if (IS_ERR(inodes)) { ret = PTR_ERR(inodes); inodes = NULL; goto out; } ret = iterate_inodes_from_logical(loi->logical, fs_info, path, build_ino_list, inodes, ignore_offset); if (ret == -EINVAL) ret = -ENOENT; if (ret < 0) goto out; ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes, size); if (ret) ret = -EFAULT; out: btrfs_free_path(path); kvfree(inodes); out_loi: kfree(loi); return ret; } void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info, struct btrfs_ioctl_balance_args *bargs) { struct btrfs_balance_control *bctl = fs_info->balance_ctl; bargs->flags = bctl->flags; if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) bargs->state |= BTRFS_BALANCE_STATE_RUNNING; if (atomic_read(&fs_info->balance_pause_req)) bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ; if (atomic_read(&fs_info->balance_cancel_req)) bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ; memcpy(&bargs->data, &bctl->data, sizeof(bargs->data)); memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta)); memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys)); spin_lock(&fs_info->balance_lock); memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat)); spin_unlock(&fs_info->balance_lock); } static long btrfs_ioctl_balance(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(file_inode(file))->root; struct btrfs_fs_info *fs_info = root->fs_info; struct btrfs_ioctl_balance_args *bargs; struct btrfs_balance_control *bctl; bool need_unlock; /* for mut. excl. ops lock */ int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; again: if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { mutex_lock(&fs_info->balance_mutex); need_unlock = true; goto locked; } /* * mut. excl. ops lock is locked. Three possibilities: * (1) some other op is running * (2) balance is running * (3) balance is paused -- special case (think resume) */ mutex_lock(&fs_info->balance_mutex); if (fs_info->balance_ctl) { /* this is either (2) or (3) */ if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) { mutex_unlock(&fs_info->balance_mutex); /* * Lock released to allow other waiters to continue, * we'll reexamine the status again. */ mutex_lock(&fs_info->balance_mutex); if (fs_info->balance_ctl && !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) { /* this is (3) */ need_unlock = false; goto locked; } mutex_unlock(&fs_info->balance_mutex); goto again; } else { /* this is (2) */ mutex_unlock(&fs_info->balance_mutex); ret = -EINPROGRESS; goto out; } } else { /* this is (1) */ mutex_unlock(&fs_info->balance_mutex); ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; goto out; } locked: BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)); if (arg) { bargs = memdup_user(arg, sizeof(*bargs)); if (IS_ERR(bargs)) { ret = PTR_ERR(bargs); goto out_unlock; } if (bargs->flags & BTRFS_BALANCE_RESUME) { if (!fs_info->balance_ctl) { ret = -ENOTCONN; goto out_bargs; } bctl = fs_info->balance_ctl; spin_lock(&fs_info->balance_lock); bctl->flags |= BTRFS_BALANCE_RESUME; spin_unlock(&fs_info->balance_lock); goto do_balance; } } else { bargs = NULL; } if (fs_info->balance_ctl) { ret = -EINPROGRESS; goto out_bargs; } bctl = kzalloc(sizeof(*bctl), GFP_KERNEL); if (!bctl) { ret = -ENOMEM; goto out_bargs; } if (arg) { memcpy(&bctl->data, &bargs->data, sizeof(bctl->data)); memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta)); memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys)); bctl->flags = bargs->flags; } else { /* balance everything - no filters */ bctl->flags |= BTRFS_BALANCE_TYPE_MASK; } if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) { ret = -EINVAL; goto out_bctl; } do_balance: /* * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to * btrfs_balance. bctl is freed in reset_balance_state, or, if * restriper was paused all the way until unmount, in free_fs_info. * The flag should be cleared after reset_balance_state. */ need_unlock = false; ret = btrfs_balance(fs_info, bctl, bargs); bctl = NULL; if ((ret == 0 || ret == -ECANCELED) && arg) { if (copy_to_user(arg, bargs, sizeof(*bargs))) ret = -EFAULT; } out_bctl: kfree(bctl); out_bargs: kfree(bargs); out_unlock: mutex_unlock(&fs_info->balance_mutex); if (need_unlock) clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); out: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; switch (cmd) { case BTRFS_BALANCE_CTL_PAUSE: return btrfs_pause_balance(fs_info); case BTRFS_BALANCE_CTL_CANCEL: return btrfs_cancel_balance(fs_info); } return -EINVAL; } static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info, void __user *arg) { struct btrfs_ioctl_balance_args *bargs; int ret = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&fs_info->balance_mutex); if (!fs_info->balance_ctl) { ret = -ENOTCONN; goto out; } bargs = kzalloc(sizeof(*bargs), GFP_KERNEL); if (!bargs) { ret = -ENOMEM; goto out; } btrfs_update_ioctl_balance_args(fs_info, bargs); if (copy_to_user(arg, bargs, sizeof(*bargs))) ret = -EFAULT; kfree(bargs); out: mutex_unlock(&fs_info->balance_mutex); return ret; } static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_ioctl_quota_ctl_args *sa; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } down_write(&fs_info->subvol_sem); switch (sa->cmd) { case BTRFS_QUOTA_CTL_ENABLE: ret = btrfs_quota_enable(fs_info); break; case BTRFS_QUOTA_CTL_DISABLE: ret = btrfs_quota_disable(fs_info); break; default: ret = -EINVAL; break; } kfree(sa); up_write(&fs_info->subvol_sem); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_qgroup_assign_args *sa; struct btrfs_trans_handle *trans; int ret; int err; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } if (sa->assign) { ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst); } else { ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst); } /* update qgroup status and info */ err = btrfs_run_qgroups(trans); if (err < 0) btrfs_handle_fs_error(fs_info, err, "failed to update qgroup status and info"); err = btrfs_end_transaction(trans); if (err && !ret) ret = err; out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_qgroup_create_args *sa; struct btrfs_trans_handle *trans; int ret; int err; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } if (!sa->qgroupid) { ret = -EINVAL; goto out; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } if (sa->create) { ret = btrfs_create_qgroup(trans, sa->qgroupid); } else { ret = btrfs_remove_qgroup(trans, sa->qgroupid); } err = btrfs_end_transaction(trans); if (err && !ret) ret = err; out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_qgroup_limit_args *sa; struct btrfs_trans_handle *trans; int ret; int err; u64 qgroupid; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } qgroupid = sa->qgroupid; if (!qgroupid) { /* take the current subvol as qgroup */ qgroupid = root->root_key.objectid; } ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim); err = btrfs_end_transaction(trans); if (err && !ret) ret = err; out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_ioctl_quota_rescan_args *qsa; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; qsa = memdup_user(arg, sizeof(*qsa)); if (IS_ERR(qsa)) { ret = PTR_ERR(qsa); goto drop_write; } if (qsa->flags) { ret = -EINVAL; goto out; } ret = btrfs_qgroup_rescan(fs_info); out: kfree(qsa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_ioctl_quota_rescan_args *qsa; int ret = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; qsa = kzalloc(sizeof(*qsa), GFP_KERNEL); if (!qsa) return -ENOMEM; if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) { qsa->flags = 1; qsa->progress = fs_info->qgroup_rescan_progress.objectid; } if (copy_to_user(arg, qsa, sizeof(*qsa))) ret = -EFAULT; kfree(qsa); return ret; } static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); if (!capable(CAP_SYS_ADMIN)) return -EPERM; return btrfs_qgroup_wait_for_completion(fs_info, true); } static long _btrfs_ioctl_set_received_subvol(struct file *file, struct btrfs_ioctl_received_subvol_args *sa) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_root_item *root_item = &root->root_item; struct btrfs_trans_handle *trans; struct timespec64 ct = current_time(inode); int ret = 0; int received_uuid_changed; if (!inode_owner_or_capable(inode)) return -EPERM; ret = mnt_want_write_file(file); if (ret < 0) return ret; down_write(&fs_info->subvol_sem); if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) { ret = -EINVAL; goto out; } if (btrfs_root_readonly(root)) { ret = -EROFS; goto out; } /* * 1 - root item * 2 - uuid items (received uuid + subvol uuid) */ trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out; } sa->rtransid = trans->transid; sa->rtime.sec = ct.tv_sec; sa->rtime.nsec = ct.tv_nsec; received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE); if (received_uuid_changed && !btrfs_is_empty_uuid(root_item->received_uuid)) { ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid, BTRFS_UUID_KEY_RECEIVED_SUBVOL, root->root_key.objectid); if (ret && ret != -ENOENT) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } } memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE); btrfs_set_root_stransid(root_item, sa->stransid); btrfs_set_root_rtransid(root_item, sa->rtransid); btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec); btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec); btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec); btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec); ret = btrfs_update_root(trans, fs_info->tree_root, &root->root_key, &root->root_item); if (ret < 0) { btrfs_end_transaction(trans); goto out; } if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) { ret = btrfs_uuid_tree_add(trans, sa->uuid, BTRFS_UUID_KEY_RECEIVED_SUBVOL, root->root_key.objectid); if (ret < 0 && ret != -EEXIST) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } } ret = btrfs_commit_transaction(trans); out: up_write(&fs_info->subvol_sem); mnt_drop_write_file(file); return ret; } #ifdef CONFIG_64BIT static long btrfs_ioctl_set_received_subvol_32(struct file *file, void __user *arg) { struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL; struct btrfs_ioctl_received_subvol_args *args64 = NULL; int ret = 0; args32 = memdup_user(arg, sizeof(*args32)); if (IS_ERR(args32)) return PTR_ERR(args32); args64 = kmalloc(sizeof(*args64), GFP_KERNEL); if (!args64) { ret = -ENOMEM; goto out; } memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE); args64->stransid = args32->stransid; args64->rtransid = args32->rtransid; args64->stime.sec = args32->stime.sec; args64->stime.nsec = args32->stime.nsec; args64->rtime.sec = args32->rtime.sec; args64->rtime.nsec = args32->rtime.nsec; args64->flags = args32->flags; ret = _btrfs_ioctl_set_received_subvol(file, args64); if (ret) goto out; memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE); args32->stransid = args64->stransid; args32->rtransid = args64->rtransid; args32->stime.sec = args64->stime.sec; args32->stime.nsec = args64->stime.nsec; args32->rtime.sec = args64->rtime.sec; args32->rtime.nsec = args64->rtime.nsec; args32->flags = args64->flags; ret = copy_to_user(arg, args32, sizeof(*args32)); if (ret) ret = -EFAULT; out: kfree(args32); kfree(args64); return ret; } #endif static long btrfs_ioctl_set_received_subvol(struct file *file, void __user *arg) { struct btrfs_ioctl_received_subvol_args *sa = NULL; int ret = 0; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); ret = _btrfs_ioctl_set_received_subvol(file, sa); if (ret) goto out; ret = copy_to_user(arg, sa, sizeof(*sa)); if (ret) ret = -EFAULT; out: kfree(sa); return ret; } static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); size_t len; int ret; char label[BTRFS_LABEL_SIZE]; spin_lock(&fs_info->super_lock); memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE); spin_unlock(&fs_info->super_lock); len = strnlen(label, BTRFS_LABEL_SIZE); if (len == BTRFS_LABEL_SIZE) { btrfs_warn(fs_info, "label is too long, return the first %zu bytes", --len); } ret = copy_to_user(arg, label, len); return ret ? -EFAULT : 0; } static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_super_block *super_block = fs_info->super_copy; struct btrfs_trans_handle *trans; char label[BTRFS_LABEL_SIZE]; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(label, arg, sizeof(label))) return -EFAULT; if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) { btrfs_err(fs_info, "unable to set label with more than %d bytes", BTRFS_LABEL_SIZE - 1); return -EINVAL; } ret = mnt_want_write_file(file); if (ret) return ret; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_unlock; } spin_lock(&fs_info->super_lock); strcpy(super_block->label, label); spin_unlock(&fs_info->super_lock); ret = btrfs_commit_transaction(trans); out_unlock: mnt_drop_write_file(file); return ret; } #define INIT_FEATURE_FLAGS(suffix) \ { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \ .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \ .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix } int btrfs_ioctl_get_supported_features(void __user *arg) { static const struct btrfs_ioctl_feature_flags features[3] = { INIT_FEATURE_FLAGS(SUPP), INIT_FEATURE_FLAGS(SAFE_SET), INIT_FEATURE_FLAGS(SAFE_CLEAR) }; if (copy_to_user(arg, &features, sizeof(features))) return -EFAULT; return 0; } static int btrfs_ioctl_get_features(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_super_block *super_block = fs_info->super_copy; struct btrfs_ioctl_feature_flags features; features.compat_flags = btrfs_super_compat_flags(super_block); features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block); features.incompat_flags = btrfs_super_incompat_flags(super_block); if (copy_to_user(arg, &features, sizeof(features))) return -EFAULT; return 0; } static int check_feature_bits(struct btrfs_fs_info *fs_info, enum btrfs_feature_set set, u64 change_mask, u64 flags, u64 supported_flags, u64 safe_set, u64 safe_clear) { const char *type = btrfs_feature_set_names[set]; char *names; u64 disallowed, unsupported; u64 set_mask = flags & change_mask; u64 clear_mask = ~flags & change_mask; unsupported = set_mask & ~supported_flags; if (unsupported) { names = btrfs_printable_features(set, unsupported); if (names) { btrfs_warn(fs_info, "this kernel does not support the %s feature bit%s", names, strchr(names, ',') ? "s" : ""); kfree(names); } else btrfs_warn(fs_info, "this kernel does not support %s bits 0x%llx", type, unsupported); return -EOPNOTSUPP; } disallowed = set_mask & ~safe_set; if (disallowed) { names = btrfs_printable_features(set, disallowed); if (names) { btrfs_warn(fs_info, "can't set the %s feature bit%s while mounted", names, strchr(names, ',') ? "s" : ""); kfree(names); } else btrfs_warn(fs_info, "can't set %s bits 0x%llx while mounted", type, disallowed); return -EPERM; } disallowed = clear_mask & ~safe_clear; if (disallowed) { names = btrfs_printable_features(set, disallowed); if (names) { btrfs_warn(fs_info, "can't clear the %s feature bit%s while mounted", names, strchr(names, ',') ? "s" : ""); kfree(names); } else btrfs_warn(fs_info, "can't clear %s bits 0x%llx while mounted", type, disallowed); return -EPERM; } return 0; } #define check_feature(fs_info, change_mask, flags, mask_base) \ check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags, \ BTRFS_FEATURE_ ## mask_base ## _SUPP, \ BTRFS_FEATURE_ ## mask_base ## _SAFE_SET, \ BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR) static int btrfs_ioctl_set_features(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_super_block *super_block = fs_info->super_copy; struct btrfs_ioctl_feature_flags flags[2]; struct btrfs_trans_handle *trans; u64 newflags; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(flags, arg, sizeof(flags))) return -EFAULT; /* Nothing to do */ if (!flags[0].compat_flags && !flags[0].compat_ro_flags && !flags[0].incompat_flags) return 0; ret = check_feature(fs_info, flags[0].compat_flags, flags[1].compat_flags, COMPAT); if (ret) return ret; ret = check_feature(fs_info, flags[0].compat_ro_flags, flags[1].compat_ro_flags, COMPAT_RO); if (ret) return ret; ret = check_feature(fs_info, flags[0].incompat_flags, flags[1].incompat_flags, INCOMPAT); if (ret) return ret; ret = mnt_want_write_file(file); if (ret) return ret; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_drop_write; } spin_lock(&fs_info->super_lock); newflags = btrfs_super_compat_flags(super_block); newflags |= flags[0].compat_flags & flags[1].compat_flags; newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags); btrfs_set_super_compat_flags(super_block, newflags); newflags = btrfs_super_compat_ro_flags(super_block); newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags; newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags); btrfs_set_super_compat_ro_flags(super_block, newflags); newflags = btrfs_super_incompat_flags(super_block); newflags |= flags[0].incompat_flags & flags[1].incompat_flags; newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags); btrfs_set_super_incompat_flags(super_block, newflags); spin_unlock(&fs_info->super_lock); ret = btrfs_commit_transaction(trans); out_drop_write: mnt_drop_write_file(file); return ret; } static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat) { struct btrfs_ioctl_send_args *arg; int ret; if (compat) { #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT) struct btrfs_ioctl_send_args_32 args32; ret = copy_from_user(&args32, argp, sizeof(args32)); if (ret) return -EFAULT; arg = kzalloc(sizeof(*arg), GFP_KERNEL); if (!arg) return -ENOMEM; arg->send_fd = args32.send_fd; arg->clone_sources_count = args32.clone_sources_count; arg->clone_sources = compat_ptr(args32.clone_sources); arg->parent_root = args32.parent_root; arg->flags = args32.flags; memcpy(arg->reserved, args32.reserved, sizeof(args32.reserved)); #else return -ENOTTY; #endif } else { arg = memdup_user(argp, sizeof(*arg)); if (IS_ERR(arg)) return PTR_ERR(arg); } ret = btrfs_ioctl_send(file, arg); kfree(arg); return ret; } long btrfs_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); struct btrfs_root *root = BTRFS_I(inode)->root; void __user *argp = (void __user *)arg; switch (cmd) { case FS_IOC_GETFLAGS: return btrfs_ioctl_getflags(file, argp); case FS_IOC_SETFLAGS: return btrfs_ioctl_setflags(file, argp); case FS_IOC_GETVERSION: return btrfs_ioctl_getversion(file, argp); case FITRIM: return btrfs_ioctl_fitrim(file, argp); case BTRFS_IOC_SNAP_CREATE: return btrfs_ioctl_snap_create(file, argp, 0); case BTRFS_IOC_SNAP_CREATE_V2: return btrfs_ioctl_snap_create_v2(file, argp, 0); case BTRFS_IOC_SUBVOL_CREATE: return btrfs_ioctl_snap_create(file, argp, 1); case BTRFS_IOC_SUBVOL_CREATE_V2: return btrfs_ioctl_snap_create_v2(file, argp, 1); case BTRFS_IOC_SNAP_DESTROY: return btrfs_ioctl_snap_destroy(file, argp); case BTRFS_IOC_SUBVOL_GETFLAGS: return btrfs_ioctl_subvol_getflags(file, argp); case BTRFS_IOC_SUBVOL_SETFLAGS: return btrfs_ioctl_subvol_setflags(file, argp); case BTRFS_IOC_DEFAULT_SUBVOL: return btrfs_ioctl_default_subvol(file, argp); case BTRFS_IOC_DEFRAG: return btrfs_ioctl_defrag(file, NULL); case BTRFS_IOC_DEFRAG_RANGE: return btrfs_ioctl_defrag(file, argp); case BTRFS_IOC_RESIZE: return btrfs_ioctl_resize(file, argp); case BTRFS_IOC_ADD_DEV: return btrfs_ioctl_add_dev(fs_info, argp); case BTRFS_IOC_RM_DEV: return btrfs_ioctl_rm_dev(file, argp); case BTRFS_IOC_RM_DEV_V2: return btrfs_ioctl_rm_dev_v2(file, argp); case BTRFS_IOC_FS_INFO: return btrfs_ioctl_fs_info(fs_info, argp); case BTRFS_IOC_DEV_INFO: return btrfs_ioctl_dev_info(fs_info, argp); case BTRFS_IOC_BALANCE: return btrfs_ioctl_balance(file, NULL); case BTRFS_IOC_TREE_SEARCH: return btrfs_ioctl_tree_search(file, argp); case BTRFS_IOC_TREE_SEARCH_V2: return btrfs_ioctl_tree_search_v2(file, argp); case BTRFS_IOC_INO_LOOKUP: return btrfs_ioctl_ino_lookup(file, argp); case BTRFS_IOC_INO_PATHS: return btrfs_ioctl_ino_to_path(root, argp); case BTRFS_IOC_LOGICAL_INO: return btrfs_ioctl_logical_to_ino(fs_info, argp, 1); case BTRFS_IOC_LOGICAL_INO_V2: return btrfs_ioctl_logical_to_ino(fs_info, argp, 2); case BTRFS_IOC_SPACE_INFO: return btrfs_ioctl_space_info(fs_info, argp); case BTRFS_IOC_SYNC: { int ret; ret = btrfs_start_delalloc_roots(fs_info, -1); if (ret) return ret; ret = btrfs_sync_fs(inode->i_sb, 1); /* * The transaction thread may want to do more work, * namely it pokes the cleaner kthread that will start * processing uncleaned subvols. */ wake_up_process(fs_info->transaction_kthread); return ret; } case BTRFS_IOC_START_SYNC: return btrfs_ioctl_start_sync(root, argp); case BTRFS_IOC_WAIT_SYNC: return btrfs_ioctl_wait_sync(fs_info, argp); case BTRFS_IOC_SCRUB: return btrfs_ioctl_scrub(file, argp); case BTRFS_IOC_SCRUB_CANCEL: return btrfs_ioctl_scrub_cancel(fs_info); case BTRFS_IOC_SCRUB_PROGRESS: return btrfs_ioctl_scrub_progress(fs_info, argp); case BTRFS_IOC_BALANCE_V2: return btrfs_ioctl_balance(file, argp); case BTRFS_IOC_BALANCE_CTL: return btrfs_ioctl_balance_ctl(fs_info, arg); case BTRFS_IOC_BALANCE_PROGRESS: return btrfs_ioctl_balance_progress(fs_info, argp); case BTRFS_IOC_SET_RECEIVED_SUBVOL: return btrfs_ioctl_set_received_subvol(file, argp); #ifdef CONFIG_64BIT case BTRFS_IOC_SET_RECEIVED_SUBVOL_32: return btrfs_ioctl_set_received_subvol_32(file, argp); #endif case BTRFS_IOC_SEND: return _btrfs_ioctl_send(file, argp, false); #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT) case BTRFS_IOC_SEND_32: return _btrfs_ioctl_send(file, argp, true); #endif case BTRFS_IOC_GET_DEV_STATS: return btrfs_ioctl_get_dev_stats(fs_info, argp); case BTRFS_IOC_QUOTA_CTL: return btrfs_ioctl_quota_ctl(file, argp); case BTRFS_IOC_QGROUP_ASSIGN: return btrfs_ioctl_qgroup_assign(file, argp); case BTRFS_IOC_QGROUP_CREATE: return btrfs_ioctl_qgroup_create(file, argp); case BTRFS_IOC_QGROUP_LIMIT: return btrfs_ioctl_qgroup_limit(file, argp); case BTRFS_IOC_QUOTA_RESCAN: return btrfs_ioctl_quota_rescan(file, argp); case BTRFS_IOC_QUOTA_RESCAN_STATUS: return btrfs_ioctl_quota_rescan_status(file, argp); case BTRFS_IOC_QUOTA_RESCAN_WAIT: return btrfs_ioctl_quota_rescan_wait(file, argp); case BTRFS_IOC_DEV_REPLACE: return btrfs_ioctl_dev_replace(fs_info, argp); case BTRFS_IOC_GET_FSLABEL: return btrfs_ioctl_get_fslabel(file, argp); case BTRFS_IOC_SET_FSLABEL: return btrfs_ioctl_set_fslabel(file, argp); case BTRFS_IOC_GET_SUPPORTED_FEATURES: return btrfs_ioctl_get_supported_features(argp); case BTRFS_IOC_GET_FEATURES: return btrfs_ioctl_get_features(file, argp); case BTRFS_IOC_SET_FEATURES: return btrfs_ioctl_set_features(file, argp); case FS_IOC_FSGETXATTR: return btrfs_ioctl_fsgetxattr(file, argp); case FS_IOC_FSSETXATTR: return btrfs_ioctl_fssetxattr(file, argp); case BTRFS_IOC_GET_SUBVOL_INFO: return btrfs_ioctl_get_subvol_info(file, argp); case BTRFS_IOC_GET_SUBVOL_ROOTREF: return btrfs_ioctl_get_subvol_rootref(file, argp); case BTRFS_IOC_INO_LOOKUP_USER: return btrfs_ioctl_ino_lookup_user(file, argp); } return -ENOTTY; } #ifdef CONFIG_COMPAT long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { /* * These all access 32-bit values anyway so no further * handling is necessary. */ switch (cmd) { case FS_IOC32_GETFLAGS: cmd = FS_IOC_GETFLAGS; break; case FS_IOC32_SETFLAGS: cmd = FS_IOC_SETFLAGS; break; case FS_IOC32_GETVERSION: cmd = FS_IOC_GETVERSION; break; } return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg)); } #endif
./CrossVul/dataset_final_sorted/CWE-476/c/good_1223_1
crossvul-cpp_data_good_4477_0
/* $OpenBSD: lka_filter.c,v 1.65 2020/12/23 20:17:49 millert Exp $ */ /* * Copyright (c) 2018 Gilles Chehade <gilles@poolp.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <sys/queue.h> #include <sys/tree.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <event.h> #include <imsg.h> #include <inttypes.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "smtpd.h" #include "log.h" #define PROTOCOL_VERSION "0.6" struct filter; struct filter_session; static void filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *); static void filter_protocol(uint64_t, enum filter_phase, const char *); static void filter_protocol_next(uint64_t, uint64_t, enum filter_phase); static void filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *); static void filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *); static void filter_data(uint64_t, const char *); static void filter_data_next(uint64_t, uint64_t, const char *); static void filter_data_query(struct filter *, uint64_t, uint64_t, const char *); static int filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *); static int filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *); static int filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *); static int filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *); static int filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *); static int filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *); static int filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *); static void filter_result_proceed(uint64_t); static void filter_result_junk(uint64_t); static void filter_result_rewrite(uint64_t, const char *); static void filter_result_reject(uint64_t, const char *); static void filter_result_disconnect(uint64_t, const char *); static void filter_session_io(struct io *, int, void *); void lka_filter_process_response(const char *, const char *); struct filter_session { uint64_t id; struct io *io; char *lastparam; char *filter_name; struct sockaddr_storage ss_src; struct sockaddr_storage ss_dest; char *rdns; int fcrdns; char *helo; char *username; char *mail_from; enum filter_phase phase; }; static struct filter_exec { enum filter_phase phase; const char *phase_name; int (*func)(struct filter_session *, struct filter *, uint64_t, const char *); } filter_execs[FILTER_PHASES_COUNT] = { { FILTER_CONNECT, "connect", filter_builtins_connect }, { FILTER_HELO, "helo", filter_builtins_helo }, { FILTER_EHLO, "ehlo", filter_builtins_helo }, { FILTER_STARTTLS, "starttls", filter_builtins_notimpl }, { FILTER_AUTH, "auth", filter_builtins_notimpl }, { FILTER_MAIL_FROM, "mail-from", filter_builtins_mail_from }, { FILTER_RCPT_TO, "rcpt-to", filter_builtins_rcpt_to }, { FILTER_DATA, "data", filter_builtins_data }, { FILTER_DATA_LINE, "data-line", filter_builtins_notimpl }, { FILTER_RSET, "rset", filter_builtins_notimpl }, { FILTER_QUIT, "quit", filter_builtins_notimpl }, { FILTER_NOOP, "noop", filter_builtins_notimpl }, { FILTER_HELP, "help", filter_builtins_notimpl }, { FILTER_WIZ, "wiz", filter_builtins_notimpl }, { FILTER_COMMIT, "commit", filter_builtins_commit }, }; struct filter { uint64_t id; uint32_t phases; const char *name; const char *proc; struct filter **chain; size_t chain_size; struct filter_config *config; }; static struct dict filters; struct filter_entry { TAILQ_ENTRY(filter_entry) entries; uint64_t id; const char *name; }; struct filter_chain { TAILQ_HEAD(, filter_entry) chain[nitems(filter_execs)]; }; static struct dict filter_smtp_in; static struct tree sessions; static int filters_inited; static struct dict filter_chains; struct reporter_proc { TAILQ_ENTRY(reporter_proc) entries; const char *name; }; TAILQ_HEAD(reporters, reporter_proc); static struct dict report_smtp_in; static struct dict report_smtp_out; static struct smtp_events { const char *event; } smtp_events[] = { { "link-connect" }, { "link-disconnect" }, { "link-greeting" }, { "link-identify" }, { "link-tls" }, { "link-auth" }, { "tx-reset" }, { "tx-begin" }, { "tx-mail" }, { "tx-rcpt" }, { "tx-envelope" }, { "tx-data" }, { "tx-commit" }, { "tx-rollback" }, { "protocol-client" }, { "protocol-server" }, { "filter-report" }, { "filter-response" }, { "timeout" }, }; static int processors_inited = 0; static struct dict processors; struct processor_instance { char *name; struct io *io; struct io *errfd; int ready; uint32_t subsystems; }; static void processor_io(struct io *, int, void *); static void processor_errfd(struct io *, int, void *); void lka_filter_process_response(const char *, const char *); int lka_proc_ready(void) { void *iter; struct processor_instance *pi; iter = NULL; while (dict_iter(&processors, &iter, NULL, (void **)&pi)) if (!pi->ready) return 0; return 1; } static void lka_proc_config(struct processor_instance *pi) { io_printf(pi->io, "config|smtpd-version|%s\n", SMTPD_VERSION); io_printf(pi->io, "config|smtp-session-timeout|%d\n", SMTPD_SESSION_TIMEOUT); if (pi->subsystems & FILTER_SUBSYSTEM_SMTP_IN) io_printf(pi->io, "config|subsystem|smtp-in\n"); if (pi->subsystems & FILTER_SUBSYSTEM_SMTP_OUT) io_printf(pi->io, "config|subsystem|smtp-out\n"); io_printf(pi->io, "config|admd|%s\n", env->sc_admd != NULL ? env->sc_admd : env->sc_hostname); io_printf(pi->io, "config|ready\n"); } void lka_proc_forked(const char *name, uint32_t subsystems, int fd) { struct processor_instance *processor; if (!processors_inited) { dict_init(&processors); processors_inited = 1; } processor = xcalloc(1, sizeof *processor); processor->name = xstrdup(name); processor->io = io_new(); processor->subsystems = subsystems; io_set_nonblocking(fd); io_set_fd(processor->io, fd); io_set_callback(processor->io, processor_io, processor->name); dict_xset(&processors, name, processor); } void lka_proc_errfd(const char *name, int fd) { struct processor_instance *processor; processor = dict_xget(&processors, name); io_set_nonblocking(fd); processor->errfd = io_new(); io_set_fd(processor->errfd, fd); io_set_callback(processor->errfd, processor_errfd, processor->name); lka_proc_config(processor); } struct io * lka_proc_get_io(const char *name) { struct processor_instance *processor; processor = dict_xget(&processors, name); return processor->io; } static void processor_register(const char *name, const char *line) { struct processor_instance *processor; processor = dict_xget(&processors, name); if (strcmp(line, "register|ready") == 0) { processor->ready = 1; return; } if (strncmp(line, "register|report|", 16) == 0) { lka_report_register_hook(name, line+16); return; } if (strncmp(line, "register|filter|", 16) == 0) { lka_filter_register_hook(name, line+16); return; } fatalx("Invalid register line received: %s", line); } static void processor_io(struct io *io, int evt, void *arg) { struct processor_instance *processor; const char *name = arg; char *line = NULL; ssize_t len; switch (evt) { case IO_DATAIN: while ((line = io_getline(io, &len)) != NULL) { if (strncmp("register|", line, 9) == 0) { processor_register(name, line); continue; } processor = dict_xget(&processors, name); if (!processor->ready) fatalx("Non-register message before register|" "ready: %s", line); else if (strncmp(line, "filter-result|", 14) == 0 || strncmp(line, "filter-dataline|", 16) == 0) lka_filter_process_response(name, line); else if (strncmp(line, "report|", 7) == 0) lka_report_proc(name, line); else fatalx("Invalid filter message type: %s", line); } } } static void processor_errfd(struct io *io, int evt, void *arg) { const char *name = arg; char *line = NULL; ssize_t len; switch (evt) { case IO_DATAIN: while ((line = io_getline(io, &len)) != NULL) log_warnx("%s: %s", name, line); } } void lka_filter_init(void) { void *iter; const char *name; struct filter *filter; struct filter_config *filter_config; size_t i; char buffer[LINE_MAX]; /* for traces */ dict_init(&filters); dict_init(&filter_chains); /* first pass, allocate and init individual filters */ iter = NULL; while (dict_iter(env->sc_filters_dict, &iter, &name, (void **)&filter_config)) { switch (filter_config->filter_type) { case FILTER_TYPE_BUILTIN: filter = xcalloc(1, sizeof(*filter)); filter->name = name; filter->phases |= (1<<filter_config->phase); filter->config = filter_config; dict_set(&filters, name, filter); log_trace(TRACE_FILTERS, "filters init type=builtin, name=%s, hooks=%08x", name, filter->phases); break; case FILTER_TYPE_PROC: filter = xcalloc(1, sizeof(*filter)); filter->name = name; filter->proc = filter_config->proc; filter->config = filter_config; dict_set(&filters, name, filter); log_trace(TRACE_FILTERS, "filters init type=proc, name=%s, proc=%s", name, filter_config->proc); break; case FILTER_TYPE_CHAIN: break; } } /* second pass, allocate and init filter chains but don't build yet */ iter = NULL; while (dict_iter(env->sc_filters_dict, &iter, &name, (void **)&filter_config)) { switch (filter_config->filter_type) { case FILTER_TYPE_CHAIN: filter = xcalloc(1, sizeof(*filter)); filter->name = name; filter->chain = xcalloc(filter_config->chain_size, sizeof(void **)); filter->chain_size = filter_config->chain_size; filter->config = filter_config; buffer[0] = '\0'; for (i = 0; i < filter->chain_size; ++i) { filter->chain[i] = dict_xget(&filters, filter_config->chain[i]); if (i) (void)strlcat(buffer, ", ", sizeof buffer); (void)strlcat(buffer, filter->chain[i]->name, sizeof buffer); } log_trace(TRACE_FILTERS, "filters init type=chain, name=%s { %s }", name, buffer); dict_set(&filters, name, filter); break; case FILTER_TYPE_BUILTIN: case FILTER_TYPE_PROC: break; } } } void lka_filter_register_hook(const char *name, const char *hook) { struct dict *subsystem; struct filter *filter; const char *filter_name; void *iter; size_t i; if (strncasecmp(hook, "smtp-in|", 8) == 0) { subsystem = &filter_smtp_in; hook += 8; } else fatalx("Invalid message direction: %s", hook); for (i = 0; i < nitems(filter_execs); i++) if (strcmp(hook, filter_execs[i].phase_name) == 0) break; if (i == nitems(filter_execs)) fatalx("Unrecognized report name: %s", hook); iter = NULL; while (dict_iter(&filters, &iter, &filter_name, (void **)&filter)) if (filter->proc && strcmp(name, filter->proc) == 0) filter->phases |= (1<<filter_execs[i].phase); } void lka_filter_ready(void) { struct filter *filter; struct filter *subfilter; const char *filter_name; struct filter_entry *filter_entry; struct filter_chain *filter_chain; void *iter; size_t i; size_t j; /* all filters are ready, actually build the filter chains */ iter = NULL; while (dict_iter(&filters, &iter, &filter_name, (void **)&filter)) { filter_chain = xcalloc(1, sizeof *filter_chain); for (i = 0; i < nitems(filter_execs); i++) TAILQ_INIT(&filter_chain->chain[i]); dict_set(&filter_chains, filter_name, filter_chain); if (filter->chain) { for (i = 0; i < filter->chain_size; i++) { subfilter = filter->chain[i]; for (j = 0; j < nitems(filter_execs); ++j) { if (subfilter->phases & (1<<j)) { filter_entry = xcalloc(1, sizeof *filter_entry); filter_entry->id = generate_uid(); filter_entry->name = subfilter->name; TAILQ_INSERT_TAIL(&filter_chain->chain[j], filter_entry, entries); } } } continue; } for (i = 0; i < nitems(filter_execs); ++i) { if (filter->phases & (1<<i)) { filter_entry = xcalloc(1, sizeof *filter_entry); filter_entry->id = generate_uid(); filter_entry->name = filter_name; TAILQ_INSERT_TAIL(&filter_chain->chain[i], filter_entry, entries); } } } } int lka_filter_proc_in_session(uint64_t reqid, const char *proc) { struct filter_session *fs; struct filter *filter; size_t i; if ((fs = tree_get(&sessions, reqid)) == NULL) return 0; filter = dict_get(&filters, fs->filter_name); if (filter == NULL || (filter->proc == NULL && filter->chain == NULL)) return 0; if (filter->proc) return strcmp(filter->proc, proc) == 0 ? 1 : 0; for (i = 0; i < filter->chain_size; i++) if (filter->chain[i]->proc && strcmp(filter->chain[i]->proc, proc) == 0) return 1; return 0; } void lka_filter_begin(uint64_t reqid, const char *filter_name) { struct filter_session *fs; if (!filters_inited) { tree_init(&sessions); filters_inited = 1; } fs = xcalloc(1, sizeof (struct filter_session)); fs->id = reqid; fs->filter_name = xstrdup(filter_name); tree_xset(&sessions, fs->id, fs); log_trace(TRACE_FILTERS, "%016"PRIx64" filters session-begin", reqid); } void lka_filter_end(uint64_t reqid) { struct filter_session *fs; fs = tree_xpop(&sessions, reqid); free(fs->rdns); free(fs->helo); free(fs->mail_from); free(fs->username); free(fs->lastparam); free(fs->filter_name); free(fs); log_trace(TRACE_FILTERS, "%016"PRIx64" filters session-end", reqid); } void lka_filter_data_begin(uint64_t reqid) { struct filter_session *fs; int sp[2]; int fd = -1; fs = tree_xget(&sessions, reqid); if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1) goto end; io_set_nonblocking(sp[0]); io_set_nonblocking(sp[1]); fd = sp[0]; fs->io = io_new(); io_set_fd(fs->io, sp[1]); io_set_callback(fs->io, filter_session_io, fs); end: m_create(p_pony, IMSG_FILTER_SMTP_DATA_BEGIN, 0, 0, fd); m_add_id(p_pony, reqid); m_add_int(p_pony, fd != -1 ? 1 : 0); m_close(p_pony); log_trace(TRACE_FILTERS, "%016"PRIx64" filters data-begin fd=%d", reqid, fd); } void lka_filter_data_end(uint64_t reqid) { struct filter_session *fs; fs = tree_xget(&sessions, reqid); if (fs->io) { io_free(fs->io); fs->io = NULL; } log_trace(TRACE_FILTERS, "%016"PRIx64" filters data-end", reqid); } static void filter_session_io(struct io *io, int evt, void *arg) { struct filter_session *fs = arg; char *line = NULL; ssize_t len; log_trace(TRACE_IO, "filter session: %p: %s %s", fs, io_strevent(evt), io_strio(io)); switch (evt) { case IO_DATAIN: nextline: line = io_getline(fs->io, &len); /* No complete line received */ if (line == NULL) return; filter_data(fs->id, line); goto nextline; } } void lka_filter_process_response(const char *name, const char *line) { uint64_t reqid; uint64_t token; char buffer[LINE_MAX]; char *ep = NULL; char *kind = NULL; char *qid = NULL; /*char *phase = NULL;*/ char *response = NULL; char *parameter = NULL; struct filter_session *fs; (void)strlcpy(buffer, line, sizeof buffer); if ((ep = strchr(buffer, '|')) == NULL) fatalx("Missing token: %s", line); ep[0] = '\0'; kind = buffer; qid = ep+1; if ((ep = strchr(qid, '|')) == NULL) fatalx("Missing reqid: %s", line); ep[0] = '\0'; reqid = strtoull(qid, &ep, 16); if (qid[0] == '\0' || *ep != '\0') fatalx("Invalid reqid: %s", line); if (errno == ERANGE && reqid == ULLONG_MAX) fatal("Invalid reqid: %s", line); qid = ep+1; if ((ep = strchr(qid, '|')) == NULL) fatal("Missing directive: %s", line); ep[0] = '\0'; token = strtoull(qid, &ep, 16); if (qid[0] == '\0' || *ep != '\0') fatalx("Invalid token: %s", line); if (errno == ERANGE && token == ULLONG_MAX) fatal("Invalid token: %s", line); response = ep+1; /* session can legitimately disappear on a resume */ if ((fs = tree_get(&sessions, reqid)) == NULL) return; if (strcmp(kind, "filter-dataline") == 0) { if (fs->phase != FILTER_DATA_LINE) fatalx("filter-dataline out of dataline phase"); filter_data_next(token, reqid, response); return; } if (fs->phase == FILTER_DATA_LINE) fatalx("filter-result in dataline phase"); if ((ep = strchr(response, '|'))) { parameter = ep + 1; ep[0] = '\0'; } if (strcmp(response, "proceed") == 0) { if (parameter != NULL) fatalx("Unexpected parameter after proceed: %s", line); filter_protocol_next(token, reqid, 0); return; } else if (strcmp(response, "junk") == 0) { if (parameter != NULL) fatalx("Unexpected parameter after junk: %s", line); if (fs->phase == FILTER_COMMIT) fatalx("filter-reponse junk after DATA"); filter_result_junk(reqid); return; } else { if (parameter == NULL) fatalx("Missing parameter: %s", line); if (strcmp(response, "rewrite") == 0) filter_result_rewrite(reqid, parameter); else if (strcmp(response, "reject") == 0) filter_result_reject(reqid, parameter); else if (strcmp(response, "disconnect") == 0) filter_result_disconnect(reqid, parameter); else fatalx("Invalid directive: %s", line); } } void lka_filter_protocol(uint64_t reqid, enum filter_phase phase, const char *param) { filter_protocol(reqid, phase, param); } static void filter_protocol_internal(struct filter_session *fs, uint64_t *token, uint64_t reqid, enum filter_phase phase, const char *param) { struct filter_chain *filter_chain; struct filter_entry *filter_entry; struct filter *filter; struct timeval tv; const char *phase_name = filter_execs[phase].phase_name; int resume = 1; if (!*token) { fs->phase = phase; resume = 0; } /* XXX - this sanity check requires a protocol change, stub for now */ phase = fs->phase; if (fs->phase != phase) fatalx("misbehaving filter"); /* based on token, identify the filter_entry we should apply */ filter_chain = dict_get(&filter_chains, fs->filter_name); filter_entry = TAILQ_FIRST(&filter_chain->chain[fs->phase]); if (*token) { TAILQ_FOREACH(filter_entry, &filter_chain->chain[fs->phase], entries) if (filter_entry->id == *token) break; if (filter_entry == NULL) fatalx("misbehaving filter"); filter_entry = TAILQ_NEXT(filter_entry, entries); } /* no filter_entry, we either had none or reached end of chain */ if (filter_entry == NULL) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, resume=%s, " "action=proceed", fs->id, phase_name, resume ? "y" : "n"); filter_result_proceed(reqid); return; } /* process param with current filter_entry */ *token = filter_entry->id; filter = dict_get(&filters, filter_entry->name); if (filter->proc) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=deferred, filter=%s", fs->id, phase_name, resume ? "y" : "n", filter->name); filter_protocol_query(filter, filter_entry->id, reqid, filter_execs[fs->phase].phase_name, param); return; /* deferred response */ } if (filter_execs[fs->phase].func(fs, filter, reqid, param)) { if (filter->config->rewrite) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=rewrite, filter=%s, query=%s, response=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param, filter->config->rewrite); filter_result_rewrite(reqid, filter->config->rewrite); return; } else if (filter->config->disconnect) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=disconnect, filter=%s, query=%s, response=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param, filter->config->disconnect); filter_result_disconnect(reqid, filter->config->disconnect); return; } else if (filter->config->junk) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=junk, filter=%s, query=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param); filter_result_junk(reqid); return; } else if (filter->config->report) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=report, filter=%s, query=%s response=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param, filter->config->report); gettimeofday(&tv, NULL); lka_report_filter_report(fs->id, filter->name, 1, "smtp-in", &tv, filter->config->report); } else if (filter->config->bypass) { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=bypass, filter=%s, query=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param); filter_result_proceed(reqid); return; } else { log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=reject, filter=%s, query=%s, response=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param, filter->config->reject); filter_result_reject(reqid, filter->config->reject); return; } } log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, " "resume=%s, action=proceed, filter=%s, query=%s", fs->id, phase_name, resume ? "y" : "n", filter->name, param); /* filter_entry resulted in proceed, try next filter */ filter_protocol_internal(fs, token, reqid, phase, param); return; } static void filter_data_internal(struct filter_session *fs, uint64_t token, uint64_t reqid, const char *line) { struct filter_chain *filter_chain; struct filter_entry *filter_entry; struct filter *filter; if (!token) fs->phase = FILTER_DATA_LINE; if (fs->phase != FILTER_DATA_LINE) fatalx("misbehaving filter"); /* based on token, identify the filter_entry we should apply */ filter_chain = dict_get(&filter_chains, fs->filter_name); filter_entry = TAILQ_FIRST(&filter_chain->chain[fs->phase]); if (token) { TAILQ_FOREACH(filter_entry, &filter_chain->chain[fs->phase], entries) if (filter_entry->id == token) break; if (filter_entry == NULL) fatalx("misbehaving filter"); filter_entry = TAILQ_NEXT(filter_entry, entries); } /* no filter_entry, we either had none or reached end of chain */ if (filter_entry == NULL) { io_printf(fs->io, "%s\n", line); return; } /* pass data to the filter */ filter = dict_get(&filters, filter_entry->name); filter_data_query(filter, filter_entry->id, reqid, line); } static void filter_protocol(uint64_t reqid, enum filter_phase phase, const char *param) { struct filter_session *fs; uint64_t token = 0; char *nparam = NULL; fs = tree_xget(&sessions, reqid); switch (phase) { case FILTER_HELO: case FILTER_EHLO: free(fs->helo); fs->helo = xstrdup(param); break; case FILTER_MAIL_FROM: free(fs->mail_from); fs->mail_from = xstrdup(param + 1); *strchr(fs->mail_from, '>') = '\0'; param = fs->mail_from; break; case FILTER_RCPT_TO: nparam = xstrdup(param + 1); *strchr(nparam, '>') = '\0'; param = nparam; break; case FILTER_STARTTLS: /* TBD */ break; default: break; } free(fs->lastparam); fs->lastparam = xstrdup(param); filter_protocol_internal(fs, &token, reqid, phase, param); if (nparam) free(nparam); } static void filter_protocol_next(uint64_t token, uint64_t reqid, enum filter_phase phase) { struct filter_session *fs; /* session can legitimately disappear on a resume */ if ((fs = tree_get(&sessions, reqid)) == NULL) return; filter_protocol_internal(fs, &token, reqid, phase, fs->lastparam); } static void filter_data(uint64_t reqid, const char *line) { struct filter_session *fs; fs = tree_xget(&sessions, reqid); filter_data_internal(fs, 0, reqid, line); } static void filter_data_next(uint64_t token, uint64_t reqid, const char *line) { struct filter_session *fs; /* session can legitimately disappear on a resume */ if ((fs = tree_get(&sessions, reqid)) == NULL) return; filter_data_internal(fs, token, reqid, line); } static void filter_protocol_query(struct filter *filter, uint64_t token, uint64_t reqid, const char *phase, const char *param) { int n; struct filter_session *fs; struct timeval tv; gettimeofday(&tv, NULL); fs = tree_xget(&sessions, reqid); if (strcmp(phase, "connect") == 0) n = io_printf(lka_proc_get_io(filter->proc), "filter|%s|%lld.%06ld|smtp-in|%s|%016"PRIx64"|%016"PRIx64"|%s|%s\n", PROTOCOL_VERSION, tv.tv_sec, tv.tv_usec, phase, reqid, token, fs->rdns, param); else n = io_printf(lka_proc_get_io(filter->proc), "filter|%s|%lld.%06ld|smtp-in|%s|%016"PRIx64"|%016"PRIx64"|%s\n", PROTOCOL_VERSION, tv.tv_sec, tv.tv_usec, phase, reqid, token, param); if (n == -1) fatalx("failed to write to processor"); } static void filter_data_query(struct filter *filter, uint64_t token, uint64_t reqid, const char *line) { int n; struct timeval tv; gettimeofday(&tv, NULL); n = io_printf(lka_proc_get_io(filter->proc), "filter|%s|%lld.%06ld|smtp-in|data-line|" "%016"PRIx64"|%016"PRIx64"|%s\n", PROTOCOL_VERSION, tv.tv_sec, tv.tv_usec, reqid, token, line); if (n == -1) fatalx("failed to write to processor"); } static void filter_result_proceed(uint64_t reqid) { m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_pony, reqid); m_add_int(p_pony, FILTER_PROCEED); m_close(p_pony); } static void filter_result_junk(uint64_t reqid) { m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_pony, reqid); m_add_int(p_pony, FILTER_JUNK); m_close(p_pony); } static void filter_result_rewrite(uint64_t reqid, const char *param) { m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_pony, reqid); m_add_int(p_pony, FILTER_REWRITE); m_add_string(p_pony, param); m_close(p_pony); } static void filter_result_reject(uint64_t reqid, const char *message) { m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_pony, reqid); m_add_int(p_pony, FILTER_REJECT); m_add_string(p_pony, message); m_close(p_pony); } static void filter_result_disconnect(uint64_t reqid, const char *message) { m_create(p_pony, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_pony, reqid); m_add_int(p_pony, FILTER_DISCONNECT); m_add_string(p_pony, message); m_close(p_pony); } /* below is code for builtin filters */ static int filter_check_rdns_table(struct filter *filter, enum table_service kind, const char *key) { int ret = 0; if (filter->config->rdns_table == NULL) return 0; if (table_match(filter->config->rdns_table, kind, key) > 0) ret = 1; return filter->config->not_rdns_table < 0 ? !ret : ret; } static int filter_check_rdns_regex(struct filter *filter, const char *key) { int ret = 0; if (filter->config->rdns_regex == NULL) return 0; if (table_match(filter->config->rdns_regex, K_REGEX, key) > 0) ret = 1; return filter->config->not_rdns_regex < 0 ? !ret : ret; } static int filter_check_src_table(struct filter *filter, enum table_service kind, const char *key) { int ret = 0; if (filter->config->src_table == NULL) return 0; if (table_match(filter->config->src_table, kind, key) > 0) ret = 1; return filter->config->not_src_table < 0 ? !ret : ret; } static int filter_check_src_regex(struct filter *filter, const char *key) { int ret = 0; if (filter->config->src_regex == NULL) return 0; if (table_match(filter->config->src_regex, K_REGEX, key) > 0) ret = 1; return filter->config->not_src_regex < 0 ? !ret : ret; } static int filter_check_helo_table(struct filter *filter, enum table_service kind, const char *key) { int ret = 0; if (filter->config->helo_table == NULL) return 0; if (table_match(filter->config->helo_table, kind, key) > 0) ret = 1; return filter->config->not_helo_table < 0 ? !ret : ret; } static int filter_check_helo_regex(struct filter *filter, const char *key) { int ret = 0; if (filter->config->helo_regex == NULL) return 0; if (table_match(filter->config->helo_regex, K_REGEX, key) > 0) ret = 1; return filter->config->not_helo_regex < 0 ? !ret : ret; } static int filter_check_auth(struct filter *filter, const char *username) { int ret = 0; if (!filter->config->auth) return 0; ret = username ? 1 : 0; return filter->config->not_auth < 0 ? !ret : ret; } static int filter_check_auth_table(struct filter *filter, enum table_service kind, const char *key) { int ret = 0; if (filter->config->auth_table == NULL) return 0; if (key && table_match(filter->config->auth_table, kind, key) > 0) ret = 1; return filter->config->not_auth_table < 0 ? !ret : ret; } static int filter_check_auth_regex(struct filter *filter, const char *key) { int ret = 0; if (filter->config->auth_regex == NULL) return 0; if (key && table_match(filter->config->auth_regex, K_REGEX, key) > 0) ret = 1; return filter->config->not_auth_regex < 0 ? !ret : ret; } static int filter_check_mail_from_table(struct filter *filter, enum table_service kind, const char *key) { int ret = 0; if (filter->config->mail_from_table == NULL) return 0; if (table_match(filter->config->mail_from_table, kind, key) > 0) ret = 1; return filter->config->not_mail_from_table < 0 ? !ret : ret; } static int filter_check_mail_from_regex(struct filter *filter, const char *key) { int ret = 0; if (filter->config->mail_from_regex == NULL) return 0; if (table_match(filter->config->mail_from_regex, K_REGEX, key) > 0) ret = 1; return filter->config->not_mail_from_regex < 0 ? !ret : ret; } static int filter_check_rcpt_to_table(struct filter *filter, enum table_service kind, const char *key) { int ret = 0; if (filter->config->rcpt_to_table == NULL) return 0; if (table_match(filter->config->rcpt_to_table, kind, key) > 0) ret = 1; return filter->config->not_rcpt_to_table < 0 ? !ret : ret; } static int filter_check_rcpt_to_regex(struct filter *filter, const char *key) { int ret = 0; if (filter->config->rcpt_to_regex == NULL) return 0; if (table_match(filter->config->rcpt_to_regex, K_REGEX, key) > 0) ret = 1; return filter->config->not_rcpt_to_regex < 0 ? !ret : ret; } static int filter_check_fcrdns(struct filter *filter, int fcrdns) { int ret = 0; if (!filter->config->fcrdns) return 0; ret = fcrdns == 1; return filter->config->not_fcrdns < 0 ? !ret : ret; } static int filter_check_rdns(struct filter *filter, const char *hostname) { int ret = 0; struct netaddr netaddr; if (!filter->config->rdns) return 0; /* this is a hack until smtp session properly deals with lack of rdns */ ret = strcmp("<unknown>", hostname); if (ret == 0) return filter->config->not_rdns < 0 ? !ret : ret; /* if text_to_netaddress succeeds, * we don't have an rDNS so the filter should match */ ret = !text_to_netaddr(&netaddr, hostname); return filter->config->not_rdns < 0 ? !ret : ret; } static int filter_builtins_notimpl(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return 0; } static int filter_builtins_global(struct filter_session *fs, struct filter *filter, uint64_t reqid) { return filter_check_fcrdns(filter, fs->fcrdns) || filter_check_rdns(filter, fs->rdns) || filter_check_rdns_table(filter, K_DOMAIN, fs->rdns) || filter_check_rdns_regex(filter, fs->rdns) || filter_check_src_table(filter, K_NETADDR, ss_to_text(&fs->ss_src)) || filter_check_src_regex(filter, ss_to_text(&fs->ss_src)) || filter_check_helo_table(filter, K_DOMAIN, fs->helo) || filter_check_helo_regex(filter, fs->helo) || filter_check_auth(filter, fs->username) || filter_check_auth_table(filter, K_STRING, fs->username) || filter_check_auth_table(filter, K_CREDENTIALS, fs->username) || filter_check_auth_regex(filter, fs->username) || filter_check_mail_from_table(filter, K_MAILADDR, fs->mail_from) || filter_check_mail_from_regex(filter, fs->mail_from); } static int filter_builtins_connect(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return filter_builtins_global(fs, filter, reqid); } static int filter_builtins_helo(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return filter_builtins_global(fs, filter, reqid); } static int filter_builtins_mail_from(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return filter_builtins_global(fs, filter, reqid); } static int filter_builtins_rcpt_to(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return filter_builtins_global(fs, filter, reqid) || filter_check_rcpt_to_table(filter, K_MAILADDR, param) || filter_check_rcpt_to_regex(filter, param); } static int filter_builtins_data(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return filter_builtins_global(fs, filter, reqid); } static int filter_builtins_commit(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param) { return filter_builtins_global(fs, filter, reqid); } static void report_smtp_broadcast(uint64_t, const char *, struct timeval *, const char *, const char *, ...) __attribute__((__format__ (printf, 5, 6))); void lka_report_init(void) { struct reporters *tailq; size_t i; dict_init(&report_smtp_in); dict_init(&report_smtp_out); for (i = 0; i < nitems(smtp_events); ++i) { tailq = xcalloc(1, sizeof (struct reporters)); TAILQ_INIT(tailq); dict_xset(&report_smtp_in, smtp_events[i].event, tailq); tailq = xcalloc(1, sizeof (struct reporters)); TAILQ_INIT(tailq); dict_xset(&report_smtp_out, smtp_events[i].event, tailq); } } void lka_report_register_hook(const char *name, const char *hook) { struct dict *subsystem; struct reporter_proc *rp; struct reporters *tailq; void *iter; size_t i; if (strncmp(hook, "smtp-in|", 8) == 0) { subsystem = &report_smtp_in; hook += 8; } else if (strncmp(hook, "smtp-out|", 9) == 0) { subsystem = &report_smtp_out; hook += 9; } else fatalx("Invalid message direction: %s", hook); if (strcmp(hook, "*") == 0) { iter = NULL; while (dict_iter(subsystem, &iter, NULL, (void **)&tailq)) { rp = xcalloc(1, sizeof *rp); rp->name = xstrdup(name); TAILQ_INSERT_TAIL(tailq, rp, entries); } return; } for (i = 0; i < nitems(smtp_events); i++) if (strcmp(hook, smtp_events[i].event) == 0) break; if (i == nitems(smtp_events)) fatalx("Unrecognized report name: %s", hook); tailq = dict_get(subsystem, hook); rp = xcalloc(1, sizeof *rp); rp->name = xstrdup(name); TAILQ_INSERT_TAIL(tailq, rp, entries); } static void report_smtp_broadcast(uint64_t reqid, const char *direction, struct timeval *tv, const char *event, const char *format, ...) { va_list ap; struct dict *d; struct reporters *tailq; struct reporter_proc *rp; if (strcmp("smtp-in", direction) == 0) d = &report_smtp_in; else if (strcmp("smtp-out", direction) == 0) d = &report_smtp_out; else fatalx("unexpected direction: %s", direction); tailq = dict_xget(d, event); TAILQ_FOREACH(rp, tailq, entries) { if (!lka_filter_proc_in_session(reqid, rp->name)) continue; va_start(ap, format); if (io_printf(lka_proc_get_io(rp->name), "report|%s|%lld.%06ld|%s|%s|%016"PRIx64"%s", PROTOCOL_VERSION, tv->tv_sec, tv->tv_usec, direction, event, reqid, format[0] != '\n' ? "|" : "") == -1 || io_vprintf(lka_proc_get_io(rp->name), format, ap) == -1) fatalx("failed to write to processor"); va_end(ap); } } void lka_report_smtp_link_connect(const char *direction, struct timeval *tv, uint64_t reqid, const char *rdns, int fcrdns, const struct sockaddr_storage *ss_src, const struct sockaddr_storage *ss_dest) { struct filter_session *fs; char src[NI_MAXHOST + 5]; char dest[NI_MAXHOST + 5]; uint16_t src_port = 0; uint16_t dest_port = 0; const char *fcrdns_str; if (ss_src->ss_family == AF_INET) src_port = ntohs(((const struct sockaddr_in *)ss_src)->sin_port); else if (ss_src->ss_family == AF_INET6) src_port = ntohs(((const struct sockaddr_in6 *)ss_src)->sin6_port); if (ss_dest->ss_family == AF_INET) dest_port = ntohs(((const struct sockaddr_in *)ss_dest)->sin_port); else if (ss_dest->ss_family == AF_INET6) dest_port = ntohs(((const struct sockaddr_in6 *)ss_dest)->sin6_port); if (strcmp(ss_to_text(ss_src), "local") == 0) { (void)snprintf(src, sizeof src, "unix:%s", SMTPD_SOCKET); (void)snprintf(dest, sizeof dest, "unix:%s", SMTPD_SOCKET); } else { (void)snprintf(src, sizeof src, "%s:%d", ss_to_text(ss_src), src_port); (void)snprintf(dest, sizeof dest, "%s:%d", ss_to_text(ss_dest), dest_port); } switch (fcrdns) { case 1: fcrdns_str = "pass"; break; case 0: fcrdns_str = "fail"; break; default: fcrdns_str = "error"; break; } fs = tree_xget(&sessions, reqid); fs->rdns = xstrdup(rdns); fs->fcrdns = fcrdns; fs->ss_src = *ss_src; fs->ss_dest = *ss_dest; report_smtp_broadcast(reqid, direction, tv, "link-connect", "%s|%s|%s|%s\n", rdns, fcrdns_str, src, dest); } void lka_report_smtp_link_disconnect(const char *direction, struct timeval *tv, uint64_t reqid) { report_smtp_broadcast(reqid, direction, tv, "link-disconnect", "\n"); } void lka_report_smtp_link_greeting(const char *direction, uint64_t reqid, struct timeval *tv, const char *domain) { report_smtp_broadcast(reqid, direction, tv, "link-greeting", "%s\n", domain); } void lka_report_smtp_link_auth(const char *direction, struct timeval *tv, uint64_t reqid, const char *username, const char *result) { struct filter_session *fs; if (strcmp(result, "pass") == 0) { fs = tree_xget(&sessions, reqid); fs->username = xstrdup(username); } report_smtp_broadcast(reqid, direction, tv, "link-auth", "%s|%s\n", username, result); } void lka_report_smtp_link_identify(const char *direction, struct timeval *tv, uint64_t reqid, const char *method, const char *heloname) { report_smtp_broadcast(reqid, direction, tv, "link-identify", "%s|%s\n", method, heloname); } void lka_report_smtp_link_tls(const char *direction, struct timeval *tv, uint64_t reqid, const char *ciphers) { report_smtp_broadcast(reqid, direction, tv, "link-tls", "%s\n", ciphers); } void lka_report_smtp_tx_reset(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid) { report_smtp_broadcast(reqid, direction, tv, "tx-reset", "%08x\n", msgid); } void lka_report_smtp_tx_begin(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid) { report_smtp_broadcast(reqid, direction, tv, "tx-begin", "%08x\n", msgid); } void lka_report_smtp_tx_mail(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, const char *address, int ok) { const char *result; switch (ok) { case 1: result = "ok"; break; case 0: result = "permfail"; break; default: result = "tempfail"; break; } report_smtp_broadcast(reqid, direction, tv, "tx-mail", "%08x|%s|%s\n", msgid, result, address); } void lka_report_smtp_tx_rcpt(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, const char *address, int ok) { const char *result; switch (ok) { case 1: result = "ok"; break; case 0: result = "permfail"; break; default: result = "tempfail"; break; } report_smtp_broadcast(reqid, direction, tv, "tx-rcpt", "%08x|%s|%s\n", msgid, result, address); } void lka_report_smtp_tx_envelope(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, uint64_t evpid) { report_smtp_broadcast(reqid, direction, tv, "tx-envelope", "%08x|%016"PRIx64"\n", msgid, evpid); } void lka_report_smtp_tx_data(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, int ok) { const char *result; switch (ok) { case 1: result = "ok"; break; case 0: result = "permfail"; break; default: result = "tempfail"; break; } report_smtp_broadcast(reqid, direction, tv, "tx-data", "%08x|%s\n", msgid, result); } void lka_report_smtp_tx_commit(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, size_t msgsz) { report_smtp_broadcast(reqid, direction, tv, "tx-commit", "%08x|%zd\n", msgid, msgsz); } void lka_report_smtp_tx_rollback(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid) { report_smtp_broadcast(reqid, direction, tv, "tx-rollback", "%08x\n", msgid); } void lka_report_smtp_protocol_client(const char *direction, struct timeval *tv, uint64_t reqid, const char *command) { report_smtp_broadcast(reqid, direction, tv, "protocol-client", "%s\n", command); } void lka_report_smtp_protocol_server(const char *direction, struct timeval *tv, uint64_t reqid, const char *response) { report_smtp_broadcast(reqid, direction, tv, "protocol-server", "%s\n", response); } void lka_report_smtp_filter_response(const char *direction, struct timeval *tv, uint64_t reqid, int phase, int response, const char *param) { const char *phase_name; const char *response_name; switch (phase) { case FILTER_CONNECT: phase_name = "connected"; break; case FILTER_HELO: phase_name = "helo"; break; case FILTER_EHLO: phase_name = "ehlo"; break; case FILTER_STARTTLS: phase_name = "tls"; break; case FILTER_AUTH: phase_name = "auth"; break; case FILTER_MAIL_FROM: phase_name = "mail-from"; break; case FILTER_RCPT_TO: phase_name = "rcpt-to"; break; case FILTER_DATA: phase_name = "data"; break; case FILTER_DATA_LINE: phase_name = "data-line"; break; case FILTER_RSET: phase_name = "rset"; break; case FILTER_QUIT: phase_name = "quit"; break; case FILTER_NOOP: phase_name = "noop"; break; case FILTER_HELP: phase_name = "help"; break; case FILTER_WIZ: phase_name = "wiz"; break; case FILTER_COMMIT: phase_name = "commit"; break; default: phase_name = ""; } switch (response) { case FILTER_PROCEED: response_name = "proceed"; break; case FILTER_JUNK: response_name = "junk"; break; case FILTER_REWRITE: response_name = "rewrite"; break; case FILTER_REJECT: response_name = "reject"; break; case FILTER_DISCONNECT: response_name = "disconnect"; break; default: response_name = ""; } report_smtp_broadcast(reqid, direction, tv, "filter-response", "%s|%s%s%s\n", phase_name, response_name, param ? "|" : "", param ? param : ""); } void lka_report_smtp_timeout(const char *direction, struct timeval *tv, uint64_t reqid) { report_smtp_broadcast(reqid, direction, tv, "timeout", "\n"); } void lka_report_filter_report(uint64_t reqid, const char *name, int builtin, const char *direction, struct timeval *tv, const char *message) { report_smtp_broadcast(reqid, direction, tv, "filter-report", "%s|%s|%s\n", builtin ? "builtin" : "proc", name, message); } void lka_report_proc(const char *name, const char *line) { char buffer[LINE_MAX]; struct timeval tv; char *ep, *sp, *direction; uint64_t reqid; if (strlcpy(buffer, line + 7, sizeof(buffer)) >= sizeof(buffer)) fatalx("Invalid report: line too long: %s", line); errno = 0; tv.tv_sec = strtoll(buffer, &ep, 10); if (ep[0] != '.' || errno != 0) fatalx("Invalid report: invalid time: %s", line); sp = ep + 1; tv.tv_usec = strtol(sp, &ep, 10); if (ep[0] != '|' || errno != 0) fatalx("Invalid report: invalid time: %s", line); if (ep - sp != 6) fatalx("Invalid report: invalid time: %s", line); direction = ep + 1; if (strncmp(direction, "smtp-in|", 8) == 0) { direction[7] = '\0'; direction += 7; #if 0 } else if (strncmp(direction, "smtp-out|", 9) == 0) { direction[8] = '\0'; direction += 8; #endif } else fatalx("Invalid report: invalid direction: %s", line); reqid = strtoull(sp, &ep, 16); if (ep[0] != '|' || errno != 0) fatalx("Invalid report: invalid reqid: %s", line); sp = ep + 1; lka_report_filter_report(reqid, name, 0, direction, &tv, sp); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_4477_0
crossvul-cpp_data_bad_5261_2
/* +----------------------------------------------------------------------+ | 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) { 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; TSRMLS_FETCH(); 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_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); 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); PHP_CLEANUP_CLASS_ATTRIBUTES(); 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_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); 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); PHP_CLEANUP_CLASS_ATTRIBUTES(); 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); } 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] && atts[i][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], 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] && atts[i][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], strlen(atts[i])); 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] && atts[i][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i]); 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] && atts[i][0]) { zval *tmp; char *key; char *p1, *p2, *endp; 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] && atts[i][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], strlen(atts[i])+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--; } else { stack->done = 1; } efree(ent1); 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->type == ST_FIELD && 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; } /* 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); *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/bad_5261_2
crossvul-cpp_data_good_3185_0
/* radare - LGPL - Copyright 2011-2016 - pancake */ #include <r_cons.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_bin.h> #include "dex/dex.h" #define r_hash_adler32 __adler32 #include "../../hash/adler32.c" extern struct r_bin_dbginfo_t r_bin_dbginfo_dex; #define DEBUG_PRINTF 0 #if DEBUG_PRINTF #define dprintf eprintf #else #define dprintf if (0)eprintf #endif static bool dexdump = false; static Sdb *mdb = NULL; static Sdb *cdb = NULL; // TODO: remove if it is not used static char *getstr(RBinDexObj *bin, int idx) { ut8 buf[6]; ut64 len; int uleblen; if (!bin || idx < 0 || idx >= bin->header.strings_size || !bin->strings) { return NULL; } if (bin->strings[idx] >= bin->size) { return NULL; } if (r_buf_read_at (bin->b, bin->strings[idx], buf, sizeof (buf)) < 1) { return NULL; } uleblen = r_uleb128 (buf, sizeof (buf), &len) - buf; if (!uleblen || uleblen >= bin->size) { return NULL; } if (!len || len >= bin->size) { return NULL; } // TODO: improve this ugly fix char c = 'a'; while (c) { ut64 offset = bin->strings[idx] + uleblen + len; if (offset >= bin->size || offset < len) { return NULL; } r_buf_read_at (bin->b, offset, (ut8*)&c, 1); len++; } if ((int)len > 0 && len < R_BIN_SIZEOF_STRINGS) { char *str = calloc (1, len + 1); if (str) { r_buf_read_at (bin->b, (bin->strings[idx]) + uleblen, (ut8 *)str, len); str[len] = 0; return str; } } return NULL; } static int countOnes(ut32 val) { int count = 0; val = val - ((val >> 1) & 0x55555555); val = (val & 0x33333333) + ((val >> 2) & 0x33333333); count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; return count; } typedef enum { kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX } AccessFor; static char *createAccessFlagStr(ut32 flags, AccessFor forWhat) { #define NUM_FLAGS 18 static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = { { /* class, inner class */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "?", /* 0x0040 */ "?", /* 0x0080 */ "?", /* 0x0100 */ "INTERFACE", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "ANNOTATION", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "VERIFIED", /* 0x10000 */ "OPTIMIZED", /* 0x20000 */ }, { /* method */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "SYNCHRONIZED", /* 0x0020 */ "BRIDGE", /* 0x0040 */ "VARARGS", /* 0x0080 */ "NATIVE", /* 0x0100 */ "?", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "STRICT", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "?", /* 0x4000 */ "MIRANDA", /* 0x8000 */ "CONSTRUCTOR", /* 0x10000 */ "DECLARED_SYNCHRONIZED", /* 0x20000 */ }, { /* field */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "VOLATILE", /* 0x0040 */ "TRANSIENT", /* 0x0080 */ "?", /* 0x0100 */ "?", /* 0x0200 */ "?", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "?", /* 0x10000 */ "?", /* 0x20000 */ }, }; const int kLongest = 21; int i, count; char* str; char* cp; count = countOnes(flags); // XXX check if this allocation is safe what if all the arithmetic // produces a huge number???? cp = str = (char*) malloc (count * (kLongest + 1) + 1); for (i = 0; i < NUM_FLAGS; i++) { if (flags & 0x01) { const char* accessStr = kAccessStrings[forWhat][i]; int len = strlen(accessStr); if (cp != str) { *cp++ = ' '; } memcpy(cp, accessStr, len); cp += len; } flags >>= 1; } *cp = '\0'; return str; } static char *dex_type_descriptor(RBinDexObj *bin, int type_idx) { if (type_idx < 0 || type_idx >= bin->header.types_size) { return NULL; } return getstr (bin, bin->types[type_idx].descriptor_id); } static char *dex_method_signature(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, type_id, list_size; char *r, *return_type = NULL, *signature = NULL, *buff = NULL; ut8 *bufptr; ut16 type_idx; int pos = 0, i, size = 1; if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { return NULL; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { return NULL; } type_id = bin->protos[proto_id].return_type_id; if (type_id >= bin->header.types_size ) { return NULL; } return_type = getstr (bin, bin->types[type_id].descriptor_id); if (!return_type) { return NULL; } if (!params_off) { return r_str_newf ("()%s", return_type);; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX again list_size is user controlled huge loop for (i = 0; i < list_size; i++) { int buff_len = 0; if (params_off + 4 + (i * 2) >= bin->size) { break; } type_idx = r_read_le16 (bufptr + params_off + 4 + (i * 2)); if (type_idx < 0 || type_idx >= bin->header.types_size || type_idx >= bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } buff_len = strlen (buff); size += buff_len + 1; signature = realloc (signature, size); strcpy (signature + pos, buff); pos += buff_len; signature[pos] = '\0'; } r = r_str_newf ("(%s)%s", signature, return_type); free (buff); free (signature); return r; } static RList *dex_method_signature2(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, list_size; char *buff = NULL; ut8 *bufptr; ut16 type_idx; int i; RList *params = r_list_newf (free); if (!params) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { goto out_error; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { goto out_error; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { goto out_error; } if (!params_off) { return params; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX list_size tainted it may produce huge loop for (i = 0; i < list_size; i++) { ut64 of = params_off + 4 + (i * 2); if (of >= bin->size || of < params_off) { break; } type_idx = r_read_le16 (bufptr + of); if (type_idx >= bin->header.types_size || type_idx > bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } r_list_append (params, buff); } return params; out_error: r_list_free (params); return NULL; } // TODO: fix this, now has more registers that it should // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L312 // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L141 static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } if (p4 <= 0) { return; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); } static int check (RBinFile *arch); static int check_bytes (const ut8 *buf, ut64 length); static Sdb *get_sdb (RBinObject *o) { if (!o || !o->bin_obj) { return NULL; } struct r_bin_dex_obj_t *bin = (struct r_bin_dex_obj_t *) o->bin_obj; if (bin->kv) { return bin->kv; } return NULL; } static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb){ void *res = NULL; RBuffer *tbuf = NULL; if (!buf || !sz || sz == UT64_MAX) { return NULL; } tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); res = r_bin_dex_new_buf (tbuf); r_buf_free (tbuf); return res; } static int load(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; if (!arch || !arch->o) { return false; } arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb); return arch->o->bin_obj ? true: false; } static ut64 baddr(RBinFile *arch) { return 0; } static int check(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; return check_bytes (bytes, sz); } static int check_bytes(const ut8 *buf, ut64 length) { if (!buf || length < 8) { return false; } // Non-extended opcode dex file if (!memcmp (buf, "dex\n035\0", 8)) { return true; } // Extended (jumnbo) opcode dex file, ICS+ only (sdk level 14+) if (!memcmp (buf, "dex\n036\0", 8)) { return true; } // M3 (Nov-Dec 07) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // M5 (Feb-Mar 08) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // Default fall through, should still be a dex file if (!memcmp (buf, "dex\n", 4)) { return true; } return false; } static RBinInfo *info(RBinFile *arch) { RBinHash *h; RBinInfo *ret = R_NEW0 (RBinInfo); if (!ret) { return NULL; } ret->file = arch->file? strdup (arch->file): NULL; ret->type = strdup ("DEX CLASS"); ret->has_va = false; ret->bclass = r_bin_dex_get_version (arch->o->bin_obj); ret->rclass = strdup ("class"); ret->os = strdup ("linux"); ret->subsystem = strdup ("any"); ret->machine = strdup ("Dalvik VM"); h = &ret->sum[0]; h->type = "sha1"; h->len = 20; h->addr = 12; h->from = 12; h->to = arch->buf->length-32; memcpy (h->buf, arch->buf->buf+12, 20); h = &ret->sum[1]; h->type = "adler32"; h->len = 4; h->addr = 0x8; h->from = 12; h->to = arch->buf->length-h->from; h = &ret->sum[2]; h->type = 0; memcpy (h->buf, arch->buf->buf + 8, 4); { ut32 *fc = (ut32 *)(arch->buf->buf + 8); ut32 cc = __adler32 (arch->buf->buf + 12, arch->buf->length - 12); if (*fc != cc) { eprintf ("# adler32 checksum doesn't match. Type this to fix it:\n"); eprintf ("wx `#sha1 $s-32 @32` @12 ; wx `#adler32 $s-12 @12` @8\n"); } } ret->arch = strdup ("dalvik"); ret->lang = "dalvik"; ret->bits = 32; ret->big_endian = 0; ret->dbg_info = 0; //1 | 4 | 8; /* Stripped | LineNums | Syms */ return ret; } static RList *strings(RBinFile *arch) { struct r_bin_dex_obj_t *bin = NULL; RBinString *ptr = NULL; RList *ret = NULL; int i, len; ut8 buf[6]; ut64 off; if (!arch || !arch->o) { return NULL; } bin = (struct r_bin_dex_obj_t *) arch->o->bin_obj; if (!bin || !bin->strings) { return NULL; } if (bin->header.strings_size > bin->size) { bin->strings = NULL; return NULL; } if (!(ret = r_list_newf (free))) { return NULL; } for (i = 0; i < bin->header.strings_size; i++) { if (!(ptr = R_NEW0 (RBinString))) { break; } if (bin->strings[i] > bin->size || bin->strings[i] + 6 > bin->size) { goto out_error; } r_buf_read_at (bin->b, bin->strings[i], (ut8*)&buf, 6); len = dex_read_uleb128 (buf); if (len > 1 && len < R_BIN_SIZEOF_STRINGS) { ptr->string = malloc (len + 1); if (!ptr->string) { goto out_error; } off = bin->strings[i] + dex_uleb128_len (buf); if (off + len >= bin->size || off + len < len) { free (ptr->string); goto out_error; } r_buf_read_at (bin->b, off, (ut8*)ptr->string, len); ptr->string[len] = 0; ptr->vaddr = ptr->paddr = bin->strings[i]; ptr->size = len; ptr->length = len; ptr->ordinal = i+1; r_list_append (ret, ptr); } else { free (ptr); } } return ret; out_error: r_list_free (ret); free (ptr); return NULL; } static char *dex_method_name(RBinDexObj *bin, int idx) { if (idx < 0 || idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[idx].class_id; if (cid < 0 || cid >= bin->header.strings_size) { return NULL; } int tid = bin->methods[idx].name_id; if (tid < 0 || tid >= bin->header.strings_size) { return NULL; } return getstr (bin, tid); } static char *dex_class_name_byid(RBinDexObj *bin, int cid) { int tid; if (!bin || !bin->types) { return NULL; } if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) { return dex_class_name_byid (bin, c->class_id); } static char *dex_field_name(RBinDexObj *bin, int fid) { int cid, tid, type_id; if (!bin || !bin->fields) { return NULL; } if (fid < 0 || fid >= bin->header.fields_size) { return NULL; } cid = bin->fields[fid].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } type_id = bin->fields[fid].type_id; if (type_id < 0 || type_id >= bin->header.types_size) { return NULL; } tid = bin->fields[fid].name_id; return r_str_newf ("%s->%s %s", getstr (bin, bin->types[cid].descriptor_id), getstr (bin, tid), getstr (bin, bin->types[type_id].descriptor_id)); } static char *dex_method_fullname(RBinDexObj *bin, int method_idx) { if (!bin || !bin->types) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[method_idx].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } char *name = dex_method_name (bin, method_idx); char *class_name = dex_class_name_byid (bin, cid); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func char *signature = dex_method_signature (bin, method_idx); char *flagname = r_str_newf ("%s.%s%s", class_name, name, signature); free (name); free (class_name); free (signature); return flagname; } static ut64 dex_get_type_offset(RBinFile *arch, int type_idx) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin || !bin->types) { return 0; } if (type_idx < 0 || type_idx >= bin->header.types_size) { return 0; } return bin->header.types_offset + type_idx * 0x04; //&bin->types[type_idx]; } static void __r_bin_class_free(RBinClass *p) { r_list_free (p->methods); r_list_free (p->fields); r_bin_class_free (p); } static char *dex_class_super_name(RBinDexObj *bin, RBinDexClass *c) { int cid, tid; if (!bin || !c || !bin->types) { return NULL; } cid = c->super_class; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static const ut8 *parse_dex_class_fields(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 fields_count, bool is_sfield) { struct r_bin_t *rbin = binfile->rbin; ut64 lastIndex = 0; ut8 ff[sizeof (DexField)] = {0}; int total, i, tid; DexField field; const char* type_str; for (i = 0; i < fields_count; i++) { ut64 fieldIndex, accessFlags; p = r_uleb128 (p, p_end - p, &fieldIndex); // fieldIndex p = r_uleb128 (p, p_end - p, &accessFlags); // accessFlags fieldIndex += lastIndex; total = bin->header.fields_offset + (sizeof (DexField) * fieldIndex); if (total >= bin->size || total < bin->header.fields_offset) { break; } if (r_buf_read_at (binfile->buf, total, ff, sizeof (DexField)) != sizeof (DexField)) { break; } field.class_id = r_read_le16 (ff); field.type_id = r_read_le16 (ff + 2); field.name_id = r_read_le32 (ff + 4); char *fieldName = getstr (bin, field.name_id); if (field.type_id >= bin->header.types_size) { break; } tid = bin->types[field.type_id].descriptor_id; type_str = getstr (bin, tid); RBinSymbol *sym = R_NEW0 (RBinSymbol); if (is_sfield) { sym->name = r_str_newf ("%s.sfield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("STATIC"); } else { sym->name = r_str_newf ("%s.ifield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("FIELD"); } sym->name = r_str_replace (sym->name, "method.", "", 0); //sym->name = r_str_replace (sym->name, ";", "", 0); sym->paddr = sym->vaddr = total; sym->ordinal = (*sym_count)++; if (dexdump) { const char *accessStr = createAccessFlagStr ( accessFlags, kAccessForField); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", fieldName); rbin->cb_printf (" type : '%s'\n", type_str); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)accessFlags, accessStr); } r_list_append (bin->methods_list, sym); r_list_append (cls->fields, sym); lastIndex = fieldIndex; } return p; } // TODO: refactor this method // XXX it needs a lot of love!!! static const ut8 *parse_dex_class_method(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 DM, int *methods, bool is_direct) { struct r_bin_t *rbin = binfile->rbin; ut8 ff2[16] = {0}; ut8 ff3[8] = {0}; int i; ut64 omi = 0; bool catchAll; ut16 regsz, ins_size, outs_size, tries_size; ut16 handler_off, start_addr, insn_count; ut32 debug_info_off, insns_size; const ut8 *encoded_method_addr; for (i = 0; i < DM; i++) { encoded_method_addr = p; char *method_name, *flag_name; ut64 MI, MA, MC; p = r_uleb128 (p, p_end - p, &MI); MI += omi; omi = MI; p = r_uleb128 (p, p_end - p, &MA); p = r_uleb128 (p, p_end - p, &MC); // TODO: MOVE CHECKS OUTSIDE! if (MI < bin->header.method_size) { if (methods) { methods[MI] = 1; } } method_name = dex_method_name (bin, MI); char *signature = dex_method_signature (bin, MI); if (!method_name) { method_name = strdup ("unknown"); } flag_name = r_str_newf ("%s.method.%s%s", cls->name, method_name, signature); if (!flag_name) { R_FREE (method_name); R_FREE (signature); continue; } // TODO: check size // ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; ut64 v2, handler_type, handler_addr; int t; if (MC > 0) { // TODO: parse debug info // XXX why binfile->buf->base??? if (MC + 16 >= bin->size || MC + 16 < MC) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } regsz = r_read_le16 (ff2); ins_size = r_read_le16 (ff2 + 2); outs_size = r_read_le16 (ff2 + 4); tries_size = r_read_le16 (ff2 + 6); debug_info_off = r_read_le32 (ff2 + 8); insns_size = r_read_le32 (ff2 + 12); int padd = 0; if (tries_size > 0 && insns_size % 2) { padd = 2; } t = 16 + 2 * insns_size + padd; } if (dexdump) { const char* accessStr = createAccessFlagStr (MA, kAccessForMethod); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", method_name); rbin->cb_printf (" type : '%s'\n", signature); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)MA, accessStr); } if (MC > 0) { if (dexdump) { rbin->cb_printf (" code -\n"); rbin->cb_printf (" registers : %d\n", regsz); rbin->cb_printf (" ins : %d\n", ins_size); rbin->cb_printf (" outs : %d\n", outs_size); rbin->cb_printf ( " insns size : %d 16-bit code " "units\n", insns_size); } if (tries_size > 0) { if (dexdump) { rbin->cb_printf (" catches : %d\n", tries_size); } int j, m = 0; //XXX bucle controlled by tainted variable it could produces huge loop for (j = 0; j < tries_size; ++j) { ut64 offset = MC + t + j * 8; if (offset >= bin->size || offset < MC) { R_FREE (signature); break; } if (r_buf_read_at ( binfile->buf, binfile->buf->base + offset, ff3, 8) < 1) { // free (method_name); R_FREE (signature); break; } start_addr = r_read_le32 (ff3); insn_count = r_read_le16 (ff3 + 4); handler_off = r_read_le16 (ff3 + 6); char* s = NULL; if (dexdump) { rbin->cb_printf ( " 0x%04x - " "0x%04x\n", start_addr, (start_addr + insn_count)); } const ut8 *p3, *p3_end; //XXX tries_size is tainted and oob here int off = MC + t + tries_size * 8 + handler_off; if (off >= bin->size || off < tries_size) { R_FREE (signature); break; } p3 = r_buf_get_at (binfile->buf, off, NULL); p3_end = p3 + binfile->buf->length - off; st64 size = r_sleb128 (&p3, p3_end); if (size <= 0) { catchAll = true; size = -size; } else { catchAll = false; } for (m = 0; m < size; m++) { p3 = r_uleb128 (p3, p3_end - p3, &handler_type); p3 = r_uleb128 (p3, p3_end - p3, &handler_addr); if (handler_type > 0 && handler_type < bin->header.types_size) { s = getstr (bin, bin->types[handler_type].descriptor_id); if (dexdump) { rbin->cb_printf ( " %s " "-> 0x%04llx\n", s, handler_addr); } } else { if (dexdump) { rbin->cb_printf ( " " "(error) -> " "0x%04llx\n", handler_addr); } } } if (catchAll) { p3 = r_uleb128 (p3, p3_end - p3, &v2); if (dexdump) { rbin->cb_printf ( " " "<any> -> " "0x%04llx\n", v2); } } } } else { if (dexdump) { rbin->cb_printf ( " catches : " "(none)\n"); } } } else { if (dexdump) { rbin->cb_printf ( " code : (none)\n"); } } if (*flag_name) { RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = flag_name; // is_direct is no longer used // if method has code *addr points to code // otherwise it points to the encoded method if (MC > 0) { sym->type = r_str_const ("FUNC"); sym->paddr = MC;// + 0x10; sym->vaddr = MC;// + 0x10; } else { sym->type = r_str_const ("METH"); sym->paddr = encoded_method_addr - binfile->buf->buf; sym->vaddr = encoded_method_addr - binfile->buf->buf; } if ((MA & 0x1) == 0x1) { sym->bind = r_str_const ("GLOBAL"); } else { sym->bind = r_str_const ("LOCAL"); } sym->ordinal = (*sym_count)++; if (MC > 0) { if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (sym); R_FREE (signature); continue; } //ut16 regsz = r_read_le16 (ff2); //ut16 ins_size = r_read_le16 (ff2 + 2); //ut16 outs_size = r_read_le16 (ff2 + 4); ut16 tries_size = r_read_le16 (ff2 + 6); //ut32 debug_info_off = r_read_le32 (ff2 + 8); ut32 insns_size = r_read_le32 (ff2 + 12); ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; if (tries_size > 0) { //prolog_size += 2 + 8*tries_size; // we need to parse all so the catch info... } // TODO: prolog_size sym->paddr = MC + prolog_size;// + 0x10; sym->vaddr = MC + prolog_size;// + 0x10; //if (is_direct) { sym->size = insns_size * 2; //} //eprintf("%s (0x%x-0x%x) size=%d\nregsz=%d\ninsns_size=%d\nouts_size=%d\ntries_size=%d\ninsns_size=%d\n", flag_name, sym->vaddr, sym->vaddr+sym->size, prolog_size, regsz, ins_size, outs_size, tries_size, insns_size); r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); if (bin->code_from > sym->paddr) { bin->code_from = sym->paddr; } if (bin->code_to < sym->paddr) { bin->code_to = sym->paddr; } if (!mdb) { mdb = sdb_new0 (); } sdb_num_set (mdb, sdb_fmt (0, "method.%d", MI), sym->paddr, 0); // ----------------- // WORK IN PROGRESS // ----------------- if (0) { if (MA & 0x10000) { //ACC_CONSTRUCTOR if (!cdb) { cdb = sdb_new0 (); } sdb_num_set (cdb, sdb_fmt (0, "%d", c->class_id), sym->paddr, 0); } } } else { sym->size = 0; r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); } if (MC > 0 && debug_info_off > 0 && bin->header.data_offset < debug_info_off && debug_info_off < bin->header.data_offset + bin->header.data_size) { dex_parse_debug_item (binfile, bin, c, MI, MA, sym->paddr, ins_size, insns_size, cls->name, regsz, debug_info_off); } else if (MC > 0) { if (dexdump) { rbin->cb_printf (" positions :\n"); rbin->cb_printf (" locals :\n"); } } } else { R_FREE (flag_name); } R_FREE (signature); R_FREE (method_name); } return p; } static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf (" Class descriptor : '%s;'\n", class_name); rbin->cb_printf ( " Access flags : 0x%04x (%s)\n", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf (" Superclass : '%s'\n", dex_class_super_name (bin, c)); rbin->cb_printf (" Interfaces -\n"); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32 (p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( " #%d : '%s'\n", z, getstr (bin, tid)); } } } } // TODO: this is quite ugly if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( " Static fields -\n Instance fields " "-\n Direct methods -\n Virtual methods " "-\n"); } } else { // TODO: move to func, def or inline // class_data_offset => [class_offset, class_defs_off+class_defs_size*32] if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; //XXX check for NULL!! c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf (" Static fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf (" Instance fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf (" Direct methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf (" Virtual methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( " source_file_idx : %d (unknown)\n\n", c->source_file); } else { rbin->cb_printf (" source_file_idx : %d (%s)\n\n", c->source_file, source_file); } } // TODO:!!!! // FIX: FREE BEFORE ALLOCATE!!! //free (class_name); } static bool is_class_idx_in_code_classes(RBinDexObj *bin, int class_idx) { int i; for (i = 0; i < bin->header.class_size; i++) { if (class_idx == bin->classes[i].class_id) { return true; } } return false; } static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id >= bin->header.types_size) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; } static RList* imports(RBinFile *arch) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin) { return NULL; } if (bin && bin->imports_list) { return bin->imports_list; } dex_loadcode (arch, bin); return bin->imports_list; } static RList *methods(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->methods_list) { dex_loadcode (arch, bin); } return bin->methods_list; } static RList *classes(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->classes_list) { dex_loadcode (arch, bin); } return bin->classes_list; } static int already_entry(RList *entries, ut64 vaddr) { RBinAddr *e; RListIter *iter; r_list_foreach (entries, iter, e) { if (e->vaddr == vaddr) { return 1; } } return 0; } static RList *entries(RBinFile *arch) { RListIter *iter; RBinDexObj *bin; RBinSymbol *m; RBinAddr *ptr; RList *ret; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; ret = r_list_newf ((RListFree)free); if (!bin->methods_list) { dex_loadcode (arch, bin); } // STEP 1. ".onCreate(Landroid/os/Bundle;)V" r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 30 && m->bind && !strcmp(m->bind, "GLOBAL") && !strcmp (m->name + strlen (m->name) - 31, ".onCreate(Landroid/os/Bundle;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } // STEP 2. ".main([Ljava/lang/String;)V" if (r_list_empty (ret)) { r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 26 && !strcmp (m->name + strlen (m->name) - 27, ".main([Ljava/lang/String;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } } // STEP 3. NOTHING FOUND POINT TO CODE_INIT if (r_list_empty (ret)) { if (!already_entry (ret, bin->code_from)) { ptr = R_NEW0 (RBinAddr); if (ptr) { ptr->paddr = ptr->vaddr = bin->code_from; r_list_append (ret, ptr); } } } return ret; } static ut64 offset_of_method_idx(RBinFile *arch, struct r_bin_dex_obj_t *dex, int idx) { ut64 off = dex->header.method_offset + idx; off = sdb_num_get (mdb, sdb_fmt (0, "method.%d", idx), 0); return (ut64) off; } // TODO: change all return type for all getoffset static int getoffset(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods // TODO: ADD CHECK return offset_of_method_idx (arch, dex, idx); case 'o': // objects break; case 's': // strings if (dex->header.strings_size > idx) { if (dex->strings) return dex->strings[idx]; } break; case 't': // type return dex_get_type_offset (arch, idx); case 'c': // class return dex_get_type_offset (arch, idx); //return sdb_num_get (cdb, sdb_fmt (0, "%d", idx), 0); } return -1; } static char *getname(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods return dex_method_fullname (dex, idx); case 'c': // classes return dex_class_name_byid (dex, idx); case 'f': // fields return dex_field_name (dex, idx); } return NULL; } static RList *sections(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; RList *ml = methods (arch); RBinSection *ptr = NULL; int ns, fsymsz = 0; RList *ret = NULL; RListIter *iter; RBinSymbol *m; int fsym = 0; r_list_foreach (ml, iter, m) { if (!fsym || m->paddr < fsym) { fsym = m->paddr; } ns = m->paddr + m->size; if (ns > arch->buf->length) { continue; } if (ns > fsymsz) { fsymsz = ns; } } if (!fsym) { return NULL; } if (!(ret = r_list_new ())) { return NULL; } ret->free = free; if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "header"); ptr->size = ptr->vsize = sizeof (struct dex_header_t); ptr->paddr= ptr->vaddr = 0; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "constpool"); //ptr->size = ptr->vsize = fsym; ptr->paddr= ptr->vaddr = sizeof (struct dex_header_t); ptr->size = bin->code_from - ptr->vaddr; // fix size ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "code"); ptr->vaddr = ptr->paddr = bin->code_from; //ptr->vaddr = fsym; ptr->size = bin->code_to - ptr->paddr; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { //ut64 sz = arch ? r_buf_size (arch->buf): 0; strcpy (ptr->name, "data"); ptr->paddr = ptr->vaddr = fsymsz+fsym; if (ptr->vaddr > arch->buf->length) { ptr->paddr = ptr->vaddr = bin->code_to; ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; } else { ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; // hacky workaround //dprintf ("Hack\n"); //ptr->size = ptr->vsize = 1024; } ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; //|2; ptr->add = true; r_list_append (ret, ptr); } return ret; } static void header(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; struct r_bin_t *rbin = arch->rbin; rbin->cb_printf ("DEX file header:\n"); rbin->cb_printf ("magic : 'dex\\n035\\0'\n"); rbin->cb_printf ("checksum : %x\n", bin->header.checksum); rbin->cb_printf ("signature : %02x%02x...%02x%02x\n", bin->header.signature[0], bin->header.signature[1], bin->header.signature[18], bin->header.signature[19]); rbin->cb_printf ("file_size : %d\n", bin->header.size); rbin->cb_printf ("header_size : %d\n", bin->header.header_size); rbin->cb_printf ("link_size : %d\n", bin->header.linksection_size); rbin->cb_printf ("link_off : %d (0x%06x)\n", bin->header.linksection_offset, bin->header.linksection_offset); rbin->cb_printf ("string_ids_size : %d\n", bin->header.strings_size); rbin->cb_printf ("string_ids_off : %d (0x%06x)\n", bin->header.strings_offset, bin->header.strings_offset); rbin->cb_printf ("type_ids_size : %d\n", bin->header.types_size); rbin->cb_printf ("type_ids_off : %d (0x%06x)\n", bin->header.types_offset, bin->header.types_offset); rbin->cb_printf ("proto_ids_size : %d\n", bin->header.prototypes_size); rbin->cb_printf ("proto_ids_off : %d (0x%06x)\n", bin->header.prototypes_offset, bin->header.prototypes_offset); rbin->cb_printf ("field_ids_size : %d\n", bin->header.fields_size); rbin->cb_printf ("field_ids_off : %d (0x%06x)\n", bin->header.fields_offset, bin->header.fields_offset); rbin->cb_printf ("method_ids_size : %d\n", bin->header.method_size); rbin->cb_printf ("method_ids_off : %d (0x%06x)\n", bin->header.method_offset, bin->header.method_offset); rbin->cb_printf ("class_defs_size : %d\n", bin->header.class_size); rbin->cb_printf ("class_defs_off : %d (0x%06x)\n", bin->header.class_offset, bin->header.class_offset); rbin->cb_printf ("data_size : %d\n", bin->header.data_size); rbin->cb_printf ("data_off : %d (0x%06x)\n\n", bin->header.data_offset, bin->header.data_offset); // TODO: print information stored in the RBIN not this ugly fix dexdump = true; bin->methods_list = NULL; dex_loadcode (arch, bin); dexdump = false; } static ut64 size(RBinFile *arch) { int ret; ut32 off = 0, len = 0; ut8 u32s[sizeof (ut32)] = {0}; ret = r_buf_read_at (arch->buf, 108, u32s, 4); if (ret != 4) { return 0; } off = r_read_le32 (u32s); ret = r_buf_read_at (arch->buf, 104, u32s, 4); if (ret != 4) { return 0; } len = r_read_le32 (u32s); return off + len; } RBinPlugin r_bin_plugin_dex = { .name = "dex", .desc = "dex format bin plugin", .license = "LGPL3", .get_sdb = &get_sdb, .load = &load, .load_bytes = &load_bytes, .check = &check, .check_bytes = &check_bytes, .baddr = &baddr, .entries = entries, .classes = classes, .sections = sections, .symbols = methods, .imports = imports, .strings = strings, .info = &info, .header = &header, .size = &size, .get_offset = &getoffset, .get_name = &getname, .dbginfo = &r_bin_dbginfo_dex, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_BIN, .data = &r_bin_plugin_dex, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-476/c/good_3185_0
crossvul-cpp_data_good_1847_0
/* RFCOMM implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com> Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org> 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; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* * RFCOMM sockets. */ #include <linux/export.h> #include <linux/debugfs.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/rfcomm.h> static const struct proto_ops rfcomm_sock_ops; static struct bt_sock_list rfcomm_sk_list = { .lock = __RW_LOCK_UNLOCKED(rfcomm_sk_list.lock) }; static void rfcomm_sock_close(struct sock *sk); static void rfcomm_sock_kill(struct sock *sk); /* ---- DLC callbacks ---- * * called under rfcomm_dlc_lock() */ static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb) { struct sock *sk = d->owner; if (!sk) return; atomic_add(skb->len, &sk->sk_rmem_alloc); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_data_ready(sk); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) rfcomm_dlc_throttle(d); } static void rfcomm_sk_state_change(struct rfcomm_dlc *d, int err) { struct sock *sk = d->owner, *parent; unsigned long flags; if (!sk) return; BT_DBG("dlc %p state %ld err %d", d, d->state, err); local_irq_save(flags); bh_lock_sock(sk); if (err) sk->sk_err = err; sk->sk_state = d->state; parent = bt_sk(sk)->parent; if (parent) { if (d->state == BT_CLOSED) { sock_set_flag(sk, SOCK_ZAPPED); bt_accept_unlink(sk); } parent->sk_data_ready(parent); } else { if (d->state == BT_CONNECTED) rfcomm_session_getaddr(d->session, &rfcomm_pi(sk)->src, NULL); sk->sk_state_change(sk); } bh_unlock_sock(sk); local_irq_restore(flags); if (parent && sock_flag(sk, SOCK_ZAPPED)) { /* We have to drop DLC lock here, otherwise * rfcomm_sock_destruct() will dead lock. */ rfcomm_dlc_unlock(d); rfcomm_sock_kill(sk); rfcomm_dlc_lock(d); } } /* ---- Socket functions ---- */ static struct sock *__rfcomm_get_listen_sock_by_addr(u8 channel, bdaddr_t *src) { struct sock *sk = NULL; sk_for_each(sk, &rfcomm_sk_list.head) { if (rfcomm_pi(sk)->channel != channel) continue; if (bacmp(&rfcomm_pi(sk)->src, src)) continue; if (sk->sk_state == BT_BOUND || sk->sk_state == BT_LISTEN) break; } return sk ? sk : NULL; } /* Find socket with channel and source bdaddr. * Returns closest match. */ static struct sock *rfcomm_get_sock_by_channel(int state, u8 channel, bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, &rfcomm_sk_list.head) { if (state && sk->sk_state != state) continue; if (rfcomm_pi(sk)->channel == channel) { /* Exact match. */ if (!bacmp(&rfcomm_pi(sk)->src, src)) break; /* Closest match */ if (!bacmp(&rfcomm_pi(sk)->src, BDADDR_ANY)) sk1 = sk; } } read_unlock(&rfcomm_sk_list.lock); return sk ? sk : sk1; } static void rfcomm_sock_destruct(struct sock *sk) { struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; BT_DBG("sk %p dlc %p", sk, d); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); rfcomm_dlc_lock(d); rfcomm_pi(sk)->dlc = NULL; /* Detach DLC if it's owned by this socket */ if (d->owner == sk) d->owner = NULL; rfcomm_dlc_unlock(d); rfcomm_dlc_put(d); } static void rfcomm_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted dlcs */ while ((sk = bt_accept_dequeue(parent, NULL))) { rfcomm_sock_close(sk); rfcomm_sock_kill(sk); } parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void rfcomm_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d refcnt %d", sk, sk->sk_state, atomic_read(&sk->sk_refcnt)); /* Kill poor orphan */ bt_sock_unlink(&rfcomm_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __rfcomm_sock_close(struct sock *sk) { struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: rfcomm_sock_cleanup_listen(sk); break; case BT_CONNECT: case BT_CONNECT2: case BT_CONFIG: case BT_CONNECTED: rfcomm_dlc_close(d, 0); default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Close socket. * Must be called on unlocked socket. */ static void rfcomm_sock_close(struct sock *sk) { lock_sock(sk); __rfcomm_sock_close(sk); release_sock(sk); } static void rfcomm_sock_init(struct sock *sk, struct sock *parent) { struct rfcomm_pinfo *pi = rfcomm_pi(sk); BT_DBG("sk %p", sk); if (parent) { sk->sk_type = parent->sk_type; pi->dlc->defer_setup = test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags); pi->sec_level = rfcomm_pi(parent)->sec_level; pi->role_switch = rfcomm_pi(parent)->role_switch; security_sk_clone(parent, sk); } else { pi->dlc->defer_setup = 0; pi->sec_level = BT_SECURITY_LOW; pi->role_switch = 0; } pi->dlc->sec_level = pi->sec_level; pi->dlc->role_switch = pi->role_switch; } static struct proto rfcomm_proto = { .name = "RFCOMM", .owner = THIS_MODULE, .obj_size = sizeof(struct rfcomm_pinfo) }; static struct sock *rfcomm_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio, int kern) { struct rfcomm_dlc *d; struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &rfcomm_proto, kern); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); d = rfcomm_dlc_alloc(prio); if (!d) { sk_free(sk); return NULL; } d->data_ready = rfcomm_sk_data_ready; d->state_change = rfcomm_sk_state_change; rfcomm_pi(sk)->dlc = d; d->owner = sk; sk->sk_destruct = rfcomm_sock_destruct; sk->sk_sndtimeo = RFCOMM_CONN_TIMEOUT; sk->sk_sndbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10; sk->sk_rcvbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; bt_sock_link(&rfcomm_sk_list, sk); BT_DBG("sk %p", sk); return sk; } static int rfcomm_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_STREAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sock->ops = &rfcomm_sock_ops; sk = rfcomm_sock_alloc(net, sock, protocol, GFP_ATOMIC, kern); if (!sk) return -ENOMEM; rfcomm_sock_init(sk, NULL); return 0; } static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_rc sa; struct sock *sk = sock->sk; int len, err = 0; if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&sa, 0, sizeof(sa)); len = min_t(unsigned int, sizeof(sa), addr_len); memcpy(&sa, addr, len); BT_DBG("sk %p %pMR", sk, &sa.rc_bdaddr); lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } write_lock(&rfcomm_sk_list.lock); if (sa.rc_channel && __rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr); rfcomm_pi(sk)->channel = sa.rc_channel; sk->sk_state = BT_BOUND; } write_unlock(&rfcomm_sk_list.lock); done: release_sock(sk); return err; } static int rfcomm_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int err = 0; BT_DBG("sk %p", sk); if (alen < sizeof(struct sockaddr_rc) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } sk->sk_state = BT_CONNECT; bacpy(&rfcomm_pi(sk)->dst, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = sa->rc_channel; d->sec_level = rfcomm_pi(sk)->sec_level; d->role_switch = rfcomm_pi(sk)->role_switch; err = rfcomm_dlc_open(d, &rfcomm_pi(sk)->src, &sa->rc_bdaddr, sa->rc_channel); if (!err) err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int rfcomm_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } if (!rfcomm_pi(sk)->channel) { bdaddr_t *src = &rfcomm_pi(sk)->src; u8 channel; err = -EINVAL; write_lock(&rfcomm_sk_list.lock); for (channel = 1; channel < 31; channel++) if (!__rfcomm_get_listen_sock_by_addr(channel, src)) { rfcomm_pi(sk)->channel = channel; err = 0; break; } write_unlock(&rfcomm_sk_list.lock); if (err < 0) goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DEFINE_WAIT_FUNC(wait, woken_wake_function); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } nsk = bt_accept_dequeue(sk, newsock); if (nsk) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); } remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; } static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); if (peer && sk->sk_state != BT_CONNECTED && sk->sk_state != BT_CONNECT && sk->sk_state != BT_CONNECT2) return -ENOTCONN; memset(sa, 0, sizeof(*sa)); sa->rc_family = AF_BLUETOOTH; sa->rc_channel = rfcomm_pi(sk)->channel; if (peer) bacpy(&sa->rc_bdaddr, &rfcomm_pi(sk)->dst); else bacpy(&sa->rc_bdaddr, &rfcomm_pi(sk)->src); *len = sizeof(struct sockaddr_rc); return 0; } static int rfcomm_sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; struct sk_buff *skb; int sent; if (test_bit(RFCOMM_DEFER_SETUP, &d->flags)) return -ENOTCONN; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (sk->sk_shutdown & SEND_SHUTDOWN) return -EPIPE; BT_DBG("sock %p, sk %p", sock, sk); lock_sock(sk); sent = bt_sock_wait_ready(sk, msg->msg_flags); if (sent) goto done; while (len) { size_t size = min_t(size_t, len, d->mtu); int err; skb = sock_alloc_send_skb(sk, size + RFCOMM_SKB_RESERVE, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) { if (sent == 0) sent = err; break; } skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE); err = memcpy_from_msg(skb_put(skb, size), msg, size); if (err) { kfree_skb(skb); if (sent == 0) sent = err; break; } skb->priority = sk->sk_priority; err = rfcomm_dlc_send(d, skb); if (err < 0) { kfree_skb(skb); if (sent == 0) sent = err; break; } sent += size; len -= size; } done: release_sock(sk); return sent; } static int rfcomm_sock_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int len; if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) { rfcomm_dlc_accept(d); return 0; } len = bt_sock_stream_recvmsg(sock, msg, size, flags); lock_sock(sk); if (!(flags & MSG_PEEK) && len > 0) atomic_sub(len, &sk->sk_rmem_alloc); if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2)) rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc); release_sock(sk); return len; } static int rfcomm_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case RFCOMM_LM: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt & RFCOMM_LM_FIPS) { err = -EINVAL; break; } if (opt & RFCOMM_LM_AUTH) rfcomm_pi(sk)->sec_level = BT_SECURITY_LOW; if (opt & RFCOMM_LM_ENCRYPT) rfcomm_pi(sk)->sec_level = BT_SECURITY_MEDIUM; if (opt & RFCOMM_LM_SECURE) rfcomm_pi(sk)->sec_level = BT_SECURITY_HIGH; rfcomm_pi(sk)->role_switch = (opt & RFCOMM_LM_MASTER); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct bt_security sec; int err = 0; size_t len; u32 opt; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_setsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = BT_SECURITY_LOW; len = min_t(unsigned int, sizeof(sec), optlen); if (copy_from_user((char *) &sec, optval, len)) { err = -EFAULT; break; } if (sec.level > BT_SECURITY_HIGH) { err = -EINVAL; break; } rfcomm_pi(sk)->sec_level = sec.level; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sock *l2cap_sk; struct l2cap_conn *conn; struct rfcomm_conninfo cinfo; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case RFCOMM_LM: switch (rfcomm_pi(sk)->sec_level) { case BT_SECURITY_LOW: opt = RFCOMM_LM_AUTH; break; case BT_SECURITY_MEDIUM: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT; break; case BT_SECURITY_HIGH: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT | RFCOMM_LM_SECURE; break; case BT_SECURITY_FIPS: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT | RFCOMM_LM_SECURE | RFCOMM_LM_FIPS; break; default: opt = 0; break; } if (rfcomm_pi(sk)->role_switch) opt |= RFCOMM_LM_MASTER; if (put_user(opt, (u32 __user *) optval)) err = -EFAULT; break; case RFCOMM_CONNINFO: if (sk->sk_state != BT_CONNECTED && !rfcomm_pi(sk)->dlc->defer_setup) { err = -ENOTCONN; break; } l2cap_sk = rfcomm_pi(sk)->dlc->session->sock->sk; conn = l2cap_pi(l2cap_sk)->chan->conn; memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = conn->hcon->handle; memcpy(cinfo.dev_class, conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *) &cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = rfcomm_pi(sk)->sec_level; sec.key_size = 0; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk __maybe_unused = sock->sk; int err; BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg); err = bt_sock_ioctl(sock, cmd, arg); if (err == -ENOIOCTLCMD) { #ifdef CONFIG_BT_RFCOMM_TTY lock_sock(sk); err = rfcomm_dev_ioctl(sk, cmd, (void __user *) arg); release_sock(sk); #else err = -EOPNOTSUPP; #endif } return err; } static int rfcomm_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; __rfcomm_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime && !(current->flags & PF_EXITING)) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); return err; } static int rfcomm_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; err = rfcomm_sock_shutdown(sock, 2); sock_orphan(sk); rfcomm_sock_kill(sk); return err; } /* ---- RFCOMM core layer callbacks ---- * * called under rfcomm_lock() */ int rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d) { struct sock *sk, *parent; bdaddr_t src, dst; int result = 0; BT_DBG("session %p channel %d", s, channel); rfcomm_session_getaddr(s, &src, &dst); /* Check if we have socket listening on channel */ parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src); if (!parent) return 0; bh_lock_sock(parent); /* Check for backlog size */ if (sk_acceptq_is_full(parent)) { BT_DBG("backlog full %d", parent->sk_ack_backlog); goto done; } sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC, 0); if (!sk) goto done; bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM); rfcomm_sock_init(sk, parent); bacpy(&rfcomm_pi(sk)->src, &src); bacpy(&rfcomm_pi(sk)->dst, &dst); rfcomm_pi(sk)->channel = channel; sk->sk_state = BT_CONFIG; bt_accept_enqueue(parent, sk); /* Accept connection and return socket DLC */ *d = rfcomm_pi(sk)->dlc; result = 1; done: bh_unlock_sock(parent); if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) parent->sk_state_change(parent); return result; } static int rfcomm_sock_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, &rfcomm_sk_list.head) { seq_printf(f, "%pMR %pMR %d %d\n", &rfcomm_pi(sk)->src, &rfcomm_pi(sk)->dst, sk->sk_state, rfcomm_pi(sk)->channel); } read_unlock(&rfcomm_sk_list.lock); return 0; } static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file) { return single_open(file, rfcomm_sock_debugfs_show, inode->i_private); } static const struct file_operations rfcomm_sock_debugfs_fops = { .open = rfcomm_sock_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *rfcomm_sock_debugfs; static const struct proto_ops rfcomm_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = rfcomm_sock_release, .bind = rfcomm_sock_bind, .connect = rfcomm_sock_connect, .listen = rfcomm_sock_listen, .accept = rfcomm_sock_accept, .getname = rfcomm_sock_getname, .sendmsg = rfcomm_sock_sendmsg, .recvmsg = rfcomm_sock_recvmsg, .shutdown = rfcomm_sock_shutdown, .setsockopt = rfcomm_sock_setsockopt, .getsockopt = rfcomm_sock_getsockopt, .ioctl = rfcomm_sock_ioctl, .poll = bt_sock_poll, .socketpair = sock_no_socketpair, .mmap = sock_no_mmap }; static const struct net_proto_family rfcomm_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = rfcomm_sock_create }; int __init rfcomm_init_sockets(void) { int err; BUILD_BUG_ON(sizeof(struct sockaddr_rc) > sizeof(struct sockaddr)); err = proto_register(&rfcomm_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_RFCOMM, &rfcomm_sock_family_ops); if (err < 0) { BT_ERR("RFCOMM socket layer registration failed"); goto error; } err = bt_procfs_init(&init_net, "rfcomm", &rfcomm_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create RFCOMM proc file"); bt_sock_unregister(BTPROTO_RFCOMM); goto error; } BT_INFO("RFCOMM socket layer initialized"); if (IS_ERR_OR_NULL(bt_debugfs)) return 0; rfcomm_sock_debugfs = debugfs_create_file("rfcomm", 0444, bt_debugfs, NULL, &rfcomm_sock_debugfs_fops); return 0; error: proto_unregister(&rfcomm_proto); return err; } void __exit rfcomm_cleanup_sockets(void) { bt_procfs_cleanup(&init_net, "rfcomm"); debugfs_remove(rfcomm_sock_debugfs); bt_sock_unregister(BTPROTO_RFCOMM); proto_unregister(&rfcomm_proto); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_1847_0
crossvul-cpp_data_good_3164_1
/* radare - LGPL - Copyright 2011-2016 - pancake */ #include <r_cons.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_bin.h> #include "dex/dex.h" #define r_hash_adler32 __adler32 #include "../../hash/adler32.c" extern struct r_bin_dbginfo_t r_bin_dbginfo_dex; #define DEBUG_PRINTF 0 #if DEBUG_PRINTF #define dprintf eprintf #else #define dprintf if (0)eprintf #endif static bool dexdump = false; static Sdb *mdb = NULL; static Sdb *cdb = NULL; // TODO: remove if it is not used static char *getstr(RBinDexObj *bin, int idx) { ut8 buf[6]; ut64 len; int uleblen; if (!bin || idx < 0 || idx >= bin->header.strings_size || !bin->strings) { return NULL; } if (bin->strings[idx] >= bin->size) { return NULL; } if (r_buf_read_at (bin->b, bin->strings[idx], buf, sizeof (buf)) < 1) { return NULL; } uleblen = r_uleb128 (buf, sizeof (buf), &len) - buf; if (!uleblen || uleblen >= bin->size) { return NULL; } if (!len || len >= bin->size) { return NULL; } // TODO: improve this ugly fix char c = 'a'; while (c) { ut64 offset = bin->strings[idx] + uleblen + len; if (offset >= bin->size || offset < len) { return NULL; } r_buf_read_at (bin->b, offset, (ut8*)&c, 1); len++; } if ((int)len > 0 && len < R_BIN_SIZEOF_STRINGS) { char *str = calloc (1, len + 1); if (str) { r_buf_read_at (bin->b, (bin->strings[idx]) + uleblen, (ut8 *)str, len); str[len] = 0; return str; } } return NULL; } static int countOnes(ut32 val) { int count = 0; val = val - ((val >> 1) & 0x55555555); val = (val & 0x33333333) + ((val >> 2) & 0x33333333); count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; return count; } typedef enum { kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX } AccessFor; static char *createAccessFlagStr(ut32 flags, AccessFor forWhat) { #define NUM_FLAGS 18 static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = { { /* class, inner class */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "?", /* 0x0040 */ "?", /* 0x0080 */ "?", /* 0x0100 */ "INTERFACE", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "ANNOTATION", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "VERIFIED", /* 0x10000 */ "OPTIMIZED", /* 0x20000 */ }, { /* method */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "SYNCHRONIZED", /* 0x0020 */ "BRIDGE", /* 0x0040 */ "VARARGS", /* 0x0080 */ "NATIVE", /* 0x0100 */ "?", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "STRICT", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "?", /* 0x4000 */ "MIRANDA", /* 0x8000 */ "CONSTRUCTOR", /* 0x10000 */ "DECLARED_SYNCHRONIZED", /* 0x20000 */ }, { /* field */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "VOLATILE", /* 0x0040 */ "TRANSIENT", /* 0x0080 */ "?", /* 0x0100 */ "?", /* 0x0200 */ "?", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "?", /* 0x10000 */ "?", /* 0x20000 */ }, }; const int kLongest = 21; int i, count; char* str; char* cp; count = countOnes(flags); // XXX check if this allocation is safe what if all the arithmetic // produces a huge number???? cp = str = (char*) malloc (count * (kLongest + 1) + 1); for (i = 0; i < NUM_FLAGS; i++) { if (flags & 0x01) { const char* accessStr = kAccessStrings[forWhat][i]; int len = strlen(accessStr); if (cp != str) { *cp++ = ' '; } memcpy(cp, accessStr, len); cp += len; } flags >>= 1; } *cp = '\0'; return str; } static char *dex_type_descriptor(RBinDexObj *bin, int type_idx) { if (type_idx < 0 || type_idx >= bin->header.types_size) { return NULL; } return getstr (bin, bin->types[type_idx].descriptor_id); } static char *dex_method_signature(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, type_id, list_size; char *r, *return_type = NULL, *signature = NULL, *buff = NULL; ut8 *bufptr; ut16 type_idx; int pos = 0, i, size = 1; if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { return NULL; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { return NULL; } type_id = bin->protos[proto_id].return_type_id; if (type_id >= bin->header.types_size ) { return NULL; } return_type = getstr (bin, bin->types[type_id].descriptor_id); if (!return_type) { return NULL; } if (!params_off) { return r_str_newf ("()%s", return_type);; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX again list_size is user controlled huge loop for (i = 0; i < list_size; i++) { int buff_len = 0; if (params_off + 4 + (i * 2) >= bin->size) { break; } type_idx = r_read_le16 (bufptr + params_off + 4 + (i * 2)); if (type_idx < 0 || type_idx >= bin->header.types_size || type_idx >= bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } buff_len = strlen (buff); size += buff_len + 1; signature = realloc (signature, size); strcpy (signature + pos, buff); pos += buff_len; signature[pos] = '\0'; } r = r_str_newf ("(%s)%s", signature, return_type); free (buff); free (signature); return r; } static RList *dex_method_signature2(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, list_size; char *buff = NULL; ut8 *bufptr; ut16 type_idx; int i; RList *params = r_list_newf (free); if (!params) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { goto out_error; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { goto out_error; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { goto out_error; } if (!params_off) { return params; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX list_size tainted it may produce huge loop for (i = 0; i < list_size; i++) { ut64 of = params_off + 4 + (i * 2); if (of >= bin->size || of < params_off) { break; } type_idx = r_read_le16 (bufptr + of); if (type_idx >= bin->header.types_size || type_idx > bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } r_list_append (params, buff); } return params; out_error: r_list_free (params); return NULL; } // TODO: fix this, now has more registers that it should // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L312 // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L141 static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg >= regsz) { //return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); } static int check (RBinFile *arch); static int check_bytes (const ut8 *buf, ut64 length); static Sdb *get_sdb (RBinObject *o) { if (!o || !o->bin_obj) { return NULL; } struct r_bin_dex_obj_t *bin = (struct r_bin_dex_obj_t *) o->bin_obj; if (bin->kv) { return bin->kv; } return NULL; } static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb){ void *res = NULL; RBuffer *tbuf = NULL; if (!buf || !sz || sz == UT64_MAX) { return NULL; } tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); res = r_bin_dex_new_buf (tbuf); r_buf_free (tbuf); return res; } static int load(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; if (!arch || !arch->o) { return false; } arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb); return arch->o->bin_obj ? true: false; } static ut64 baddr(RBinFile *arch) { return 0; } static int check(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; return check_bytes (bytes, sz); } static int check_bytes(const ut8 *buf, ut64 length) { if (!buf || length < 8) { return false; } // Non-extended opcode dex file if (!memcmp (buf, "dex\n035\0", 8)) { return true; } // Extended (jumnbo) opcode dex file, ICS+ only (sdk level 14+) if (!memcmp (buf, "dex\n036\0", 8)) { return true; } // M3 (Nov-Dec 07) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // M5 (Feb-Mar 08) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // Default fall through, should still be a dex file if (!memcmp (buf, "dex\n", 4)) { return true; } return false; } static RBinInfo *info(RBinFile *arch) { RBinHash *h; RBinInfo *ret = R_NEW0 (RBinInfo); if (!ret) { return NULL; } ret->file = arch->file? strdup (arch->file): NULL; ret->type = strdup ("DEX CLASS"); ret->has_va = false; ret->bclass = r_bin_dex_get_version (arch->o->bin_obj); ret->rclass = strdup ("class"); ret->os = strdup ("linux"); ret->subsystem = strdup ("any"); ret->machine = strdup ("Dalvik VM"); h = &ret->sum[0]; h->type = "sha1"; h->len = 20; h->addr = 12; h->from = 12; h->to = arch->buf->length-32; memcpy (h->buf, arch->buf->buf+12, 20); h = &ret->sum[1]; h->type = "adler32"; h->len = 4; h->addr = 0x8; h->from = 12; h->to = arch->buf->length-h->from; h = &ret->sum[2]; h->type = 0; memcpy (h->buf, arch->buf->buf + 8, 4); { ut32 *fc = (ut32 *)(arch->buf->buf + 8); ut32 cc = __adler32 (arch->buf->buf + 12, arch->buf->length - 12); if (*fc != cc) { eprintf ("# adler32 checksum doesn't match. Type this to fix it:\n"); eprintf ("wx `#sha1 $s-32 @32` @12 ; wx `#adler32 $s-12 @12` @8\n"); } } ret->arch = strdup ("dalvik"); ret->lang = "dalvik"; ret->bits = 32; ret->big_endian = 0; ret->dbg_info = 0; //1 | 4 | 8; /* Stripped | LineNums | Syms */ return ret; } static RList *strings(RBinFile *arch) { struct r_bin_dex_obj_t *bin = NULL; RBinString *ptr = NULL; RList *ret = NULL; int i, len; ut8 buf[6]; ut64 off; if (!arch || !arch->o) { return NULL; } bin = (struct r_bin_dex_obj_t *) arch->o->bin_obj; if (!bin || !bin->strings) { return NULL; } if (bin->header.strings_size > bin->size) { bin->strings = NULL; return NULL; } if (!(ret = r_list_newf (free))) { return NULL; } for (i = 0; i < bin->header.strings_size; i++) { if (!(ptr = R_NEW0 (RBinString))) { break; } if (bin->strings[i] > bin->size || bin->strings[i] + 6 > bin->size) { goto out_error; } r_buf_read_at (bin->b, bin->strings[i], (ut8*)&buf, 6); len = dex_read_uleb128 (buf); if (len > 1 && len < R_BIN_SIZEOF_STRINGS) { ptr->string = malloc (len + 1); if (!ptr->string) { goto out_error; } off = bin->strings[i] + dex_uleb128_len (buf); if (off + len >= bin->size || off + len < len) { free (ptr->string); goto out_error; } r_buf_read_at (bin->b, off, (ut8*)ptr->string, len); ptr->string[len] = 0; ptr->vaddr = ptr->paddr = bin->strings[i]; ptr->size = len; ptr->length = len; ptr->ordinal = i+1; r_list_append (ret, ptr); } else { free (ptr); } } return ret; out_error: r_list_free (ret); free (ptr); return NULL; } static char *dex_method_name(RBinDexObj *bin, int idx) { if (idx < 0 || idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[idx].class_id; if (cid < 0 || cid >= bin->header.strings_size) { return NULL; } int tid = bin->methods[idx].name_id; if (tid < 0 || tid >= bin->header.strings_size) { return NULL; } return getstr (bin, tid); } static char *dex_class_name_byid(RBinDexObj *bin, int cid) { int tid; if (!bin || !bin->types) { return NULL; } if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) { return dex_class_name_byid (bin, c->class_id); } static char *dex_field_name(RBinDexObj *bin, int fid) { int cid, tid, type_id; if (!bin || !bin->fields) { return NULL; } if (fid < 0 || fid >= bin->header.fields_size) { return NULL; } cid = bin->fields[fid].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } type_id = bin->fields[fid].type_id; if (type_id < 0 || type_id >= bin->header.types_size) { return NULL; } tid = bin->fields[fid].name_id; return r_str_newf ("%s->%s %s", getstr (bin, bin->types[cid].descriptor_id), getstr (bin, tid), getstr (bin, bin->types[type_id].descriptor_id)); } static char *dex_method_fullname(RBinDexObj *bin, int method_idx) { if (!bin || !bin->types) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[method_idx].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } char *name = dex_method_name (bin, method_idx); char *class_name = dex_class_name_byid (bin, cid); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func char *signature = dex_method_signature (bin, method_idx); char *flagname = r_str_newf ("%s.%s%s", class_name, name, signature); free (name); free (class_name); free (signature); return flagname; } static ut64 dex_get_type_offset(RBinFile *arch, int type_idx) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin || !bin->types) { return 0; } if (type_idx < 0 || type_idx >= bin->header.types_size) { return 0; } return bin->header.types_offset + type_idx * 0x04; //&bin->types[type_idx]; } static void __r_bin_class_free(RBinClass *p) { r_list_free (p->methods); r_list_free (p->fields); r_bin_class_free (p); } static char *dex_class_super_name(RBinDexObj *bin, RBinDexClass *c) { int cid, tid; if (!bin || !c || !bin->types) { return NULL; } cid = c->super_class; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static const ut8 *parse_dex_class_fields(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 fields_count, bool is_sfield) { struct r_bin_t *rbin = binfile->rbin; ut64 lastIndex = 0; ut8 ff[sizeof (DexField)] = {0}; int total, i, tid; DexField field; const char* type_str; for (i = 0; i < fields_count; i++) { ut64 fieldIndex, accessFlags; p = r_uleb128 (p, p_end - p, &fieldIndex); // fieldIndex p = r_uleb128 (p, p_end - p, &accessFlags); // accessFlags fieldIndex += lastIndex; total = bin->header.fields_offset + (sizeof (DexField) * fieldIndex); if (total >= bin->size || total < bin->header.fields_offset) { break; } if (r_buf_read_at (binfile->buf, total, ff, sizeof (DexField)) != sizeof (DexField)) { break; } field.class_id = r_read_le16 (ff); field.type_id = r_read_le16 (ff + 2); field.name_id = r_read_le32 (ff + 4); char *fieldName = getstr (bin, field.name_id); if (field.type_id >= bin->header.types_size) { break; } tid = bin->types[field.type_id].descriptor_id; type_str = getstr (bin, tid); RBinSymbol *sym = R_NEW0 (RBinSymbol); if (is_sfield) { sym->name = r_str_newf ("%s.sfield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("STATIC"); } else { sym->name = r_str_newf ("%s.ifield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("FIELD"); } sym->name = r_str_replace (sym->name, "method.", "", 0); //sym->name = r_str_replace (sym->name, ";", "", 0); sym->paddr = sym->vaddr = total; sym->ordinal = (*sym_count)++; if (dexdump) { const char *accessStr = createAccessFlagStr ( accessFlags, kAccessForField); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", fieldName); rbin->cb_printf (" type : '%s'\n", type_str); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)accessFlags, accessStr); } r_list_append (bin->methods_list, sym); r_list_append (cls->fields, sym); lastIndex = fieldIndex; } return p; } // TODO: refactor this method // XXX it needs a lot of love!!! static const ut8 *parse_dex_class_method(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 DM, int *methods, bool is_direct) { struct r_bin_t *rbin = binfile->rbin; ut8 ff2[16] = {0}; ut8 ff3[8] = {0}; int i; ut64 omi = 0; bool catchAll; ut16 regsz, ins_size, outs_size, tries_size; ut16 handler_off, start_addr, insn_count; ut32 debug_info_off, insns_size; const ut8 *encoded_method_addr; for (i = 0; i < DM; i++) { encoded_method_addr = p; char *method_name, *flag_name; ut64 MI, MA, MC; p = r_uleb128 (p, p_end - p, &MI); MI += omi; omi = MI; p = r_uleb128 (p, p_end - p, &MA); p = r_uleb128 (p, p_end - p, &MC); // TODO: MOVE CHECKS OUTSIDE! if (MI < bin->header.method_size) { if (methods) { methods[MI] = 1; } } method_name = dex_method_name (bin, MI); char *signature = dex_method_signature (bin, MI); if (!method_name) { method_name = strdup ("unknown"); } flag_name = r_str_newf ("%s.method.%s%s", cls->name, method_name, signature); if (!flag_name) { R_FREE (method_name); R_FREE (signature); continue; } // TODO: check size // ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; ut64 v2, handler_type, handler_addr; int t; if (MC > 0) { // TODO: parse debug info // XXX why binfile->buf->base??? if (MC + 16 >= bin->size || MC + 16 < MC) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } regsz = r_read_le16 (ff2); ins_size = r_read_le16 (ff2 + 2); outs_size = r_read_le16 (ff2 + 4); tries_size = r_read_le16 (ff2 + 6); debug_info_off = r_read_le32 (ff2 + 8); insns_size = r_read_le32 (ff2 + 12); int padd = 0; if (tries_size > 0 && insns_size % 2) { padd = 2; } t = 16 + 2 * insns_size + padd; } if (dexdump) { const char* accessStr = createAccessFlagStr (MA, kAccessForMethod); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", method_name); rbin->cb_printf (" type : '%s'\n", signature); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)MA, accessStr); } if (MC > 0) { if (dexdump) { rbin->cb_printf (" code -\n"); rbin->cb_printf (" registers : %d\n", regsz); rbin->cb_printf (" ins : %d\n", ins_size); rbin->cb_printf (" outs : %d\n", outs_size); rbin->cb_printf ( " insns size : %d 16-bit code " "units\n", insns_size); } if (tries_size > 0) { if (dexdump) { rbin->cb_printf (" catches : %d\n", tries_size); } int j, m = 0; //XXX bucle controlled by tainted variable it could produces huge loop for (j = 0; j < tries_size; ++j) { ut64 offset = MC + t + j * 8; if (offset >= bin->size || offset < MC) { R_FREE (signature); break; } if (r_buf_read_at ( binfile->buf, binfile->buf->base + offset, ff3, 8) < 1) { // free (method_name); R_FREE (signature); break; } start_addr = r_read_le32 (ff3); insn_count = r_read_le16 (ff3 + 4); handler_off = r_read_le16 (ff3 + 6); char* s = NULL; if (dexdump) { rbin->cb_printf ( " 0x%04x - " "0x%04x\n", start_addr, (start_addr + insn_count)); } const ut8 *p3, *p3_end; //XXX tries_size is tainted and oob here int off = MC + t + tries_size * 8 + handler_off; if (off >= bin->size || off < tries_size) { R_FREE (signature); break; } p3 = r_buf_get_at (binfile->buf, off, NULL); p3_end = p3 + binfile->buf->length - off; st64 size = r_sleb128 (&p3, p3_end); if (size <= 0) { catchAll = true; size = -size; } else { catchAll = false; } for (m = 0; m < size; m++) { p3 = r_uleb128 (p3, p3_end - p3, &handler_type); p3 = r_uleb128 (p3, p3_end - p3, &handler_addr); if (handler_type > 0 && handler_type < bin->header.types_size) { s = getstr (bin, bin->types[handler_type].descriptor_id); if (dexdump) { rbin->cb_printf ( " %s " "-> 0x%04llx\n", s, handler_addr); } } else { if (dexdump) { rbin->cb_printf ( " " "(error) -> " "0x%04llx\n", handler_addr); } } } if (catchAll) { p3 = r_uleb128 (p3, p3_end - p3, &v2); if (dexdump) { rbin->cb_printf ( " " "<any> -> " "0x%04llx\n", v2); } } } } else { if (dexdump) { rbin->cb_printf ( " catches : " "(none)\n"); } } } else { if (dexdump) { rbin->cb_printf ( " code : (none)\n"); } } if (*flag_name) { RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = flag_name; // is_direct is no longer used // if method has code *addr points to code // otherwise it points to the encoded method if (MC > 0) { sym->type = r_str_const ("FUNC"); sym->paddr = MC;// + 0x10; sym->vaddr = MC;// + 0x10; } else { sym->type = r_str_const ("METH"); sym->paddr = encoded_method_addr - binfile->buf->buf; sym->vaddr = encoded_method_addr - binfile->buf->buf; } if ((MA & 0x1) == 0x1) { sym->bind = r_str_const ("GLOBAL"); } else { sym->bind = r_str_const ("LOCAL"); } sym->ordinal = (*sym_count)++; if (MC > 0) { if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (sym); R_FREE (signature); continue; } //ut16 regsz = r_read_le16 (ff2); //ut16 ins_size = r_read_le16 (ff2 + 2); //ut16 outs_size = r_read_le16 (ff2 + 4); ut16 tries_size = r_read_le16 (ff2 + 6); //ut32 debug_info_off = r_read_le32 (ff2 + 8); ut32 insns_size = r_read_le32 (ff2 + 12); ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; if (tries_size > 0) { //prolog_size += 2 + 8*tries_size; // we need to parse all so the catch info... } // TODO: prolog_size sym->paddr = MC + prolog_size;// + 0x10; sym->vaddr = MC + prolog_size;// + 0x10; //if (is_direct) { sym->size = insns_size * 2; //} //eprintf("%s (0x%x-0x%x) size=%d\nregsz=%d\ninsns_size=%d\nouts_size=%d\ntries_size=%d\ninsns_size=%d\n", flag_name, sym->vaddr, sym->vaddr+sym->size, prolog_size, regsz, ins_size, outs_size, tries_size, insns_size); r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); if (bin->code_from > sym->paddr) { bin->code_from = sym->paddr; } if (bin->code_to < sym->paddr) { bin->code_to = sym->paddr; } if (!mdb) { mdb = sdb_new0 (); } sdb_num_set (mdb, sdb_fmt (0, "method.%d", MI), sym->paddr, 0); // ----------------- // WORK IN PROGRESS // ----------------- if (0) { if (MA & 0x10000) { //ACC_CONSTRUCTOR if (!cdb) { cdb = sdb_new0 (); } sdb_num_set (cdb, sdb_fmt (0, "%d", c->class_id), sym->paddr, 0); } } } else { sym->size = 0; r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); } if (MC > 0 && debug_info_off > 0 && bin->header.data_offset < debug_info_off && debug_info_off < bin->header.data_offset + bin->header.data_size) { dex_parse_debug_item (binfile, bin, c, MI, MA, sym->paddr, ins_size, insns_size, cls->name, regsz, debug_info_off); } else if (MC > 0) { if (dexdump) { rbin->cb_printf (" positions :\n"); rbin->cb_printf (" locals :\n"); } } } else { R_FREE (flag_name); } R_FREE (signature); R_FREE (method_name); } return p; } static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf (" Class descriptor : '%s;'\n", class_name); rbin->cb_printf ( " Access flags : 0x%04x (%s)\n", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf (" Superclass : '%s'\n", dex_class_super_name (bin, c)); rbin->cb_printf (" Interfaces -\n"); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32 (p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( " #%d : '%s'\n", z, getstr (bin, tid)); } } } } // TODO: this is quite ugly if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( " Static fields -\n Instance fields " "-\n Direct methods -\n Virtual methods " "-\n"); } } else { // TODO: move to func, def or inline // class_data_offset => [class_offset, class_defs_off+class_defs_size*32] if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; //XXX check for NULL!! c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf (" Static fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf (" Instance fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf (" Direct methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf (" Virtual methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( " source_file_idx : %d (unknown)\n\n", c->source_file); } else { rbin->cb_printf (" source_file_idx : %d (%s)\n\n", c->source_file, source_file); } } // TODO:!!!! // FIX: FREE BEFORE ALLOCATE!!! //free (class_name); } static bool is_class_idx_in_code_classes(RBinDexObj *bin, int class_idx) { int i; for (i = 0; i < bin->header.class_size; i++) { if (class_idx == bin->classes[i].class_id) { return true; } } return false; } static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size - 1) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; } static RList* imports(RBinFile *arch) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin) { return NULL; } if (bin && bin->imports_list) { return bin->imports_list; } dex_loadcode (arch, bin); return bin->imports_list; } static RList *methods(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->methods_list) { dex_loadcode (arch, bin); } return bin->methods_list; } static RList *classes(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->classes_list) { dex_loadcode (arch, bin); } return bin->classes_list; } static int already_entry(RList *entries, ut64 vaddr) { RBinAddr *e; RListIter *iter; r_list_foreach (entries, iter, e) { if (e->vaddr == vaddr) { return 1; } } return 0; } static RList *entries(RBinFile *arch) { RListIter *iter; RBinDexObj *bin; RBinSymbol *m; RBinAddr *ptr; RList *ret; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; ret = r_list_newf ((RListFree)free); if (!bin->methods_list) { dex_loadcode (arch, bin); } // STEP 1. ".onCreate(Landroid/os/Bundle;)V" r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 30 && m->bind && !strcmp(m->bind, "GLOBAL") && !strcmp (m->name + strlen (m->name) - 31, ".onCreate(Landroid/os/Bundle;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } // STEP 2. ".main([Ljava/lang/String;)V" if (r_list_empty (ret)) { r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 26 && !strcmp (m->name + strlen (m->name) - 27, ".main([Ljava/lang/String;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } } // STEP 3. NOTHING FOUND POINT TO CODE_INIT if (r_list_empty (ret)) { if (!already_entry (ret, bin->code_from)) { ptr = R_NEW0 (RBinAddr); if (ptr) { ptr->paddr = ptr->vaddr = bin->code_from; r_list_append (ret, ptr); } } } return ret; } static ut64 offset_of_method_idx(RBinFile *arch, struct r_bin_dex_obj_t *dex, int idx) { ut64 off = dex->header.method_offset + idx; off = sdb_num_get (mdb, sdb_fmt (0, "method.%d", idx), 0); return (ut64) off; } // TODO: change all return type for all getoffset static int getoffset(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods // TODO: ADD CHECK return offset_of_method_idx (arch, dex, idx); case 'o': // objects break; case 's': // strings if (dex->header.strings_size > idx) { if (dex->strings) return dex->strings[idx]; } break; case 't': // type return dex_get_type_offset (arch, idx); case 'c': // class return dex_get_type_offset (arch, idx); //return sdb_num_get (cdb, sdb_fmt (0, "%d", idx), 0); } return -1; } static char *getname(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods return dex_method_fullname (dex, idx); case 'c': // classes return dex_class_name_byid (dex, idx); case 'f': // fields return dex_field_name (dex, idx); } return NULL; } static RList *sections(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; RList *ml = methods (arch); RBinSection *ptr = NULL; int ns, fsymsz = 0; RList *ret = NULL; RListIter *iter; RBinSymbol *m; int fsym = 0; r_list_foreach (ml, iter, m) { if (!fsym || m->paddr < fsym) { fsym = m->paddr; } ns = m->paddr + m->size; if (ns > arch->buf->length) { continue; } if (ns > fsymsz) { fsymsz = ns; } } if (!fsym) { return NULL; } if (!(ret = r_list_new ())) { return NULL; } ret->free = free; if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "header"); ptr->size = ptr->vsize = sizeof (struct dex_header_t); ptr->paddr= ptr->vaddr = 0; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "constpool"); //ptr->size = ptr->vsize = fsym; ptr->paddr= ptr->vaddr = sizeof (struct dex_header_t); ptr->size = bin->code_from - ptr->vaddr; // fix size ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "code"); ptr->vaddr = ptr->paddr = bin->code_from; //ptr->vaddr = fsym; ptr->size = bin->code_to - ptr->paddr; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { //ut64 sz = arch ? r_buf_size (arch->buf): 0; strcpy (ptr->name, "data"); ptr->paddr = ptr->vaddr = fsymsz+fsym; if (ptr->vaddr > arch->buf->length) { ptr->paddr = ptr->vaddr = bin->code_to; ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; } else { ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; // hacky workaround //dprintf ("Hack\n"); //ptr->size = ptr->vsize = 1024; } ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; //|2; ptr->add = true; r_list_append (ret, ptr); } return ret; } static void header(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; struct r_bin_t *rbin = arch->rbin; rbin->cb_printf ("DEX file header:\n"); rbin->cb_printf ("magic : 'dex\\n035\\0'\n"); rbin->cb_printf ("checksum : %x\n", bin->header.checksum); rbin->cb_printf ("signature : %02x%02x...%02x%02x\n", bin->header.signature[0], bin->header.signature[1], bin->header.signature[18], bin->header.signature[19]); rbin->cb_printf ("file_size : %d\n", bin->header.size); rbin->cb_printf ("header_size : %d\n", bin->header.header_size); rbin->cb_printf ("link_size : %d\n", bin->header.linksection_size); rbin->cb_printf ("link_off : %d (0x%06x)\n", bin->header.linksection_offset, bin->header.linksection_offset); rbin->cb_printf ("string_ids_size : %d\n", bin->header.strings_size); rbin->cb_printf ("string_ids_off : %d (0x%06x)\n", bin->header.strings_offset, bin->header.strings_offset); rbin->cb_printf ("type_ids_size : %d\n", bin->header.types_size); rbin->cb_printf ("type_ids_off : %d (0x%06x)\n", bin->header.types_offset, bin->header.types_offset); rbin->cb_printf ("proto_ids_size : %d\n", bin->header.prototypes_size); rbin->cb_printf ("proto_ids_off : %d (0x%06x)\n", bin->header.prototypes_offset, bin->header.prototypes_offset); rbin->cb_printf ("field_ids_size : %d\n", bin->header.fields_size); rbin->cb_printf ("field_ids_off : %d (0x%06x)\n", bin->header.fields_offset, bin->header.fields_offset); rbin->cb_printf ("method_ids_size : %d\n", bin->header.method_size); rbin->cb_printf ("method_ids_off : %d (0x%06x)\n", bin->header.method_offset, bin->header.method_offset); rbin->cb_printf ("class_defs_size : %d\n", bin->header.class_size); rbin->cb_printf ("class_defs_off : %d (0x%06x)\n", bin->header.class_offset, bin->header.class_offset); rbin->cb_printf ("data_size : %d\n", bin->header.data_size); rbin->cb_printf ("data_off : %d (0x%06x)\n\n", bin->header.data_offset, bin->header.data_offset); // TODO: print information stored in the RBIN not this ugly fix dexdump = true; bin->methods_list = NULL; dex_loadcode (arch, bin); dexdump = false; } static ut64 size(RBinFile *arch) { int ret; ut32 off = 0, len = 0; ut8 u32s[sizeof (ut32)] = {0}; ret = r_buf_read_at (arch->buf, 108, u32s, 4); if (ret != 4) { return 0; } off = r_read_le32 (u32s); ret = r_buf_read_at (arch->buf, 104, u32s, 4); if (ret != 4) { return 0; } len = r_read_le32 (u32s); return off + len; } RBinPlugin r_bin_plugin_dex = { .name = "dex", .desc = "dex format bin plugin", .license = "LGPL3", .get_sdb = &get_sdb, .load = &load, .load_bytes = &load_bytes, .check = &check, .check_bytes = &check_bytes, .baddr = &baddr, .entries = entries, .classes = classes, .sections = sections, .symbols = methods, .imports = imports, .strings = strings, .info = &info, .header = &header, .size = &size, .get_offset = &getoffset, .get_name = &getname, .dbginfo = &r_bin_dbginfo_dex, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_BIN, .data = &r_bin_plugin_dex, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-476/c/good_3164_1
crossvul-cpp_data_bad_3256_3
/* * key management facility for FS encryption support. * * Copyright (C) 2015, Google, Inc. * * This contains encryption key functions. * * Written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar, 2015. */ #include <keys/user-type.h> #include <linux/scatterlist.h> #include "fscrypt_private.h" static void derive_crypt_complete(struct crypto_async_request *req, int rc) { struct fscrypt_completion_result *ecr = req->data; if (rc == -EINPROGRESS) return; ecr->res = rc; complete(&ecr->completion); } /** * derive_key_aes() - Derive a key using AES-128-ECB * @deriving_key: Encryption key used for derivation. * @source_key: Source key to which to apply derivation. * @derived_key: Derived key. * * Return: Zero on success; non-zero otherwise. */ static int derive_key_aes(u8 deriving_key[FS_AES_128_ECB_KEY_SIZE], u8 source_key[FS_AES_256_XTS_KEY_SIZE], u8 derived_key[FS_AES_256_XTS_KEY_SIZE]) { int res = 0; struct skcipher_request *req = NULL; DECLARE_FS_COMPLETION_RESULT(ecr); struct scatterlist src_sg, dst_sg; struct crypto_skcipher *tfm = crypto_alloc_skcipher("ecb(aes)", 0, 0); if (IS_ERR(tfm)) { res = PTR_ERR(tfm); tfm = NULL; goto out; } crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_WEAK_KEY); req = skcipher_request_alloc(tfm, GFP_NOFS); if (!req) { res = -ENOMEM; goto out; } skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP, derive_crypt_complete, &ecr); res = crypto_skcipher_setkey(tfm, deriving_key, FS_AES_128_ECB_KEY_SIZE); if (res < 0) goto out; sg_init_one(&src_sg, source_key, FS_AES_256_XTS_KEY_SIZE); sg_init_one(&dst_sg, derived_key, FS_AES_256_XTS_KEY_SIZE); skcipher_request_set_crypt(req, &src_sg, &dst_sg, FS_AES_256_XTS_KEY_SIZE, NULL); res = crypto_skcipher_encrypt(req); if (res == -EINPROGRESS || res == -EBUSY) { wait_for_completion(&ecr.completion); res = ecr.res; } out: skcipher_request_free(req); crypto_free_skcipher(tfm); return res; } static int validate_user_key(struct fscrypt_info *crypt_info, struct fscrypt_context *ctx, u8 *raw_key, const char *prefix) { char *description; struct key *keyring_key; struct fscrypt_key *master_key; const struct user_key_payload *ukp; int res; description = kasprintf(GFP_NOFS, "%s%*phN", prefix, FS_KEY_DESCRIPTOR_SIZE, ctx->master_key_descriptor); if (!description) return -ENOMEM; keyring_key = request_key(&key_type_logon, description, NULL); kfree(description); if (IS_ERR(keyring_key)) return PTR_ERR(keyring_key); if (keyring_key->type != &key_type_logon) { printk_once(KERN_WARNING "%s: key type must be logon\n", __func__); res = -ENOKEY; goto out; } down_read(&keyring_key->sem); ukp = user_key_payload(keyring_key); if (ukp->datalen != sizeof(struct fscrypt_key)) { res = -EINVAL; up_read(&keyring_key->sem); goto out; } master_key = (struct fscrypt_key *)ukp->data; BUILD_BUG_ON(FS_AES_128_ECB_KEY_SIZE != FS_KEY_DERIVATION_NONCE_SIZE); if (master_key->size != FS_AES_256_XTS_KEY_SIZE) { printk_once(KERN_WARNING "%s: key size incorrect: %d\n", __func__, master_key->size); res = -ENOKEY; up_read(&keyring_key->sem); goto out; } res = derive_key_aes(ctx->nonce, master_key->raw, raw_key); up_read(&keyring_key->sem); if (res) goto out; crypt_info->ci_keyring_key = keyring_key; return 0; out: key_put(keyring_key); return res; } static int determine_cipher_type(struct fscrypt_info *ci, struct inode *inode, const char **cipher_str_ret, int *keysize_ret) { if (S_ISREG(inode->i_mode)) { if (ci->ci_data_mode == FS_ENCRYPTION_MODE_AES_256_XTS) { *cipher_str_ret = "xts(aes)"; *keysize_ret = FS_AES_256_XTS_KEY_SIZE; return 0; } pr_warn_once("fscrypto: unsupported contents encryption mode " "%d for inode %lu\n", ci->ci_data_mode, inode->i_ino); return -ENOKEY; } if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) { if (ci->ci_filename_mode == FS_ENCRYPTION_MODE_AES_256_CTS) { *cipher_str_ret = "cts(cbc(aes))"; *keysize_ret = FS_AES_256_CTS_KEY_SIZE; return 0; } pr_warn_once("fscrypto: unsupported filenames encryption mode " "%d for inode %lu\n", ci->ci_filename_mode, inode->i_ino); return -ENOKEY; } pr_warn_once("fscrypto: unsupported file type %d for inode %lu\n", (inode->i_mode & S_IFMT), inode->i_ino); return -ENOKEY; } static void put_crypt_info(struct fscrypt_info *ci) { if (!ci) return; key_put(ci->ci_keyring_key); crypto_free_skcipher(ci->ci_ctfm); kmem_cache_free(fscrypt_info_cachep, ci); } int fscrypt_get_crypt_info(struct inode *inode) { struct fscrypt_info *crypt_info; struct fscrypt_context ctx; struct crypto_skcipher *ctfm; const char *cipher_str; int keysize; u8 *raw_key = NULL; int res; res = fscrypt_initialize(inode->i_sb->s_cop->flags); if (res) return res; if (!inode->i_sb->s_cop->get_context) return -EOPNOTSUPP; retry: crypt_info = ACCESS_ONCE(inode->i_crypt_info); if (crypt_info) { if (!crypt_info->ci_keyring_key || key_validate(crypt_info->ci_keyring_key) == 0) return 0; fscrypt_put_encryption_info(inode, crypt_info); goto retry; } res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx)); if (res < 0) { if (!fscrypt_dummy_context_enabled(inode) || inode->i_sb->s_cop->is_encrypted(inode)) return res; /* Fake up a context for an unencrypted directory */ memset(&ctx, 0, sizeof(ctx)); ctx.format = FS_ENCRYPTION_CONTEXT_FORMAT_V1; ctx.contents_encryption_mode = FS_ENCRYPTION_MODE_AES_256_XTS; ctx.filenames_encryption_mode = FS_ENCRYPTION_MODE_AES_256_CTS; memset(ctx.master_key_descriptor, 0x42, FS_KEY_DESCRIPTOR_SIZE); } else if (res != sizeof(ctx)) { return -EINVAL; } if (ctx.format != FS_ENCRYPTION_CONTEXT_FORMAT_V1) return -EINVAL; if (ctx.flags & ~FS_POLICY_FLAGS_VALID) return -EINVAL; crypt_info = kmem_cache_alloc(fscrypt_info_cachep, GFP_NOFS); if (!crypt_info) return -ENOMEM; crypt_info->ci_flags = ctx.flags; crypt_info->ci_data_mode = ctx.contents_encryption_mode; crypt_info->ci_filename_mode = ctx.filenames_encryption_mode; crypt_info->ci_ctfm = NULL; crypt_info->ci_keyring_key = NULL; memcpy(crypt_info->ci_master_key, ctx.master_key_descriptor, sizeof(crypt_info->ci_master_key)); res = determine_cipher_type(crypt_info, inode, &cipher_str, &keysize); if (res) goto out; /* * This cannot be a stack buffer because it is passed to the scatterlist * crypto API as part of key derivation. */ res = -ENOMEM; raw_key = kmalloc(FS_MAX_KEY_SIZE, GFP_NOFS); if (!raw_key) goto out; res = validate_user_key(crypt_info, &ctx, raw_key, FS_KEY_DESC_PREFIX); if (res && inode->i_sb->s_cop->key_prefix) { int res2 = validate_user_key(crypt_info, &ctx, raw_key, inode->i_sb->s_cop->key_prefix); if (res2) { if (res2 == -ENOKEY) res = -ENOKEY; goto out; } } else if (res) { goto out; } ctfm = crypto_alloc_skcipher(cipher_str, 0, 0); if (!ctfm || IS_ERR(ctfm)) { res = ctfm ? PTR_ERR(ctfm) : -ENOMEM; printk(KERN_DEBUG "%s: error %d (inode %u) allocating crypto tfm\n", __func__, res, (unsigned) inode->i_ino); goto out; } crypt_info->ci_ctfm = ctfm; crypto_skcipher_clear_flags(ctfm, ~0); crypto_skcipher_set_flags(ctfm, CRYPTO_TFM_REQ_WEAK_KEY); res = crypto_skcipher_setkey(ctfm, raw_key, keysize); if (res) goto out; kzfree(raw_key); raw_key = NULL; if (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) != NULL) { put_crypt_info(crypt_info); goto retry; } return 0; out: if (res == -ENOKEY) res = 0; put_crypt_info(crypt_info); kzfree(raw_key); return res; } void fscrypt_put_encryption_info(struct inode *inode, struct fscrypt_info *ci) { struct fscrypt_info *prev; if (ci == NULL) ci = ACCESS_ONCE(inode->i_crypt_info); if (ci == NULL) return; prev = cmpxchg(&inode->i_crypt_info, ci, NULL); if (prev != ci) return; put_crypt_info(ci); } EXPORT_SYMBOL(fscrypt_put_encryption_info); int fscrypt_get_encryption_info(struct inode *inode) { struct fscrypt_info *ci = inode->i_crypt_info; if (!ci || (ci->ci_keyring_key && (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_DEAD))))) return fscrypt_get_crypt_info(inode); return 0; } EXPORT_SYMBOL(fscrypt_get_encryption_info);
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3256_3
crossvul-cpp_data_bad_4808_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; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } 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/bad_4808_0
crossvul-cpp_data_good_3060_11
/* * Copyright (C) 2010 IBM Corporation * Copyright (C) 2010 Politecnico di Torino, Italy * TORSEC group -- http://security.polito.it * * Authors: * Mimi Zohar <zohar@us.ibm.com> * Roberto Sassu <roberto.sassu@polito.it> * * 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 <keys/encrypted-type.h> #include <linux/key-type.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/scatterlist.h> #include <linux/crypto.h> #include <linux/ctype.h> #include <crypto/hash.h> #include <crypto/sha.h> #include <crypto/aes.h> #include "encrypted.h" #include "ecryptfs_format.h" static const char KEY_TRUSTED_PREFIX[] = "trusted:"; static const char KEY_USER_PREFIX[] = "user:"; static const char hash_alg[] = "sha256"; static const char hmac_alg[] = "hmac(sha256)"; static const char blkcipher_alg[] = "cbc(aes)"; static const char key_format_default[] = "default"; static const char key_format_ecryptfs[] = "ecryptfs"; static unsigned int ivsize; static int blksize; #define KEY_TRUSTED_PREFIX_LEN (sizeof (KEY_TRUSTED_PREFIX) - 1) #define KEY_USER_PREFIX_LEN (sizeof (KEY_USER_PREFIX) - 1) #define KEY_ECRYPTFS_DESC_LEN 16 #define HASH_SIZE SHA256_DIGEST_SIZE #define MAX_DATA_SIZE 4096 #define MIN_DATA_SIZE 20 struct sdesc { struct shash_desc shash; char ctx[]; }; static struct crypto_shash *hashalg; static struct crypto_shash *hmacalg; enum { Opt_err = -1, Opt_new, Opt_load, Opt_update }; enum { Opt_error = -1, Opt_default, Opt_ecryptfs }; static const match_table_t key_format_tokens = { {Opt_default, "default"}, {Opt_ecryptfs, "ecryptfs"}, {Opt_error, NULL} }; static const match_table_t key_tokens = { {Opt_new, "new"}, {Opt_load, "load"}, {Opt_update, "update"}, {Opt_err, NULL} }; static int aes_get_sizes(void) { struct crypto_blkcipher *tfm; tfm = crypto_alloc_blkcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm)) { pr_err("encrypted_key: failed to alloc_cipher (%ld)\n", PTR_ERR(tfm)); return PTR_ERR(tfm); } ivsize = crypto_blkcipher_ivsize(tfm); blksize = crypto_blkcipher_blocksize(tfm); crypto_free_blkcipher(tfm); return 0; } /* * valid_ecryptfs_desc - verify the description of a new/loaded encrypted key * * The description of a encrypted key with format 'ecryptfs' must contain * exactly 16 hexadecimal characters. * */ static int valid_ecryptfs_desc(const char *ecryptfs_desc) { int i; if (strlen(ecryptfs_desc) != KEY_ECRYPTFS_DESC_LEN) { pr_err("encrypted_key: key description must be %d hexadecimal " "characters long\n", KEY_ECRYPTFS_DESC_LEN); return -EINVAL; } for (i = 0; i < KEY_ECRYPTFS_DESC_LEN; i++) { if (!isxdigit(ecryptfs_desc[i])) { pr_err("encrypted_key: key description must contain " "only hexadecimal characters\n"); return -EINVAL; } } return 0; } /* * valid_master_desc - verify the 'key-type:desc' of a new/updated master-key * * key-type:= "trusted:" | "user:" * desc:= master-key description * * Verify that 'key-type' is valid and that 'desc' exists. On key update, * only the master key description is permitted to change, not the key-type. * The key-type remains constant. * * On success returns 0, otherwise -EINVAL. */ static int valid_master_desc(const char *new_desc, const char *orig_desc) { if (!memcmp(new_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN)) { if (strlen(new_desc) == KEY_TRUSTED_PREFIX_LEN) goto out; if (orig_desc) if (memcmp(new_desc, orig_desc, KEY_TRUSTED_PREFIX_LEN)) goto out; } else if (!memcmp(new_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN)) { if (strlen(new_desc) == KEY_USER_PREFIX_LEN) goto out; if (orig_desc) if (memcmp(new_desc, orig_desc, KEY_USER_PREFIX_LEN)) goto out; } else goto out; return 0; out: return -EINVAL; } /* * datablob_parse - parse the keyctl data * * datablob format: * new [<format>] <master-key name> <decrypted data length> * load [<format>] <master-key name> <decrypted data length> * <encrypted iv + data> * update <new-master-key name> * * Tokenizes a copy of the keyctl data, returning a pointer to each token, * which is null terminated. * * On success returns 0, otherwise -EINVAL. */ static int datablob_parse(char *datablob, const char **format, char **master_desc, char **decrypted_datalen, char **hex_encoded_iv) { substring_t args[MAX_OPT_ARGS]; int ret = -EINVAL; int key_cmd; int key_format; char *p, *keyword; keyword = strsep(&datablob, " \t"); if (!keyword) { pr_info("encrypted_key: insufficient parameters specified\n"); return ret; } key_cmd = match_token(keyword, key_tokens, args); /* Get optional format: default | ecryptfs */ p = strsep(&datablob, " \t"); if (!p) { pr_err("encrypted_key: insufficient parameters specified\n"); return ret; } key_format = match_token(p, key_format_tokens, args); switch (key_format) { case Opt_ecryptfs: case Opt_default: *format = p; *master_desc = strsep(&datablob, " \t"); break; case Opt_error: *master_desc = p; break; } if (!*master_desc) { pr_info("encrypted_key: master key parameter is missing\n"); goto out; } if (valid_master_desc(*master_desc, NULL) < 0) { pr_info("encrypted_key: master key parameter \'%s\' " "is invalid\n", *master_desc); goto out; } if (decrypted_datalen) { *decrypted_datalen = strsep(&datablob, " \t"); if (!*decrypted_datalen) { pr_info("encrypted_key: keylen parameter is missing\n"); goto out; } } switch (key_cmd) { case Opt_new: if (!decrypted_datalen) { pr_info("encrypted_key: keyword \'%s\' not allowed " "when called from .update method\n", keyword); break; } ret = 0; break; case Opt_load: if (!decrypted_datalen) { pr_info("encrypted_key: keyword \'%s\' not allowed " "when called from .update method\n", keyword); break; } *hex_encoded_iv = strsep(&datablob, " \t"); if (!*hex_encoded_iv) { pr_info("encrypted_key: hex blob is missing\n"); break; } ret = 0; break; case Opt_update: if (decrypted_datalen) { pr_info("encrypted_key: keyword \'%s\' not allowed " "when called from .instantiate method\n", keyword); break; } ret = 0; break; case Opt_err: pr_info("encrypted_key: keyword \'%s\' not recognized\n", keyword); break; } out: return ret; } /* * datablob_format - format as an ascii string, before copying to userspace */ static char *datablob_format(struct encrypted_key_payload *epayload, size_t asciiblob_len) { char *ascii_buf, *bufp; u8 *iv = epayload->iv; int len; int i; ascii_buf = kmalloc(asciiblob_len + 1, GFP_KERNEL); if (!ascii_buf) goto out; ascii_buf[asciiblob_len] = '\0'; /* copy datablob master_desc and datalen strings */ len = sprintf(ascii_buf, "%s %s %s ", epayload->format, epayload->master_desc, epayload->datalen); /* convert the hex encoded iv, encrypted-data and HMAC to ascii */ bufp = &ascii_buf[len]; for (i = 0; i < (asciiblob_len - len) / 2; i++) bufp = hex_byte_pack(bufp, iv[i]); out: return ascii_buf; } /* * request_user_key - request the user key * * Use a user provided key to encrypt/decrypt an encrypted-key. */ static struct key *request_user_key(const char *master_desc, u8 **master_key, size_t *master_keylen) { struct user_key_payload *upayload; struct key *ukey; ukey = request_key(&key_type_user, master_desc, NULL); if (IS_ERR(ukey)) goto error; down_read(&ukey->sem); upayload = ukey->payload.data; *master_key = upayload->data; *master_keylen = upayload->datalen; error: return ukey; } static struct sdesc *alloc_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 calc_hmac(u8 *digest, const u8 *key, unsigned int keylen, const u8 *buf, unsigned int buflen) { struct sdesc *sdesc; int ret; sdesc = alloc_sdesc(hmacalg); if (IS_ERR(sdesc)) { pr_info("encrypted_key: can't alloc %s\n", hmac_alg); return PTR_ERR(sdesc); } ret = crypto_shash_setkey(hmacalg, key, keylen); if (!ret) ret = crypto_shash_digest(&sdesc->shash, buf, buflen, digest); kfree(sdesc); return ret; } static int calc_hash(u8 *digest, const u8 *buf, unsigned int buflen) { struct sdesc *sdesc; int ret; sdesc = alloc_sdesc(hashalg); if (IS_ERR(sdesc)) { pr_info("encrypted_key: can't alloc %s\n", hash_alg); return PTR_ERR(sdesc); } ret = crypto_shash_digest(&sdesc->shash, buf, buflen, digest); kfree(sdesc); return ret; } enum derived_key_type { ENC_KEY, AUTH_KEY }; /* Derive authentication/encryption key from trusted key */ static int get_derived_key(u8 *derived_key, enum derived_key_type key_type, const u8 *master_key, size_t master_keylen) { u8 *derived_buf; unsigned int derived_buf_len; int ret; derived_buf_len = strlen("AUTH_KEY") + 1 + master_keylen; if (derived_buf_len < HASH_SIZE) derived_buf_len = HASH_SIZE; derived_buf = kzalloc(derived_buf_len, GFP_KERNEL); if (!derived_buf) { pr_err("encrypted_key: out of memory\n"); return -ENOMEM; } if (key_type) strcpy(derived_buf, "AUTH_KEY"); else strcpy(derived_buf, "ENC_KEY"); memcpy(derived_buf + strlen(derived_buf) + 1, master_key, master_keylen); ret = calc_hash(derived_key, derived_buf, derived_buf_len); kfree(derived_buf); return ret; } static int init_blkcipher_desc(struct blkcipher_desc *desc, const u8 *key, unsigned int key_len, const u8 *iv, unsigned int ivsize) { int ret; desc->tfm = crypto_alloc_blkcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(desc->tfm)) { pr_err("encrypted_key: failed to load %s transform (%ld)\n", blkcipher_alg, PTR_ERR(desc->tfm)); return PTR_ERR(desc->tfm); } desc->flags = 0; ret = crypto_blkcipher_setkey(desc->tfm, key, key_len); if (ret < 0) { pr_err("encrypted_key: failed to setkey (%d)\n", ret); crypto_free_blkcipher(desc->tfm); return ret; } crypto_blkcipher_set_iv(desc->tfm, iv, ivsize); return 0; } static struct key *request_master_key(struct encrypted_key_payload *epayload, u8 **master_key, size_t *master_keylen) { struct key *mkey = NULL; if (!strncmp(epayload->master_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN)) { mkey = request_trusted_key(epayload->master_desc + KEY_TRUSTED_PREFIX_LEN, master_key, master_keylen); } else if (!strncmp(epayload->master_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN)) { mkey = request_user_key(epayload->master_desc + KEY_USER_PREFIX_LEN, master_key, master_keylen); } else goto out; if (IS_ERR(mkey)) { int ret = PTR_ERR(mkey); if (ret == -ENOTSUPP) pr_info("encrypted_key: key %s not supported", epayload->master_desc); else pr_info("encrypted_key: key %s not found", epayload->master_desc); goto out; } dump_master_key(*master_key, *master_keylen); out: return mkey; } /* Before returning data to userspace, encrypt decrypted data. */ static int derived_key_encrypt(struct encrypted_key_payload *epayload, const u8 *derived_key, unsigned int derived_keylen) { struct scatterlist sg_in[2]; struct scatterlist sg_out[1]; struct blkcipher_desc desc; unsigned int encrypted_datalen; unsigned int padlen; char pad[16]; int ret; encrypted_datalen = roundup(epayload->decrypted_datalen, blksize); padlen = encrypted_datalen - epayload->decrypted_datalen; ret = init_blkcipher_desc(&desc, derived_key, derived_keylen, epayload->iv, ivsize); if (ret < 0) goto out; dump_decrypted_data(epayload); memset(pad, 0, sizeof pad); sg_init_table(sg_in, 2); sg_set_buf(&sg_in[0], epayload->decrypted_data, epayload->decrypted_datalen); sg_set_buf(&sg_in[1], pad, padlen); sg_init_table(sg_out, 1); sg_set_buf(sg_out, epayload->encrypted_data, encrypted_datalen); ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in, encrypted_datalen); crypto_free_blkcipher(desc.tfm); if (ret < 0) pr_err("encrypted_key: failed to encrypt (%d)\n", ret); else dump_encrypted_data(epayload, encrypted_datalen); out: return ret; } static int datablob_hmac_append(struct encrypted_key_payload *epayload, const u8 *master_key, size_t master_keylen) { u8 derived_key[HASH_SIZE]; u8 *digest; int ret; ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen); if (ret < 0) goto out; digest = epayload->format + epayload->datablob_len; ret = calc_hmac(digest, derived_key, sizeof derived_key, epayload->format, epayload->datablob_len); if (!ret) dump_hmac(NULL, digest, HASH_SIZE); out: return ret; } /* verify HMAC before decrypting encrypted key */ static int datablob_hmac_verify(struct encrypted_key_payload *epayload, const u8 *format, const u8 *master_key, size_t master_keylen) { u8 derived_key[HASH_SIZE]; u8 digest[HASH_SIZE]; int ret; char *p; unsigned short len; ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen); if (ret < 0) goto out; len = epayload->datablob_len; if (!format) { p = epayload->master_desc; len -= strlen(epayload->format) + 1; } else p = epayload->format; ret = calc_hmac(digest, derived_key, sizeof derived_key, p, len); if (ret < 0) goto out; ret = memcmp(digest, epayload->format + epayload->datablob_len, sizeof digest); if (ret) { ret = -EINVAL; dump_hmac("datablob", epayload->format + epayload->datablob_len, HASH_SIZE); dump_hmac("calc", digest, HASH_SIZE); } out: return ret; } static int derived_key_decrypt(struct encrypted_key_payload *epayload, const u8 *derived_key, unsigned int derived_keylen) { struct scatterlist sg_in[1]; struct scatterlist sg_out[2]; struct blkcipher_desc desc; unsigned int encrypted_datalen; char pad[16]; int ret; encrypted_datalen = roundup(epayload->decrypted_datalen, blksize); ret = init_blkcipher_desc(&desc, derived_key, derived_keylen, epayload->iv, ivsize); if (ret < 0) goto out; dump_encrypted_data(epayload, encrypted_datalen); memset(pad, 0, sizeof pad); sg_init_table(sg_in, 1); sg_init_table(sg_out, 2); sg_set_buf(sg_in, epayload->encrypted_data, encrypted_datalen); sg_set_buf(&sg_out[0], epayload->decrypted_data, epayload->decrypted_datalen); sg_set_buf(&sg_out[1], pad, sizeof pad); ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, encrypted_datalen); crypto_free_blkcipher(desc.tfm); if (ret < 0) goto out; dump_decrypted_data(epayload); out: return ret; } /* Allocate memory for decrypted key and datablob. */ static struct encrypted_key_payload *encrypted_key_alloc(struct key *key, const char *format, const char *master_desc, const char *datalen) { struct encrypted_key_payload *epayload = NULL; unsigned short datablob_len; unsigned short decrypted_datalen; unsigned short payload_datalen; unsigned int encrypted_datalen; unsigned int format_len; long dlen; int ret; ret = kstrtol(datalen, 10, &dlen); if (ret < 0 || dlen < MIN_DATA_SIZE || dlen > MAX_DATA_SIZE) return ERR_PTR(-EINVAL); format_len = (!format) ? strlen(key_format_default) : strlen(format); decrypted_datalen = dlen; payload_datalen = decrypted_datalen; if (format && !strcmp(format, key_format_ecryptfs)) { if (dlen != ECRYPTFS_MAX_KEY_BYTES) { pr_err("encrypted_key: keylen for the ecryptfs format " "must be equal to %d bytes\n", ECRYPTFS_MAX_KEY_BYTES); return ERR_PTR(-EINVAL); } decrypted_datalen = ECRYPTFS_MAX_KEY_BYTES; payload_datalen = sizeof(struct ecryptfs_auth_tok); } encrypted_datalen = roundup(decrypted_datalen, blksize); datablob_len = format_len + 1 + strlen(master_desc) + 1 + strlen(datalen) + 1 + ivsize + 1 + encrypted_datalen; ret = key_payload_reserve(key, payload_datalen + datablob_len + HASH_SIZE + 1); if (ret < 0) return ERR_PTR(ret); epayload = kzalloc(sizeof(*epayload) + payload_datalen + datablob_len + HASH_SIZE + 1, GFP_KERNEL); if (!epayload) return ERR_PTR(-ENOMEM); epayload->payload_datalen = payload_datalen; epayload->decrypted_datalen = decrypted_datalen; epayload->datablob_len = datablob_len; return epayload; } static int encrypted_key_decrypt(struct encrypted_key_payload *epayload, const char *format, const char *hex_encoded_iv) { struct key *mkey; u8 derived_key[HASH_SIZE]; u8 *master_key; u8 *hmac; const char *hex_encoded_data; unsigned int encrypted_datalen; size_t master_keylen; size_t asciilen; int ret; encrypted_datalen = roundup(epayload->decrypted_datalen, blksize); asciilen = (ivsize + 1 + encrypted_datalen + HASH_SIZE) * 2; if (strlen(hex_encoded_iv) != asciilen) return -EINVAL; hex_encoded_data = hex_encoded_iv + (2 * ivsize) + 2; ret = hex2bin(epayload->iv, hex_encoded_iv, ivsize); if (ret < 0) return -EINVAL; ret = hex2bin(epayload->encrypted_data, hex_encoded_data, encrypted_datalen); if (ret < 0) return -EINVAL; hmac = epayload->format + epayload->datablob_len; ret = hex2bin(hmac, hex_encoded_data + (encrypted_datalen * 2), HASH_SIZE); if (ret < 0) return -EINVAL; mkey = request_master_key(epayload, &master_key, &master_keylen); if (IS_ERR(mkey)) return PTR_ERR(mkey); ret = datablob_hmac_verify(epayload, format, master_key, master_keylen); if (ret < 0) { pr_err("encrypted_key: bad hmac (%d)\n", ret); goto out; } ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen); if (ret < 0) goto out; ret = derived_key_decrypt(epayload, derived_key, sizeof derived_key); if (ret < 0) pr_err("encrypted_key: failed to decrypt key (%d)\n", ret); out: up_read(&mkey->sem); key_put(mkey); return ret; } static void __ekey_init(struct encrypted_key_payload *epayload, const char *format, const char *master_desc, const char *datalen) { unsigned int format_len; format_len = (!format) ? strlen(key_format_default) : strlen(format); epayload->format = epayload->payload_data + epayload->payload_datalen; epayload->master_desc = epayload->format + format_len + 1; epayload->datalen = epayload->master_desc + strlen(master_desc) + 1; epayload->iv = epayload->datalen + strlen(datalen) + 1; epayload->encrypted_data = epayload->iv + ivsize + 1; epayload->decrypted_data = epayload->payload_data; if (!format) memcpy(epayload->format, key_format_default, format_len); else { if (!strcmp(format, key_format_ecryptfs)) epayload->decrypted_data = ecryptfs_get_auth_tok_key((struct ecryptfs_auth_tok *)epayload->payload_data); memcpy(epayload->format, format, format_len); } memcpy(epayload->master_desc, master_desc, strlen(master_desc)); memcpy(epayload->datalen, datalen, strlen(datalen)); } /* * encrypted_init - initialize an encrypted key * * For a new key, use a random number for both the iv and data * itself. For an old key, decrypt the hex encoded data. */ static int encrypted_init(struct encrypted_key_payload *epayload, const char *key_desc, const char *format, const char *master_desc, const char *datalen, const char *hex_encoded_iv) { int ret = 0; if (format && !strcmp(format, key_format_ecryptfs)) { ret = valid_ecryptfs_desc(key_desc); if (ret < 0) return ret; ecryptfs_fill_auth_tok((struct ecryptfs_auth_tok *)epayload->payload_data, key_desc); } __ekey_init(epayload, format, master_desc, datalen); if (!hex_encoded_iv) { get_random_bytes(epayload->iv, ivsize); get_random_bytes(epayload->decrypted_data, epayload->decrypted_datalen); } else ret = encrypted_key_decrypt(epayload, format, hex_encoded_iv); return ret; } /* * encrypted_instantiate - instantiate an encrypted key * * Decrypt an existing encrypted datablob or create a new encrypted key * based on a kernel random number. * * On success, return 0. Otherwise return errno. */ static int encrypted_instantiate(struct key *key, struct key_preparsed_payload *prep) { struct encrypted_key_payload *epayload = NULL; char *datablob = NULL; const char *format = NULL; char *master_desc = NULL; char *decrypted_datalen = NULL; char *hex_encoded_iv = NULL; size_t datalen = prep->datalen; int ret; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; datablob[datalen] = 0; memcpy(datablob, prep->data, datalen); ret = datablob_parse(datablob, &format, &master_desc, &decrypted_datalen, &hex_encoded_iv); if (ret < 0) goto out; epayload = encrypted_key_alloc(key, format, master_desc, decrypted_datalen); if (IS_ERR(epayload)) { ret = PTR_ERR(epayload); goto out; } ret = encrypted_init(epayload, key->description, format, master_desc, decrypted_datalen, hex_encoded_iv); if (ret < 0) { kfree(epayload); goto out; } rcu_assign_keypointer(key, epayload); out: kfree(datablob); return ret; } static void encrypted_rcu_free(struct rcu_head *rcu) { struct encrypted_key_payload *epayload; epayload = container_of(rcu, struct encrypted_key_payload, rcu); memset(epayload->decrypted_data, 0, epayload->decrypted_datalen); kfree(epayload); } /* * encrypted_update - update the master key description * * Change the master key description for an existing encrypted key. * The next read will return an encrypted datablob using the new * master key description. * * On success, return 0. Otherwise return errno. */ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep) { struct encrypted_key_payload *epayload = key->payload.data; struct encrypted_key_payload *new_epayload; char *buf; char *new_master_desc = NULL; const char *format = NULL; size_t datalen = prep->datalen; int ret = 0; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; buf = kmalloc(datalen + 1, GFP_KERNEL); if (!buf) return -ENOMEM; buf[datalen] = 0; memcpy(buf, prep->data, datalen); ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL); if (ret < 0) goto out; ret = valid_master_desc(new_master_desc, epayload->master_desc); if (ret < 0) goto out; new_epayload = encrypted_key_alloc(key, epayload->format, new_master_desc, epayload->datalen); if (IS_ERR(new_epayload)) { ret = PTR_ERR(new_epayload); goto out; } __ekey_init(new_epayload, epayload->format, new_master_desc, epayload->datalen); memcpy(new_epayload->iv, epayload->iv, ivsize); memcpy(new_epayload->payload_data, epayload->payload_data, epayload->payload_datalen); rcu_assign_keypointer(key, new_epayload); call_rcu(&epayload->rcu, encrypted_rcu_free); out: kfree(buf); return ret; } /* * encrypted_read - format and copy the encrypted data to userspace * * The resulting datablob format is: * <master-key name> <decrypted data length> <encrypted iv> <encrypted data> * * On success, return to userspace the encrypted key datablob size. */ static long encrypted_read(const struct key *key, char __user *buffer, size_t buflen) { struct encrypted_key_payload *epayload; struct key *mkey; u8 *master_key; size_t master_keylen; char derived_key[HASH_SIZE]; char *ascii_buf; size_t asciiblob_len; int ret; epayload = rcu_dereference_key(key); /* returns the hex encoded iv, encrypted-data, and hmac as ascii */ asciiblob_len = epayload->datablob_len + ivsize + 1 + roundup(epayload->decrypted_datalen, blksize) + (HASH_SIZE * 2); if (!buffer || buflen < asciiblob_len) return asciiblob_len; mkey = request_master_key(epayload, &master_key, &master_keylen); if (IS_ERR(mkey)) return PTR_ERR(mkey); ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen); if (ret < 0) goto out; ret = derived_key_encrypt(epayload, derived_key, sizeof derived_key); if (ret < 0) goto out; ret = datablob_hmac_append(epayload, master_key, master_keylen); if (ret < 0) goto out; ascii_buf = datablob_format(epayload, asciiblob_len); if (!ascii_buf) { ret = -ENOMEM; goto out; } up_read(&mkey->sem); key_put(mkey); if (copy_to_user(buffer, ascii_buf, asciiblob_len) != 0) ret = -EFAULT; kfree(ascii_buf); return asciiblob_len; out: up_read(&mkey->sem); key_put(mkey); return ret; } /* * encrypted_destroy - before freeing the key, clear the decrypted data * * Before freeing the key, clear the memory containing the decrypted * key data. */ static void encrypted_destroy(struct key *key) { struct encrypted_key_payload *epayload = key->payload.data; if (!epayload) return; memset(epayload->decrypted_data, 0, epayload->decrypted_datalen); kfree(key->payload.data); } struct key_type key_type_encrypted = { .name = "encrypted", .instantiate = encrypted_instantiate, .update = encrypted_update, .destroy = encrypted_destroy, .describe = user_describe, .read = encrypted_read, }; EXPORT_SYMBOL_GPL(key_type_encrypted); static void encrypted_shash_release(void) { if (hashalg) crypto_free_shash(hashalg); if (hmacalg) crypto_free_shash(hmacalg); } static int __init encrypted_shash_alloc(void) { int ret; hmacalg = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(hmacalg)) { pr_info("encrypted_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("encrypted_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_encrypted(void) { int ret; ret = encrypted_shash_alloc(); if (ret < 0) return ret; ret = register_key_type(&key_type_encrypted); if (ret < 0) goto out; return aes_get_sizes(); out: encrypted_shash_release(); return ret; } static void __exit cleanup_encrypted(void) { encrypted_shash_release(); unregister_key_type(&key_type_encrypted); } late_initcall(init_encrypted); module_exit(cleanup_encrypted); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-476/c/good_3060_11
crossvul-cpp_data_good_3256_3
/* * key management facility for FS encryption support. * * Copyright (C) 2015, Google, Inc. * * This contains encryption key functions. * * Written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar, 2015. */ #include <keys/user-type.h> #include <linux/scatterlist.h> #include "fscrypt_private.h" static void derive_crypt_complete(struct crypto_async_request *req, int rc) { struct fscrypt_completion_result *ecr = req->data; if (rc == -EINPROGRESS) return; ecr->res = rc; complete(&ecr->completion); } /** * derive_key_aes() - Derive a key using AES-128-ECB * @deriving_key: Encryption key used for derivation. * @source_key: Source key to which to apply derivation. * @derived_key: Derived key. * * Return: Zero on success; non-zero otherwise. */ static int derive_key_aes(u8 deriving_key[FS_AES_128_ECB_KEY_SIZE], u8 source_key[FS_AES_256_XTS_KEY_SIZE], u8 derived_key[FS_AES_256_XTS_KEY_SIZE]) { int res = 0; struct skcipher_request *req = NULL; DECLARE_FS_COMPLETION_RESULT(ecr); struct scatterlist src_sg, dst_sg; struct crypto_skcipher *tfm = crypto_alloc_skcipher("ecb(aes)", 0, 0); if (IS_ERR(tfm)) { res = PTR_ERR(tfm); tfm = NULL; goto out; } crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_WEAK_KEY); req = skcipher_request_alloc(tfm, GFP_NOFS); if (!req) { res = -ENOMEM; goto out; } skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP, derive_crypt_complete, &ecr); res = crypto_skcipher_setkey(tfm, deriving_key, FS_AES_128_ECB_KEY_SIZE); if (res < 0) goto out; sg_init_one(&src_sg, source_key, FS_AES_256_XTS_KEY_SIZE); sg_init_one(&dst_sg, derived_key, FS_AES_256_XTS_KEY_SIZE); skcipher_request_set_crypt(req, &src_sg, &dst_sg, FS_AES_256_XTS_KEY_SIZE, NULL); res = crypto_skcipher_encrypt(req); if (res == -EINPROGRESS || res == -EBUSY) { wait_for_completion(&ecr.completion); res = ecr.res; } out: skcipher_request_free(req); crypto_free_skcipher(tfm); return res; } static int validate_user_key(struct fscrypt_info *crypt_info, struct fscrypt_context *ctx, u8 *raw_key, const char *prefix) { char *description; struct key *keyring_key; struct fscrypt_key *master_key; const struct user_key_payload *ukp; int res; description = kasprintf(GFP_NOFS, "%s%*phN", prefix, FS_KEY_DESCRIPTOR_SIZE, ctx->master_key_descriptor); if (!description) return -ENOMEM; keyring_key = request_key(&key_type_logon, description, NULL); kfree(description); if (IS_ERR(keyring_key)) return PTR_ERR(keyring_key); down_read(&keyring_key->sem); if (keyring_key->type != &key_type_logon) { printk_once(KERN_WARNING "%s: key type must be logon\n", __func__); res = -ENOKEY; goto out; } ukp = user_key_payload(keyring_key); if (ukp->datalen != sizeof(struct fscrypt_key)) { res = -EINVAL; goto out; } master_key = (struct fscrypt_key *)ukp->data; BUILD_BUG_ON(FS_AES_128_ECB_KEY_SIZE != FS_KEY_DERIVATION_NONCE_SIZE); if (master_key->size != FS_AES_256_XTS_KEY_SIZE) { printk_once(KERN_WARNING "%s: key size incorrect: %d\n", __func__, master_key->size); res = -ENOKEY; goto out; } res = derive_key_aes(ctx->nonce, master_key->raw, raw_key); out: up_read(&keyring_key->sem); key_put(keyring_key); return res; } static int determine_cipher_type(struct fscrypt_info *ci, struct inode *inode, const char **cipher_str_ret, int *keysize_ret) { if (S_ISREG(inode->i_mode)) { if (ci->ci_data_mode == FS_ENCRYPTION_MODE_AES_256_XTS) { *cipher_str_ret = "xts(aes)"; *keysize_ret = FS_AES_256_XTS_KEY_SIZE; return 0; } pr_warn_once("fscrypto: unsupported contents encryption mode " "%d for inode %lu\n", ci->ci_data_mode, inode->i_ino); return -ENOKEY; } if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) { if (ci->ci_filename_mode == FS_ENCRYPTION_MODE_AES_256_CTS) { *cipher_str_ret = "cts(cbc(aes))"; *keysize_ret = FS_AES_256_CTS_KEY_SIZE; return 0; } pr_warn_once("fscrypto: unsupported filenames encryption mode " "%d for inode %lu\n", ci->ci_filename_mode, inode->i_ino); return -ENOKEY; } pr_warn_once("fscrypto: unsupported file type %d for inode %lu\n", (inode->i_mode & S_IFMT), inode->i_ino); return -ENOKEY; } static void put_crypt_info(struct fscrypt_info *ci) { if (!ci) return; crypto_free_skcipher(ci->ci_ctfm); kmem_cache_free(fscrypt_info_cachep, ci); } int fscrypt_get_encryption_info(struct inode *inode) { struct fscrypt_info *crypt_info; struct fscrypt_context ctx; struct crypto_skcipher *ctfm; const char *cipher_str; int keysize; u8 *raw_key = NULL; int res; if (inode->i_crypt_info) return 0; res = fscrypt_initialize(inode->i_sb->s_cop->flags); if (res) return res; if (!inode->i_sb->s_cop->get_context) return -EOPNOTSUPP; res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx)); if (res < 0) { if (!fscrypt_dummy_context_enabled(inode) || inode->i_sb->s_cop->is_encrypted(inode)) return res; /* Fake up a context for an unencrypted directory */ memset(&ctx, 0, sizeof(ctx)); ctx.format = FS_ENCRYPTION_CONTEXT_FORMAT_V1; ctx.contents_encryption_mode = FS_ENCRYPTION_MODE_AES_256_XTS; ctx.filenames_encryption_mode = FS_ENCRYPTION_MODE_AES_256_CTS; memset(ctx.master_key_descriptor, 0x42, FS_KEY_DESCRIPTOR_SIZE); } else if (res != sizeof(ctx)) { return -EINVAL; } if (ctx.format != FS_ENCRYPTION_CONTEXT_FORMAT_V1) return -EINVAL; if (ctx.flags & ~FS_POLICY_FLAGS_VALID) return -EINVAL; crypt_info = kmem_cache_alloc(fscrypt_info_cachep, GFP_NOFS); if (!crypt_info) return -ENOMEM; crypt_info->ci_flags = ctx.flags; crypt_info->ci_data_mode = ctx.contents_encryption_mode; crypt_info->ci_filename_mode = ctx.filenames_encryption_mode; crypt_info->ci_ctfm = NULL; memcpy(crypt_info->ci_master_key, ctx.master_key_descriptor, sizeof(crypt_info->ci_master_key)); res = determine_cipher_type(crypt_info, inode, &cipher_str, &keysize); if (res) goto out; /* * This cannot be a stack buffer because it is passed to the scatterlist * crypto API as part of key derivation. */ res = -ENOMEM; raw_key = kmalloc(FS_MAX_KEY_SIZE, GFP_NOFS); if (!raw_key) goto out; res = validate_user_key(crypt_info, &ctx, raw_key, FS_KEY_DESC_PREFIX); if (res && inode->i_sb->s_cop->key_prefix) { int res2 = validate_user_key(crypt_info, &ctx, raw_key, inode->i_sb->s_cop->key_prefix); if (res2) { if (res2 == -ENOKEY) res = -ENOKEY; goto out; } } else if (res) { goto out; } ctfm = crypto_alloc_skcipher(cipher_str, 0, 0); if (!ctfm || IS_ERR(ctfm)) { res = ctfm ? PTR_ERR(ctfm) : -ENOMEM; printk(KERN_DEBUG "%s: error %d (inode %u) allocating crypto tfm\n", __func__, res, (unsigned) inode->i_ino); goto out; } crypt_info->ci_ctfm = ctfm; crypto_skcipher_clear_flags(ctfm, ~0); crypto_skcipher_set_flags(ctfm, CRYPTO_TFM_REQ_WEAK_KEY); res = crypto_skcipher_setkey(ctfm, raw_key, keysize); if (res) goto out; if (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) == NULL) crypt_info = NULL; out: if (res == -ENOKEY) res = 0; put_crypt_info(crypt_info); kzfree(raw_key); return res; } EXPORT_SYMBOL(fscrypt_get_encryption_info); void fscrypt_put_encryption_info(struct inode *inode, struct fscrypt_info *ci) { struct fscrypt_info *prev; if (ci == NULL) ci = ACCESS_ONCE(inode->i_crypt_info); if (ci == NULL) return; prev = cmpxchg(&inode->i_crypt_info, ci, NULL); if (prev != ci) return; put_crypt_info(ci); } EXPORT_SYMBOL(fscrypt_put_encryption_info);
./CrossVul/dataset_final_sorted/CWE-476/c/good_3256_3
crossvul-cpp_data_bad_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, .match = user_match, .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/bad_3060_17
crossvul-cpp_data_good_4058_1
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2011-2012 D. R. Commander * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin * Copyright (C) 2002 RealVNC Ltd. * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #include <stdio.h> #include <string.h> #include <rfb/rfb.h> #include <rfb/rfbregion.h> #include "private.h" #include "rfb/rfbconfig.h" #ifdef LIBVNCSERVER_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef WIN32 #include <io.h> #else #include <pwd.h> #endif #include "sockets.h" #ifdef DEBUGPROTO #undef DEBUGPROTO #define DEBUGPROTO(x) x #else #define DEBUGPROTO(x) #endif #include <stdarg.h> #include "scale.h" /* stst() */ #include <sys/types.h> #include <sys/stat.h> #if LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #ifndef WIN32 /* readdir() */ #include <dirent.h> #endif /* errno */ #include <errno.h> /* strftime() */ #include <time.h> /* INT_MAX */ #include <limits.h> #ifdef LIBVNCSERVER_WITH_WEBSOCKETS #include "rfbssl.h" #endif #ifdef _MSC_VER /* Prevent POSIX deprecation warnings */ #define close _close #define strdup _strdup #endif #ifdef WIN32 #include <direct.h> #ifdef __MINGW32__ #define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */ #else /* MSVC and other windows compilers */ #define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */ #endif /* __MINGW32__ else... */ #ifndef S_ISDIR #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients. This emulates the behavior of the TigerVNC Server. */ static const int tight2turbo_qual[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static const int tight2turbo_subsamp[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; #endif static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); #if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS) void rfbIncrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount++; UNLOCK(cl->refCountMutex); } void rfbDecrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount--; if(cl->refCount<=0) /* just to be sure also < 0 */ TSIGNAL(cl->deleteCond); UNLOCK(cl->refCountMutex); } #else void rfbIncrClientRef(rfbClientPtr cl) {} void rfbDecrClientRef(rfbClientPtr cl) {} #endif #if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS) static MUTEX(rfbClientListMutex); #endif struct rfbClientIterator { rfbClientPtr next; rfbScreenInfoPtr screen; rfbBool closedToo; }; void rfbClientListInit(rfbScreenInfoPtr rfbScreen) { if(sizeof(rfbBool)!=1) { /* a sanity check */ fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool)); /* we cannot continue, because rfbBool is supposed to be char everywhere */ exit(1); } rfbScreen->clientHead = NULL; INIT_MUTEX(rfbClientListMutex); } rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); if(i) { i->next = NULL; i->screen = rfbScreen; i->closedToo = FALSE; } return i; } rfbClientIteratorPtr rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); if(i) { i->next = NULL; i->screen = rfbScreen; i->closedToo = TRUE; } return i; } rfbClientPtr rfbClientIteratorHead(rfbClientIteratorPtr i) { #if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS) if(i->next != 0) { rfbDecrClientRef(i->next); rfbIncrClientRef(i->screen->clientHead); } #endif LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); return i->next; } rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr i) { if (!i) return NULL; if(i->next == 0) { LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); } else { rfbClientPtr cl = i->next; i->next = i->next->next; rfbDecrClientRef(cl); } #if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS) if(!i->closedToo) while(i->next && i->next->sock<0) i->next = i->next->next; if(i->next) rfbIncrClientRef(i->next); #endif return i->next; } void rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { if(iterator && iterator->next) rfbDecrClientRef(iterator->next); free(iterator); } /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen, rfbSocket sock) { rfbNewClient(rfbScreen,sock); } /* * rfbReverseConnection is called to make an outward * connection to a "listening" RFB client. */ rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen, char *host, int port) { rfbSocket sock; rfbClientPtr cl; if ((sock = rfbConnect(rfbScreen, host, port)) < 0) return (rfbClientPtr)NULL; cl = rfbNewClient(rfbScreen, sock); if (cl) { cl->reverseConnection = TRUE; } return cl; } void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_) { /* Permit the server to set the version to report */ /* TODO: sanity checking */ if ((major_==3) && (minor_ > 2 && minor_ < 9)) { rfbScreen->protocolMajorVersion = major_; rfbScreen->protocolMinorVersion = minor_; } else rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_); } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen, rfbSocket sock, rfbBool isUDP) { rfbProtocolVersionMsg pv; rfbClientIteratorPtr iterator; rfbClientPtr cl,cl_; #ifdef LIBVNCSERVER_IPv6 struct sockaddr_storage addr; #else struct sockaddr_in addr; #endif socklen_t addrlen = sizeof(addr); rfbProtocolExtension* extension; cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1); if (!cl) return NULL; cl->screen = rfbScreen; cl->sock = sock; cl->viewOnly = FALSE; /* setup pseudo scaling */ cl->scaledScreen = rfbScreen; cl->scaledScreen->scaledScreenRefCount++; rfbResetStats(cl); cl->clientData = NULL; cl->clientGoneHook = rfbDoNothingWithClient; if(isUDP) { rfbLog(" accepted UDP client\n"); } else { #ifdef LIBVNCSERVER_IPv6 char host[1024]; #endif int one=1; size_t otherClientsCount = 0; getpeername(sock, (struct sockaddr *)&addr, &addrlen); #ifdef LIBVNCSERVER_IPv6 if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { rfbLogPerror("rfbNewClient: error in getnameinfo"); cl->host = strdup(""); } else cl->host = strdup(host); #else cl->host = strdup(inet_ntoa(addr.sin_addr)); #endif iterator = rfbGetClientIterator(rfbScreen); while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) ++otherClientsCount; rfbReleaseClientIterator(iterator); rfbLog(" %lu other clients\n", (unsigned long) otherClientsCount); if(!rfbSetNonBlocking(sock)) { rfbCloseSocket(sock); return NULL; } if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one)) < 0) { rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?"); } FD_SET(sock,&(rfbScreen->allFds)); rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd); INIT_MUTEX(cl->outputMutex); INIT_MUTEX(cl->refCountMutex); INIT_MUTEX(cl->sendMutex); INIT_COND(cl->deleteCond); cl->state = RFB_PROTOCOL_VERSION; cl->reverseConnection = FALSE; cl->readyForSetColourMapEntries = FALSE; cl->useCopyRect = FALSE; cl->preferredEncoding = -1; cl->correMaxWidth = 48; cl->correMaxHeight = 48; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->zrleData = NULL; #endif cl->copyRegion = sraRgnCreate(); cl->copyDX = 0; cl->copyDY = 0; cl->modifiedRegion = sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height); INIT_MUTEX(cl->updateMutex); INIT_COND(cl->updateCond); cl->requestedRegion = sraRgnCreate(); cl->format = cl->screen->serverFormat; cl->translateFn = rfbTranslateNone; cl->translateLookupTable = NULL; LOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS) cl->refCount = 0; #endif cl->next = rfbScreen->clientHead; cl->prev = NULL; if (rfbScreen->clientHead) rfbScreen->clientHead->prev = cl; rfbScreen->clientHead = cl; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; { int i; for (i = 0; i < 4; i++) cl->zsActive[i] = FALSE; } #endif #endif cl->fileTransfer.fd = -1; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; cl->lastKeyboardLedState = -1; cl->cursorX = rfbScreen->cursorX; cl->cursorY = rfbScreen->cursorY; cl->useNewFBSize = FALSE; cl->useExtDesktopSize = FALSE; cl->requestedDesktopSizeChange = 0; cl->lastDesktopSizeChangeError = 0; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->compStreamInited = FALSE; cl->compStream.total_in = 0; cl->compStream.total_out = 0; cl->compStream.zalloc = Z_NULL; cl->compStream.zfree = Z_NULL; cl->compStream.opaque = Z_NULL; cl->zlibCompressLevel = 5; #endif cl->progressiveSliceY = 0; cl->extensions = NULL; cl->lastPtrX = -1; #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD cl->pipe_notify_client_thread[0] = -1; cl->pipe_notify_client_thread[1] = -1; #endif #ifdef LIBVNCSERVER_WITH_WEBSOCKETS /* * Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain) */ if (!webSocketsCheck(cl)) { /* Error reporting handled in webSocketsHandshake */ rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } #endif sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion, rfbScreen->protocolMinorVersion); if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } } for(extension = rfbGetExtensionIterator(); extension; extension=extension->next) { void* data = NULL; /* if the extension does not have a newClient method, it wants * to be initialized later. */ if(extension->newClient && extension->newClient(cl, &data)) rfbEnableExtension(cl, extension, data); } rfbReleaseExtensionIterator(); switch (cl->screen->newClientHook(cl)) { case RFB_CLIENT_ON_HOLD: cl->onHold = TRUE; break; case RFB_CLIENT_ACCEPT: cl->onHold = FALSE; break; case RFB_CLIENT_REFUSE: rfbCloseClient(cl); rfbClientConnectionGone(cl); cl = NULL; break; } return cl; } rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen, rfbSocket sock) { return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE)); } rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen) { return((rfbScreen->udpClient= rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE))); } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { #if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG) int i; #endif LOCK(rfbClientListMutex); if (cl->prev) cl->prev->next = cl->next; else cl->screen->clientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBPTHREAD) || defined(LIBVNCSERVER_HAVE_WIN32THREADS) if(cl->screen->backgroundLoop != FALSE) { int i; do { LOCK(cl->refCountMutex); i=cl->refCount; if(i>0) WAIT(cl->deleteCond,cl->refCountMutex); UNLOCK(cl->refCountMutex); } while(i>0); } #endif if(cl->sock != RFB_INVALID_SOCKET) rfbCloseSocket(cl->sock); if (cl->scaledScreen!=NULL) cl->scaledScreen->scaledScreenRefCount--; #ifdef LIBVNCSERVER_HAVE_LIBZ rfbFreeZrleData(cl); #endif rfbFreeUltraData(cl); /* free buffers holding pixel data before and after encoding */ free(cl->beforeEncBuf); free(cl->afterEncBuf); if(cl->sock != RFB_INVALID_SOCKET) FD_CLR(cl->sock,&(cl->screen->allFds)); cl->clientGoneHook(cl); rfbLog("Client %s gone\n",cl->host); free(cl->host); #ifdef LIBVNCSERVER_HAVE_LIBZ /* Release the compression state structures if any. */ if ( cl->compStreamInited ) { deflateEnd( &(cl->compStream) ); } #ifdef LIBVNCSERVER_HAVE_LIBJPEG for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } #endif #endif if (cl->screen->pointerClient == cl) cl->screen->pointerClient = NULL; sraRgnDestroy(cl->modifiedRegion); sraRgnDestroy(cl->requestedRegion); sraRgnDestroy(cl->copyRegion); if (cl->translateLookupTable) free(cl->translateLookupTable); TINI_COND(cl->updateCond); TINI_MUTEX(cl->updateMutex); /* make sure outputMutex is unlocked before destroying */ LOCK(cl->outputMutex); UNLOCK(cl->outputMutex); TINI_MUTEX(cl->outputMutex); LOCK(cl->sendMutex); UNLOCK(cl->sendMutex); TINI_MUTEX(cl->sendMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD close(cl->pipe_notify_client_thread[0]); close(cl->pipe_notify_client_thread[1]); #endif rfbPrintStats(cl); rfbResetStats(cl); free(cl); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbProcessClientSecurityType(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_INITIALISATION: case RFB_INITIALISATION_SHARED: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major_, minor_; if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) { rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv); rfbCloseClient(cl); return; } rfbLog("Client Protocol Version %d.%d\n", major_, minor_); if (major_ != rfbProtocolMajorVersion) { rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d", cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion, major_,minor_); rfbCloseClient(cl); return; } /* Check for the minor version use either of the two standard version of RFB */ /* * UltraVNC Viewer detects FileTransfer compatible servers via rfb versions * 3.4, 3.6, 3.14, 3.16 * It's a bad method, but it is what they use to enable features... * maintaining RFB version compatibility across multiple servers is a pain * Should use something like ServerIdentity encoding */ cl->protocolMajorVersion = major_; cl->protocolMinorVersion = minor_; rfbLog("Protocol version sent %d.%d, using %d.%d\n", major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion); rfbAuthNewClient(cl); } void rfbClientSendString(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientSendString(\"%s\")\n", reason); buf = (char *)malloc(4 + len); if (buf) { ((uint32_t *)buf)[0] = Swap32IfLE(len); memcpy(buf + 4, reason, len); if (rfbWriteExact(cl, buf, 4 + len) < 0) rfbLogPerror("rfbClientSendString: write"); free(buf); } rfbCloseClient(cl); } /* * rfbClientConnFailed is called when a client connection has failed either * because it talks the wrong protocol or it has failed authentication. */ void rfbClientConnFailed(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientConnFailed(\"%s\")\n", reason); buf = (char *)malloc(8 + len); if (buf) { ((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed); ((uint32_t *)buf)[1] = Swap32IfLE(len); memcpy(buf + 8, reason, len); if (rfbWriteExact(cl, buf, 8 + len) < 0) rfbLogPerror("rfbClientConnFailed: write"); free(buf); } rfbCloseClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; union { char buf[256]; rfbServerInitMsg si; } u; int len, n; rfbClientIteratorPtr iterator; rfbClientPtr otherCl; rfbExtensionData* extension; if (cl->state == RFB_INITIALISATION_SHARED) { /* In this case behave as though an implicit ClientInit message has * already been received with a shared-flag of true. */ ci.shared = 1; /* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED * state to calling software. */ cl->state = RFB_INITIALISATION; } else { if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } } memset(u.buf,0,sizeof(u.buf)); u.si.framebufferWidth = Swap16IfLE(cl->screen->width); u.si.framebufferHeight = Swap16IfLE(cl->screen->height); u.si.format = cl->screen->serverFormat; u.si.format.redMax = Swap16IfLE(u.si.format.redMax); u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax); u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax); strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127); len = strlen(u.buf + sz_rfbServerInitMsg); u.si.nameLength = Swap32IfLE(len); if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } for(extension = cl->extensions; extension;) { rfbExtensionData* next = extension->next; if(extension->extension->init && !extension->extension->init(cl, extension->data)) /* extension requested that it be removed */ rfbDisableExtension(cl, extension->extension); extension = next; } cl->state = RFB_NORMAL; if (!cl->reverseConnection && (cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) { if (cl->screen->dontDisconnect) { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); rfbReleaseClientIterator(iterator); return; } } rfbReleaseClientIterator(iterator); } else { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } rfbReleaseClientIterator(iterator); } } } /* The values come in based on the scaled screen, we need to convert them to * values based on the man screen's coordinate system */ static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h, rfbClientPtr cl) { int x1=Swap16IfLE(*x); int y1=Swap16IfLE(*y); int w1=Swap16IfLE(*w); int h1=Swap16IfLE(*h); rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip"); *x = x1; *y = y1; *w = w1; *h = h1; if(*w>cl->screen->width-*x) *w=cl->screen->width-*x; /* possible underflow */ if(*w>cl->screen->width-*x) return FALSE; if(*h>cl->screen->height-*y) *h=cl->screen->height-*y; if(*h>cl->screen->height-*y) return FALSE; return TRUE; } /* * Send keyboard state (PointerPos pseudo-encoding). */ rfbBool rfbSendKeyboardLedState(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState); rect.r.x = Swap16IfLE(cl->lastKeyboardLedState); rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8))) /* * Send rfbEncodingSupportedMessages. */ rfbBool rfbSendSupportedMessages(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; rfbSupportedMessages msgs; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbSupportedMessages > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(sz_rfbSupportedMessages); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memset((char *)&msgs, 0, sz_rfbSupportedMessages); rfbSetBit(msgs.client2server, rfbSetPixelFormat); rfbSetBit(msgs.client2server, rfbFixColourMapEntries); rfbSetBit(msgs.client2server, rfbSetEncodings); rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest); rfbSetBit(msgs.client2server, rfbKeyEvent); rfbSetBit(msgs.client2server, rfbPointerEvent); rfbSetBit(msgs.client2server, rfbClientCutText); rfbSetBit(msgs.client2server, rfbFileTransfer); rfbSetBit(msgs.client2server, rfbSetScale); /*rfbSetBit(msgs.client2server, rfbSetServerInput); */ /*rfbSetBit(msgs.client2server, rfbSetSW); */ /*rfbSetBit(msgs.client2server, rfbTextChat); */ rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor); rfbSetBit(msgs.server2client, rfbFramebufferUpdate); rfbSetBit(msgs.server2client, rfbSetColourMapEntries); rfbSetBit(msgs.server2client, rfbBell); rfbSetBit(msgs.server2client, rfbServerCutText); rfbSetBit(msgs.server2client, rfbResizeFrameBuffer); rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer); rfbSetBit(msgs.client2server, rfbSetDesktopSize); if (cl->screen->xvpHook) { rfbSetBit(msgs.client2server, rfbXvp); rfbSetBit(msgs.server2client, rfbXvp); } memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages); cl->ublen += sz_rfbSupportedMessages; rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send rfbEncodingSupportedEncodings. */ rfbBool rfbSendSupportedEncodings(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; static uint32_t supported[] = { rfbEncodingRaw, rfbEncodingCopyRect, rfbEncodingRRE, rfbEncodingCoRRE, rfbEncodingHextile, #ifdef LIBVNCSERVER_HAVE_LIBZ rfbEncodingZlib, rfbEncodingZRLE, rfbEncodingZYWRLE, #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG rfbEncodingTight, #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG rfbEncodingTightPng, #endif rfbEncodingUltra, rfbEncodingUltraZip, rfbEncodingXCursor, rfbEncodingRichCursor, rfbEncodingPointerPos, rfbEncodingLastRect, rfbEncodingNewFBSize, rfbEncodingExtDesktopSize, rfbEncodingKeyboardLedState, rfbEncodingSupportedMessages, rfbEncodingSupportedEncodings, rfbEncodingServerIdentity, }; uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i; /* think rfbSetEncodingsMsg */ if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t)); rect.r.h = Swap16IfLE(nEncodings); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; for (i = 0; i < nEncodings; i++) { uint32_t encoding = Swap32IfLE(supported[i]); memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding)); cl->ublen += sizeof(encoding); } rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings, sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)), sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t))); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...) { char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); if (screen->versionString!=NULL) free(screen->versionString); screen->versionString = strdup(buffer); } /* * Send rfbEncodingServerIdentity. */ rfbBool rfbSendServerIdentity(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; char buffer[512]; /* tack on our library version */ snprintf(buffer,sizeof(buffer)-1, "%s (%s)", (cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString), LIBVNCSERVER_PACKAGE_STRING); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (strlen(buffer)+1) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingServerIdentity); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(strlen(buffer)+1); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1); cl->ublen += strlen(buffer)+1; rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send an xvp server message */ rfbBool rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code) { rfbXvpMsg xvp; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) { rfbLogPerror("rfbSendXvp: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg); return TRUE; } rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer) { rfbTextChatMsg tc; int bytesToSend=0; memset((char *)&tc, 0, sizeof(tc)); tc.type = rfbTextChat; tc.length = Swap32IfLE(length); switch(length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: bytesToSend=0; break; default: bytesToSend=length; if (bytesToSend>rfbTextMaxSize) bytesToSend=rfbTextMaxSize; } if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg); cl->ublen += sz_rfbTextChatMsg; if (bytesToSend>0) { memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend); cl->ublen += bytesToSend; } rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \ if ((cl->screen->getFileTransferPermission != NULL \ && cl->screen->getFileTransferPermission(cl) != TRUE) \ || cl->screen->permitFileTransfer != TRUE) { \ rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \ rfbCloseClient(cl); \ return ret; \ } int DB = 1; rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer) { rfbFileTransferMsg ft; ft.type = rfbFileTransfer; ft.contentType = contentType; ft.contentParam = contentParam; ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */ ft.size = Swap32IfLE(size); ft.length = Swap32IfLE(length); FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer); */ LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } if (length>0) { if (rfbWriteExact(cl, buffer, length) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length); return TRUE; } /* * UltraVNC uses Windows Structures */ #define MAX_PATH 260 typedef struct { uint32_t dwLowDateTime; uint32_t dwHighDateTime; } RFB_FILETIME; typedef struct { uint32_t dwFileAttributes; RFB_FILETIME ftCreationTime; RFB_FILETIME ftLastAccessTime; RFB_FILETIME ftLastWriteTime; uint32_t nFileSizeHigh; uint32_t nFileSizeLow; uint32_t dwReserved0; uint32_t dwReserved1; uint8_t cFileName[ MAX_PATH ]; uint8_t cAlternateFileName[ 14 ]; } RFB_FIND_DATA; #define RFB_FILE_ATTRIBUTE_READONLY 0x1 #define RFB_FILE_ATTRIBUTE_HIDDEN 0x2 #define RFB_FILE_ATTRIBUTE_SYSTEM 0x4 #define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10 #define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20 #define RFB_FILE_ATTRIBUTE_NORMAL 0x80 #define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100 #define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800 rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen) { int x; char *home=NULL; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* * Do not use strncpy() - truncating the file name would probably have undesirable side effects * Instead check if destination buffer is big enough */ if (strlen(path) >= unixPathMaxLen) return FALSE; /* C: */ if (path[0]=='C' && path[1]==':') strcpy(unixPath, &path[2]); else { home = getenv("HOME"); if (home!=NULL) { /* Re-check buffer size */ if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen) return FALSE; strcpy(unixPath, home); strcat(unixPath,"/"); strcat(unixPath, path); } else strcpy(unixPath, path); } for (x=0;x<strlen(unixPath);x++) if (unixPath[x]=='\\') unixPath[x]='/'; return TRUE; } rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path) { int x; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); sprintf(path,"C:%s", unixPath); for (x=2;x<strlen(path);x++) if (path[x]=='/') path[x]='\\'; return TRUE; } rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer) { char retfilename[MAX_PATH]; char path[MAX_PATH]; struct stat statbuf; RFB_FIND_DATA win32filename; int nOptLen = 0, retval=0; #ifdef WIN32 WIN32_FIND_DATAA winFindData; HANDLE findHandle; int pathLen, basePathLength; char *basePath; #else DIR *dirp=NULL; struct dirent *direntp=NULL; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* Client thinks we are Winblows */ if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path))) return FALSE; if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path); #ifdef WIN32 // Create a search string, like C:\folder\* pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; // Start a search memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); free(basePath); if (findHandle == INVALID_HANDLE_VALUE) #else dirp=opendir(path); if (dirp==NULL) #endif return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL); /* send back the path name (necessary for links) */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE; #ifdef WIN32 while (findHandle != INVALID_HANDLE_VALUE) #else for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp)) #endif { /* get stats */ #ifdef WIN32 snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName); #else snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name); #endif retval = stat(retfilename, &statbuf); if (retval==0) { memset((char *)&win32filename, 0, sizeof(win32filename)); #ifdef WIN32 win32filename.dwFileAttributes = winFindData.dwFileAttributes; win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime; win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime; win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime; win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime; win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime; win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime; win32filename.nFileSizeLow = winFindData.nFileSizeLow; win32filename.nFileSizeHigh = winFindData.nFileSizeHigh; win32filename.dwReserved0 = winFindData.dwReserved0; win32filename.dwReserved1 = winFindData.dwReserved1; strcpy((char *)win32filename.cFileName, winFindData.cFileName); strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName); #else win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL); if (S_ISDIR(statbuf.st_mode)) win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY); win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */ win32filename.ftCreationTime.dwHighDateTime = 0; win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */ win32filename.ftLastAccessTime.dwHighDateTime = 0; win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */ win32filename.ftLastWriteTime.dwHighDateTime = 0; win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */ win32filename.nFileSizeHigh = 0; win32filename.dwReserved0 = 0; win32filename.dwReserved1 = 0; /* If this had the full path, we would need to translate to DOS format ("C:\") */ /* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */ strcpy((char *)win32filename.cFileName, direntp->d_name); #endif /* Do not show hidden files (but show how to move up the tree) */ if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.')) { nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName); /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName); */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE) { #ifdef WIN32 FindClose(findHandle); #else closedir(dirp); #endif return FALSE; } } } #ifdef WIN32 if (FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } #endif } #ifdef WIN32 if (findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } #else closedir(dirp); #endif /* End of the transfer */ return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL); } char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. We also later pass length to rfbReadExact() that expects a signed int type and that might wrap on platforms with a 32-bit int type if length is bigger than 0X7FFFFFFF. */ if(length == SIZE_MAX || length > INT_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } rfbBool rfbSendFileTransferChunk(rfbClientPtr cl) { /* Allocate buffer for compression */ char readBuf[sz_rfbBlockSize]; int bytesRead=0; int retval=0; fd_set wfds; struct timeval tv; int n; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuf[sz_rfbBlockSize + 1024]; unsigned long nMaxCompSize = sizeof(compBuf); int nRetC = 0; #endif /* * Don't close the client if we get into this one because * it is called from many places to service file transfers. * Note that permitFileTransfer is checked first. */ if (cl->screen->permitFileTransfer != TRUE || (cl->screen->getFileTransferPermission != NULL && cl->screen->getFileTransferPermission(cl) != TRUE)) { return TRUE; } /* If not sending, or no file open... Return as if we sent something! */ if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1)) { FD_ZERO(&wfds); FD_SET(cl->sock, &wfds); /* return immediately */ tv.tv_sec = 0; tv.tv_usec = 0; n = select(cl->sock + 1, NULL, &wfds, NULL, &tv); if (n<0) { #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno)); } /* We have space on the transmit queue */ if (n > 0) { bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize); switch (bytesRead) { case 0: /* rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n"); */ retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; case -1: /* TODO : send an error msg to the client... */ #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno)); retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; default: /* rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead); */ if (!cl->fileTransfer.compressionEnabled) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, readBuf); else { #ifdef LIBVNCSERVER_HAVE_LIBZ nRetC = compress(compBuf, &nMaxCompSize, (unsigned char *)readBuf, bytesRead); /* rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead); */ if ((nRetC==0) && (nMaxCompSize<bytesRead)) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf); else return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, readBuf); #else /* We do not support compression of the data stream */ return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, readBuf); #endif } } } } return TRUE; } rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length) { char *buffer=NULL, *p=NULL; int retval=0; char filename1[MAX_PATH]; char filename2[MAX_PATH]; char szFileTime[MAX_PATH]; struct stat statbuf; uint32_t sizeHtmp=0; int n=0; char timespec[64]; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuff[sz_rfbBlockSize]; unsigned long nRawBytes = sz_rfbBlockSize; int nRet = 0; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length); */ switch (contentType) { case rfbDirContentRequest: switch (contentParam) { case rfbRDrivesList: /* Client requests the List of Local Drives */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n"); */ /* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL> * * We replace the "\" char following the drive letter and ":" * with a char corresponding to the type of drive * We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>" * Isn't it ugly ? * DRIVE_FIXED = 'l' (local?) * DRIVE_REMOVABLE = 'f' (floppy?) * DRIVE_CDROM = 'c' * DRIVE_REMOTE = 'n' */ /* in unix, there are no 'drives' (We could list mount points though) * We fake the root as a "C:" for the Winblows users */ filename2[0]='C'; filename2[1]=':'; filename2[2]='l'; filename2[3]=0; filename2[4]=0; retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2); if (buffer!=NULL) free(buffer); return retval; break; case rfbRDirContent: /* Client requests the content of a directory */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; retval = rfbSendDirContent(cl, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; case rfbDirPacket: rfbLog("rfbProcessFileTransfer() rfbDirPacket\n"); break; case rfbFileAcceptHeader: rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n"); break; case rfbCommandReturn: rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n"); break; case rfbFileChecksums: /* Destination file already exists - the viewer sends the checksums */ rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n"); break; case rfbFileTransferAccess: rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n"); break; /* * sending from the server to the viewer */ case rfbFileTransferRequest: /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n"); */ /* add some space to the end of the buffer as we will be adding a timespec to it */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* The client requests a File */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744); /* */ if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd); if (cl->fileTransfer.fd!=-1) { if (fstat(cl->fileTransfer.fd, &statbuf)!=0) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; } else { /* Add the File Time Stamp to the filename */ strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime)); buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */ if (buffer==NULL) { rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2); return FALSE; } strcat(buffer,","); strcat(buffer, timespec); length = strlen(buffer); if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer); } } /* The viewer supports compression if size==1 */ cl->fileTransfer.compressionEnabled = (size==1); /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":"")); */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer); if (cl->fileTransfer.fd==-1) { if (buffer!=NULL) free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = statbuf.st_size; cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize; cl->fileTransfer.receiving = 0; cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */ /* TODO: finish 64-bit file size support */ sizeHtmp = 0; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) { rfbLogPerror("rfbProcessFileTransfer: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); if (buffer!=NULL) free(buffer); return FALSE; } UNLOCK(cl->sendMutex); break; case rfbFileHeader: /* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */ if (size==-1) { rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n"); close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; return TRUE; } /* rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size); */ /* Starts the transfer! */ cl->fileTransfer.sending=1; return rfbSendFileTransferChunk(cl); break; /* * sending from the viewer to the server */ case rfbFileTransferOffer: /* client is sending a file to us */ /* buffer contains full path name (plus FileTime) */ /* size contains size of the file */ /* rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* Parse the FileTime */ p = strrchr(buffer, ','); if (p!=NULL) { *p = '\0'; strncpy(szFileTime, p+1, sizeof(szFileTime)); szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */ } else szFileTime[0]=0; /* Need to read in sizeHtmp */ if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return FALSE; } sizeHtmp = Swap32IfLE(sizeHtmp); if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; /* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */ /* TODO: Delta Transfer */ cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744); if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd); /* */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer); if (cl->fileTransfer.fd==-1) { free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = size; cl->fileTransfer.numPackets = size / sz_rfbBlockSize; cl->fileTransfer.receiving = 1; cl->fileTransfer.sending = 0; break; case rfbFilePacket: /* rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; if (cl->fileTransfer.fd!=-1) { /* buffer contains the contents of the file */ if (size==0) retval=write(cl->fileTransfer.fd, buffer, length); else { #ifdef LIBVNCSERVER_HAVE_LIBZ /* compressed packet */ nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length); if(nRet == Z_OK) retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes); else retval = -1; #else /* Write the file out as received... */ retval=write(cl->fileTransfer.fd, buffer, length); #endif } if (retval==-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } } break; case rfbEndOfFile: if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n"); /* */ if (cl->fileTransfer.fd!=-1) close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; break; case rfbAbortFileTransfer: if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n"); /* */ if (cl->fileTransfer.fd!=-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } else { /* We use this message for FileTransfer rights (<=RC18 versions) * The client asks for FileTransfer permission */ if (contentParam == 0) { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n"); /* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/ return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, ""); } /* New method is allowed */ if (cl->screen->getFileTransferPermission!=NULL) { if (cl->screen->getFileTransferPermission(cl)==TRUE) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */ } } else { if (cl->screen->permitFileTransfer) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */ } } } break; case rfbCommand: /* rfbLog("rfbProcessFileTransfer() rfbCommand:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; switch (contentParam) { case rfbCDirCreate: /* Client requests the creation of a directory */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; retval = mkdir(filename1, 0755); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success")); /* */ retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileDelete: /* Client requests the deletion of a file */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (stat(filename1,&statbuf)==0) { if (S_ISDIR(statbuf.st_mode)) retval = rmdir(filename1); else retval = unlink(filename1); } else retval=-1; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileRename: /* Client requests the Renaming of a file/directory */ p = strrchr(buffer, '*'); if (p != NULL) { /* Split into 2 filenames ('*' is a seperator) */ *p = '\0'; if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2))) goto fail; retval = rename(filename1,filename2); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success")); /* */ /* Restore the buffer so the reply is good */ *p = '*'; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; } break; } /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return TRUE; fail: if (buffer!=NULL) free(buffer); return FALSE; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n=0; rfbClientToServerMsg msg; char *str; int i; uint32_t enc=0; uint32_t lastPreferredEncoding = -1; char encBuf[64]; char encBuf2[64]; rfbExtDesktopScreen *extDesktopScreens; rfbClientIteratorPtr iterator; rfbClientPtr clp; if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } switch (msg.type) { case rfbSetPixelFormat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE); cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; cl->screen->setTranslateFunction(cl); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); return; case rfbFixColourMapEntries: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); rfbLog("rfbProcessClientNormalMessage: %s", "FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; /* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features... * We may want to look into this... * Example: * case rfbEncodingXCursor: * cl->enableCursorShapeUpdates = TRUE; * * Currently: cl->enableCursorShapeUpdates can *never* be turned off... */ case rfbSetEncodings: { if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4)); /* * UltraVNC Client has the ability to adapt to changing network environments * So, let's give it a change to tell us what it wants now! */ if (cl->preferredEncoding!=-1) lastPreferredEncoding = cl->preferredEncoding; /* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */ cl->preferredEncoding=-1; cl->useCopyRect = FALSE; cl->useNewFBSize = FALSE; cl->useExtDesktopSize = FALSE; cl->cursorWasChanged = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; cl->turboQualityLevel = -1; #endif #endif for (i = 0; i < msg.se.nEncodings; i++) { if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: case rfbEncodingRRE: case rfbEncodingCoRRE: case rfbEncodingHextile: case rfbEncodingUltra: #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: case rfbEncodingZRLE: case rfbEncodingZYWRLE: #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: #endif /* The first supported encoding is the 'preferred' encoding */ if (cl->preferredEncoding == -1) cl->preferredEncoding = enc; break; case rfbEncodingXCursor: if(!cl->screen->dontConvertRichCursorToXCursor) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client " "%s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->useNewFBSize) { rfbLog("Enabling NewFBSize protocol extension for client " "%s\n", cl->host); cl->useNewFBSize = TRUE; } break; case rfbEncodingExtDesktopSize: if (!cl->useExtDesktopSize) { rfbLog("Enabling ExtDesktopSize protocol extension for client " "%s\n", cl->host); cl->useExtDesktopSize = TRUE; cl->useNewFBSize = TRUE; } break; case rfbEncodingKeyboardLedState: if (!cl->enableKeyboardLedState) { rfbLog("Enabling KeyboardLedState protocol extension for client " "%s\n", cl->host); cl->enableKeyboardLedState = TRUE; } break; case rfbEncodingSupportedMessages: if (!cl->enableSupportedMessages) { rfbLog("Enabling SupportedMessages protocol extension for client " "%s\n", cl->host); cl->enableSupportedMessages = TRUE; } break; case rfbEncodingSupportedEncodings: if (!cl->enableSupportedEncodings) { rfbLog("Enabling SupportedEncodings protocol extension for client " "%s\n", cl->host); cl->enableSupportedEncodings = TRUE; } break; case rfbEncodingServerIdentity: if (!cl->enableServerIdentity) { rfbLog("Enabling ServerIdentity protocol extension for client " "%s\n", cl->host); cl->enableServerIdentity = TRUE; } break; case rfbEncodingXvp: if (cl->screen->xvpHook) { rfbLog("Enabling Xvp protocol extension for client " "%s\n", cl->host); if (!rfbSendXvp(cl, 1, rfbXvp_Init)) { rfbCloseClient(cl); return; } } break; default: #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) if ( enc >= (uint32_t)rfbEncodingCompressLevel0 && enc <= (uint32_t)rfbEncodingCompressLevel9 ) { cl->zlibCompressLevel = enc & 0x0F; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = enc & 0x0F; rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); #endif } else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 && enc <= (uint32_t)rfbEncodingQualityLevel9 ) { cl->tightQualityLevel = enc & 0x0F; rfbLog("Using image quality level %d for client %s\n", cl->tightQualityLevel, cl->host); #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F]; cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F]; rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->turboSubsampLevel, cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 && enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) { cl->turboQualityLevel = enc & 0xFF; rfbLog("Using fine quality level %d for client %s\n", cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingSubsamp1X && enc <= (uint32_t)rfbEncodingSubsampGray ) { cl->turboSubsampLevel = enc & 0xFF; rfbLog("Using subsampling level %d for client %s\n", cl->turboSubsampLevel, cl->host); #endif } else #endif { rfbExtensionData* e; for(e = cl->extensions; e;) { rfbExtensionData* next = e->next; if(e->extension->enablePseudoEncoding && e->extension->enablePseudoEncoding(cl, &e->data, (int)enc)) /* ext handles this encoding */ break; e = next; } if(e == NULL) { rfbBool handled = FALSE; /* if the pseudo encoding is not handled by the enabled extensions, search through all extensions. */ rfbProtocolExtension* e; for(e = rfbGetExtensionIterator(); e;) { int* encs = e->pseudoEncodings; while(encs && *encs!=0) { if(*encs==(int)enc) { void* data = NULL; if(!e->enablePseudoEncoding(cl, &data, (int)enc)) { rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc); } else { rfbEnableExtension(cl, e, data); handled = TRUE; e = NULL; break; } } encs++; } if(e) e = e->next; } rfbReleaseExtensionIterator(); if(!handled) rfbLog("rfbProcessClientNormalMessage: " "ignoring unsupported encoding type %s\n", encodingName(enc,encBuf,sizeof(encBuf))); } } } } if (cl->preferredEncoding == -1) { if (lastPreferredEncoding==-1) { cl->preferredEncoding = rfbEncodingRaw; rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { cl->preferredEncoding = lastPreferredEncoding; rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } } else { if (lastPreferredEncoding==-1) { rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { rfbLog("Switching from %s to %s Encoding for client %s\n", encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)), encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host); } } if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } return; } case rfbFramebufferUpdateRequest: { sraRegionPtr tmpRegion; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg); /* The values come in based on the scaled screen, we need to convert them to * values based on the main screen's coordinate system */ if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl)) { rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h); return; } if (cl->clientFramebufferUpdateRequestHook) cl->clientFramebufferUpdateRequestHook(cl, &msg.fur); tmpRegion = sraRgnCreateRect(msg.fur.x, msg.fur.y, msg.fur.x+msg.fur.w, msg.fur.y+msg.fur.h); LOCK(cl->updateMutex); sraRgnOr(cl->requestedRegion,tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { sraRgnDestroy(tmpRegion); TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); return; } } } if (!msg.fur.incremental) { sraRgnOr(cl->modifiedRegion,tmpRegion); sraRgnSubtract(cl->copyRegion,tmpRegion); if (cl->useExtDesktopSize) cl->newFBSizePending = TRUE; } TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); sraRgnDestroy(tmpRegion); return; } case rfbKeyEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg); if(!cl->viewOnly) { cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); } return; case rfbPointerEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg); if (cl->screen->pointerClient && cl->screen->pointerClient != cl) return; if (msg.pe.buttonMask == 0) cl->screen->pointerClient = NULL; else cl->screen->pointerClient = cl; if(!cl->viewOnly) { if (msg.pe.buttonMask != cl->lastPtrButtons || cl->screen->deferPtrUpdateTime == 0) { cl->screen->ptrAddEvent(msg.pe.buttonMask, ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)), ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)), cl); cl->lastPtrButtons = msg.pe.buttonMask; } else { cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)); cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)); cl->lastPtrButtons = msg.pe.buttonMask; } } return; case rfbFileTransfer: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFileTransferMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.ft.size = Swap32IfLE(msg.ft.size); msg.ft.length = Swap32IfLE(msg.ft.length); /* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */ rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length); return; case rfbSetSW: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetSWMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.sw.x = Swap16IfLE(msg.sw.x); msg.sw.y = Swap16IfLE(msg.sw.y); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg); /* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */ rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y); if (cl->screen->setSingleWindow!=NULL) cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y); return; case rfbSetServerInput: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetServerInputMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg); /* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */ /* msg.sim.pad = Swap16IfLE(msg.sim.pad); */ rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status); if (cl->screen->setServerInput!=NULL) cl->screen->setServerInput(cl, msg.sim.status); return; case rfbTextChat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbTextChatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.tc.pad2 = Swap16IfLE(msg.tc.pad2); msg.tc.length = Swap32IfLE(msg.tc.length); switch (msg.tc.length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: /* commands do not have text following */ /* Why couldn't they have used the pad byte??? */ str=NULL; rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg); break; default: if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize)) { str = (char *)malloc(msg.tc.length); if (str==NULL) { rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length); } else { /* This should never happen */ rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize); rfbCloseClient(cl); return; } } /* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished * at which point, the str is NULL (as it is not sent) */ if (cl->screen->setTextChat!=NULL) cl->screen->setTextChat(cl, msg.tc.length, str); free(str); return; case rfbClientCutText: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.cct.length = Swap32IfLE(msg.cct.length); /* uint32_t input is passed to malloc()'s size_t argument, * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int * argument. Here we impose a limit of 1 MB so that the value fits * into all of the types to prevent from misinterpretation and thus * from accessing uninitialized memory (CVE-2018-7225) and also to * prevent from a denial-of-service by allocating too much memory in * the server. */ if (msg.cct.length > 1<<20) { rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length); rfbCloseClient(cl); return; } /* Allow zero-length client cut text. */ str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length); if(!cl->viewOnly) { cl->screen->setXCutText(str, msg.cct.length, cl); } free(str); return; case rfbPalmVNCSetScaleFactor: cl->PalmVNC = TRUE; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbSetScale: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbXvp: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbXvpMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg); /* only version when is defined, so echo back a fail */ if(msg.xvp.version != 1) { rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail); } else { /* if the hook exists and fails, send a fail msg */ if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code)) rfbSendXvp(cl, 1, rfbXvp_Fail); } return; case rfbSetDesktopSize: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.sdm.numberOfScreens == 0) { rfbLog("Ignoring setDesktopSize message from client that defines zero screens\n"); return; } extDesktopScreens = (rfbExtDesktopScreen *) malloc(msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen); if (extDesktopScreens == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, ((char *)extDesktopScreens), msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(extDesktopScreens); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetDesktopSizeMsg + msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen, sz_rfbSetDesktopSizeMsg + msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen); for (i=0; i < msg.sdm.numberOfScreens; i++) { extDesktopScreens[i].id = Swap32IfLE(extDesktopScreens[i].id); extDesktopScreens[i].x = Swap16IfLE(extDesktopScreens[i].x); extDesktopScreens[i].y = Swap16IfLE(extDesktopScreens[i].y); extDesktopScreens[i].width = Swap16IfLE(extDesktopScreens[i].width); extDesktopScreens[i].height = Swap16IfLE(extDesktopScreens[i].height); extDesktopScreens[i].flags = Swap32IfLE(extDesktopScreens[i].flags); } msg.sdm.width = Swap16IfLE(msg.sdm.width); msg.sdm.height = Swap16IfLE(msg.sdm.height); rfbLog("Client requested resolution change to (%dx%d)\n", msg.sdm.width, msg.sdm.height); cl->requestedDesktopSizeChange = rfbExtDesktopSize_ClientRequestedChange; cl->lastDesktopSizeChangeError = cl->screen->setDesktopSizeHook(msg.sdm.width, msg.sdm.height, msg.sdm.numberOfScreens, extDesktopScreens, cl); if (cl->lastDesktopSizeChangeError == 0) { /* Let other clients know it was this client that requested the change */ iterator = rfbGetClientIterator(cl->screen); while ((clp = rfbClientIteratorNext(iterator)) != NULL) { LOCK(clp->updateMutex); if (clp != cl) clp->requestedDesktopSizeChange = rfbExtDesktopSize_OtherClientRequestedChange; UNLOCK(clp->updateMutex); } } else { /* Force ExtendedDesktopSize message to be sent with result code in case of error. (In case of success, it is delayed until the new framebuffer is created) */ cl->newFBSizePending = TRUE; } free(extDesktopScreens); return; default: { rfbExtensionData *e,*next; for(e=cl->extensions; e;) { next = e->next; if(e->extension->handleMessage && e->extension->handleMessage(cl, e->data, &msg)) { rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */ return; } e = next; } rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } } } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. * givenUpdateRegion is not changed. */ rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion,updateCopyRegion,tmpRegion; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool sendKeyboardLedState = FALSE; rfbBool sendSupportedMessages = FALSE; rfbBool sendSupportedEncodings = FALSE; rfbBool sendServerIdentity = FALSE; rfbBool result = TRUE; if(cl->screen->displayHook) cl->screen->displayHook(cl); /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (cl->useExtDesktopSize) { if (!rfbSendExtDesktopSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } } else if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } result = rfbSendUpdateBuf(cl); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (cl->cursorWasChanged && cl->readyForSetColourMapEntries) sendCursorShape = TRUE; } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * Do we plan to send a keyboard state update? */ if ((cl->enableKeyboardLedState) && (cl->screen->getKeyboardLedStateHook!=NULL)) { int x; x=cl->screen->getKeyboardLedStateHook(cl->screen); if (x!=cl->lastKeyboardLedState) { sendKeyboardLedState = TRUE; cl->lastKeyboardLedState=x; } } /* * Do we plan to send a rfbEncodingSupportedMessages? */ if (cl->enableSupportedMessages) { sendSupportedMessages = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedMessages = FALSE; } /* * Do we plan to send a rfbEncodingSupportedEncodings? */ if (cl->enableSupportedEncodings) { sendSupportedEncodings = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedEncodings = FALSE; } /* * Do we plan to send a rfbEncodingServerIdentity? */ if (cl->enableServerIdentity) { sendServerIdentity = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableServerIdentity = FALSE; } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ updateRegion = sraRgnCreateRgn(givenUpdateRegion); if(cl->screen->progressiveSliceHeight>0) { int height=cl->screen->progressiveSliceHeight, y=cl->progressiveSliceY; sraRegionPtr bbox=sraRgnBBox(updateRegion); sraRect rect; if(sraRgnPopRect(bbox,&rect,0)) { sraRegionPtr slice; if(y<rect.y1 || y>=rect.y2) y=rect.y1; slice=sraRgnCreateRect(0,y,cl->screen->width,y+height); sraRgnAnd(updateRegion,slice); sraRgnDestroy(slice); } sraRgnDestroy(bbox); y+=height; if(y>=cl->screen->height) y=0; cl->progressiveSliceY=y; } sraRgnOr(updateRegion,cl->copyRegion); if(!sraRgnAnd(updateRegion,cl->requestedRegion) && sraRgnEmpty(updateRegion) && (cl->enableCursorShapeUpdates || (cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) && !sendCursorShape && !sendCursorPos && !sendKeyboardLedState && !sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) { sraRgnDestroy(updateRegion); UNLOCK(cl->updateMutex); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, TRUE); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); if (!cl->enableCursorShapeUpdates) { if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) { rfbRedrawAfterHideCursor(cl,updateRegion); LOCK(cl->screen->cursorMutex); cl->cursorX = cl->screen->cursorX; cl->cursorY = cl->screen->cursorY; UNLOCK(cl->screen->cursorMutex); rfbRedrawAfterHideCursor(cl,updateRegion); } rfbShowCursor(cl); } /* * Now send the update. */ rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0); if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int rectsPerRow, rows; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); rectsPerRow = (w-1)/cl->correMaxWidth+1; rows = (h-1)/cl->correMaxHeight+1; nUpdateRegionRects += rectsPerRow*rows; } sraRgnReleaseIterator(i); i=NULL; } else if (cl->preferredEncoding == rfbEncodingUltra) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG) } else if (cl->preferredEncoding == rfbEncodingTightPng) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE /* Ultra encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingUltra #ifdef LIBVNCSERVER_HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTightPng #endif && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState + !!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto updateFailed; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto updateFailed; } if (sendKeyboardLedState) { if (!rfbSendKeyboardLedState(cl)) goto updateFailed; } if (sendSupportedMessages) { if (!rfbSendSupportedMessages(cl)) goto updateFailed; } if (sendSupportedEncodings) { if (!rfbSendSupportedEncodings(cl)) goto updateFailed; } if (sendServerIdentity) { if (!rfbSendServerIdentity(cl)) goto updateFailed; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto updateFailed; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); switch (cl->preferredEncoding) { case -1: case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingUltra: if (!rfbSendRectEncodingUltra(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto updateFailed; break; #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)) case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: if (!rfbSendRectEncodingTightPng(cl, x, y, w, h)) goto updateFailed; break; #endif #endif } } if (i) { sraRgnReleaseIterator(i); i = NULL; } if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto updateFailed; if (!rfbSendUpdateBuf(cl)) { updateFailed: result = FALSE; } if (!cl->enableCursorShapeUpdates) { rfbHideCursor(cl); } if(i) sraRgnReleaseIterator(i); sraRgnDestroy(updateRegion); sraRgnDestroy(updateCopyRegion); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ rfbBool rfbSendCopyRegion(rfbClientPtr cl, sraRegionPtr reg, int dx, int dy) { int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; sraRectangleIterator* i; sraRect rect1; /* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */ i = sraRgnGetReverseIterator(reg,dx>0,dy>0); /* correct for the scale of the screen */ dx = ScaleX(cl->screen, cl->scaledScreen, dx); dy = ScaleX(cl->screen, cl->scaledScreen, dy); while(sraRgnIteratorNext(i,&rect1)) { x = rect1.x1; y = rect1.y1; w = rect1.x2 - x; h = rect1.y2 - y; /* correct for scaling (if necessary) */ rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect"); rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect); cl->ublen += sz_rfbCopyRect; rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect, w * h * (cl->scaledScreen->bitsPerPixel / 8)); } sraRgnReleaseIterator(i); return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); if(!h || !w) return TRUE; /* nothing to send */ /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (cl->ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, &cl->updateBuf[cl->ublen], cl->scaledScreen->paddedWidthInBytes, w, nlines); cl->ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; if (nlines == 0) { rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d " "bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ rfbBool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send NewFBSize pseudo-rectangle. This tells the client to change * its framebuffer size. */ rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } if (cl->PalmVNC==TRUE) rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h); else rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h); rect.encoding = Swap32IfLE(rfbEncodingNewFBSize); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send ExtDesktopSize pseudo-rectangle. This message is used: * - to tell the client to change its framebuffer size * - at the start of the session to inform the client we support size changes through setDesktopSize * - in response to setDesktopSize commands to indicate success or failure */ rfbBool rfbSendExtDesktopSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbExtDesktopSizeMsg edsHdr; rfbExtDesktopScreen eds; int i; char *logmsg; int numScreens = cl->screen->numberOfExtDesktopScreensHook(cl); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingExtDesktopSize); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.r.x = Swap16IfLE(cl->requestedDesktopSizeChange); rect.r.y = Swap16IfLE(cl->lastDesktopSizeChangeError); logmsg = ""; if (cl->requestedDesktopSizeChange == rfbExtDesktopSize_ClientRequestedChange) { /* our client requested the resize through setDesktopSize */ switch (cl->lastDesktopSizeChangeError) { case rfbExtDesktopSize_Success: logmsg = "resize successful"; break; case rfbExtDesktopSize_ResizeProhibited: logmsg = "resize prohibited"; break; case rfbExtDesktopSize_OutOfResources: logmsg = "resize failed: out of resources"; break; case rfbExtDesktopSize_InvalidScreenLayout: logmsg = "resize failed: invalid screen layout"; break; default: break; } } cl->requestedDesktopSizeChange = 0; cl->lastDesktopSizeChangeError = 0; rfbLog("Sending rfbEncodingExtDesktopSize for size (%dx%d) %s\n", w, h, logmsg); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; edsHdr.numberOfScreens = numScreens; edsHdr.pad[0] = edsHdr.pad[1] = edsHdr.pad[2] = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&edsHdr, sz_rfbExtDesktopSizeMsg); cl->ublen += sz_rfbExtDesktopSizeMsg; for (i=0; i<numScreens; i++) { if (!cl->screen->getExtDesktopScreenHook(i, &eds, cl)) { rfbErr("Error getting ExtendedDesktopSize information for screen #%d\n", i); return FALSE; } eds.id = Swap32IfLE(eds.id); eds.x = Swap16IfLE(eds.x); eds.y = Swap16IfLE(eds.y); eds.width = Swap16IfLE(eds.width); eds.height = Swap16IfLE(eds.height); eds.flags = Swap32IfLE(eds.flags); memcpy(&cl->updateBuf[cl->ublen], (char *)&eds, sz_rfbExtDesktopScreen); cl->ublen += sz_rfbExtDesktopScreen; } rfbStatRecordEncodingSent(cl, rfbEncodingExtDesktopSize, sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens, sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens); return TRUE; } /* * Send the contents of cl->updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ rfbBool rfbSendUpdateBuf(rfbClientPtr cl) { if(cl->sock<0) return FALSE; if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } cl->ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; char *wbuf = buf; rfbSetColourMapEntriesMsg *scme; uint16_t *rgb; rfbColourMap* cm = &cl->screen->colourMap; int i, len; if (nColours > 256) { /* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */ wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2); } scme = (rfbSetColourMapEntriesMsg *)wbuf; rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]); scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; for (i = 0; i < nColours; i++) { if(i<(int)cm->count) { if(cm->is16) { rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]); rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]); rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]); } else { rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]); rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]); rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]); } } } len += nColours * 3 * 2; LOCK(cl->sendMutex); if (rfbWriteExact(cl, wbuf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); if (wbuf != buf) free(wbuf); UNLOCK(cl->sendMutex); return FALSE; } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len); if (wbuf != buf) free(wbuf); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i; rfbClientPtr cl; rfbBellMsg b; i = rfbGetClientIterator(rfbScreen); while((cl=rfbClientIteratorNext(i))) { b.type = rfbBell; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); } rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg); rfbReleaseClientIterator(i); } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; memset((char *)&sct, 0, sizeof(sct)); iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); continue; } if (rfbWriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len); } rfbReleaseClientIterator(iterator); } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ static unsigned char ptrAcceleration = 50; void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen, rfbSocket sock) { if (write(sock, (char*) &ptrAcceleration, 1) < 0) { rfbLogPerror("rfbNewUDPConnection: write"); } } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen) { int n; rfbClientPtr cl=rfbScreen->udpClient; rfbClientToServerMsg msg; if((!cl) || cl->onHold) return; if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) { rfbLogPerror("rfbProcessUDPInput: read"); } rfbDisconnectUDPSock(rfbScreen); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbErr("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbErr("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->ptrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl); break; default: rfbErr("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(rfbScreen); } }
./CrossVul/dataset_final_sorted/CWE-476/c/good_4058_1
crossvul-cpp_data_good_2561_0
/* misc.c : irssi Copyright (C) 1999 Timo Sirainen 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "module.h" #include "misc.h" #include "commands.h" typedef struct { int condition; GInputFunction function; void *data; } IRSSI_INPUT_REC; static int irssi_io_invoke(GIOChannel *source, GIOCondition condition, void *data) { IRSSI_INPUT_REC *rec = data; int icond = 0; if (condition & (G_IO_ERR | G_IO_HUP | G_IO_NVAL)) { /* error, we have to call the function.. */ if (rec->condition & G_IO_IN) icond |= G_INPUT_READ; else icond |= G_INPUT_WRITE; } if (condition & (G_IO_IN | G_IO_PRI)) icond |= G_INPUT_READ; if (condition & G_IO_OUT) icond |= G_INPUT_WRITE; if (rec->condition & icond) rec->function(rec->data, source, icond); return TRUE; } int g_input_add_full(GIOChannel *source, int priority, int condition, GInputFunction function, void *data) { IRSSI_INPUT_REC *rec; unsigned int result; GIOCondition cond; rec = g_new(IRSSI_INPUT_REC, 1); rec->condition = condition; rec->function = function; rec->data = data; cond = (GIOCondition) (G_IO_ERR|G_IO_HUP|G_IO_NVAL); if (condition & G_INPUT_READ) cond |= G_IO_IN|G_IO_PRI; if (condition & G_INPUT_WRITE) cond |= G_IO_OUT; result = g_io_add_watch_full(source, priority, cond, irssi_io_invoke, rec, g_free); return result; } int g_input_add(GIOChannel *source, int condition, GInputFunction function, void *data) { return g_input_add_full(source, G_PRIORITY_DEFAULT, condition, function, data); } /* easy way to bypass glib polling of io channel internal buffer */ int g_input_add_poll(int fd, int priority, int condition, GInputFunction function, void *data) { GIOChannel *source = g_io_channel_unix_new(fd); int ret = g_input_add_full(source, priority, condition, function, data); g_io_channel_unref(source); return ret; } int g_timeval_cmp(const GTimeVal *tv1, const GTimeVal *tv2) { if (tv1->tv_sec < tv2->tv_sec) return -1; if (tv1->tv_sec > tv2->tv_sec) return 1; return tv1->tv_usec < tv2->tv_usec ? -1 : tv1->tv_usec > tv2->tv_usec ? 1 : 0; } long get_timeval_diff(const GTimeVal *tv1, const GTimeVal *tv2) { long secs, usecs; secs = tv1->tv_sec - tv2->tv_sec; usecs = tv1->tv_usec - tv2->tv_usec; if (usecs < 0) { usecs += 1000000; secs--; } usecs = usecs/1000 + secs * 1000; return usecs; } int find_substr(const char *list, const char *item) { const char *ptr; g_return_val_if_fail(list != NULL, FALSE); g_return_val_if_fail(item != NULL, FALSE); if (*item == '\0') return FALSE; for (;;) { while (i_isspace(*list)) list++; if (*list == '\0') break; ptr = strchr(list, ' '); if (ptr == NULL) ptr = list+strlen(list); if (g_ascii_strncasecmp(list, item, ptr-list) == 0 && item[ptr-list] == '\0') return TRUE; list = ptr; } return FALSE; } int strarray_find(char **array, const char *item) { char **tmp; int index; g_return_val_if_fail(array != NULL, -1); g_return_val_if_fail(item != NULL, -1); index = 0; for (tmp = array; *tmp != NULL; tmp++, index++) { if (g_ascii_strcasecmp(*tmp, item) == 0) return index; } return -1; } GSList *gslist_find_string(GSList *list, const char *key) { for (; list != NULL; list = list->next) if (g_strcmp0(list->data, key) == 0) return list; return NULL; } GSList *gslist_find_icase_string(GSList *list, const char *key) { for (; list != NULL; list = list->next) if (g_ascii_strcasecmp(list->data, key) == 0) return list; return NULL; } void *gslist_foreach_find(GSList *list, FOREACH_FIND_FUNC func, const void *data) { void *ret; while (list != NULL) { ret = func(list->data, (void *) data); if (ret != NULL) return ret; list = list->next; } return NULL; } void gslist_free_full (GSList *list, GDestroyNotify free_func) { GSList *tmp; if (list == NULL) return; for (tmp = list; tmp != NULL; tmp = tmp->next) free_func(tmp->data); g_slist_free(list); } GSList *gslist_remove_string (GSList *list, const char *str) { GSList *l; l = g_slist_find_custom(list, str, (GCompareFunc) g_strcmp0); if (l != NULL) return g_slist_remove_link(list, l); return list; } /* `list' contains pointer to structure with a char* to string. */ char *gslistptr_to_string(GSList *list, int offset, const char *delimiter) { GString *str; char **data, *ret; str = g_string_new(NULL); while (list != NULL) { data = G_STRUCT_MEMBER_P(list->data, offset); if (str->len != 0) g_string_append(str, delimiter); g_string_append(str, *data); list = list->next; } ret = str->str; g_string_free(str, FALSE); return ret; } /* `list' contains char* */ char *gslist_to_string(GSList *list, const char *delimiter) { GString *str; char *ret; str = g_string_new(NULL); while (list != NULL) { if (str->len != 0) g_string_append(str, delimiter); g_string_append(str, list->data); list = list->next; } ret = str->str; g_string_free(str, FALSE); return ret; } void hash_save_key(char *key, void *value, GSList **list) { *list = g_slist_append(*list, key); } /* remove all the options from the optlist hash table that are valid for the * command cmd */ GList *optlist_remove_known(const char *cmd, GHashTable *optlist) { GList *list, *tmp, *next; list = g_hash_table_get_keys(optlist); if (cmd != NULL && list != NULL) { for (tmp = list; tmp != NULL; tmp = next) { char *option = tmp->data; next = tmp->next; if (command_have_option(cmd, option)) list = g_list_remove(list, option); } } return list; } GList *glist_find_string(GList *list, const char *key) { for (; list != NULL; list = list->next) if (g_strcmp0(list->data, key) == 0) return list; return NULL; } GList *glist_find_icase_string(GList *list, const char *key) { for (; list != NULL; list = list->next) if (g_ascii_strcasecmp(list->data, key) == 0) return list; return NULL; } char *stristr(const char *data, const char *key) { const char *max; int keylen, datalen, pos; keylen = strlen(key); datalen = strlen(data); if (keylen > datalen) return NULL; if (keylen == 0) return (char *) data; max = data+datalen-keylen; pos = 0; while (data <= max) { if (key[pos] == '\0') return (char *) data; if (i_toupper(data[pos]) == i_toupper(key[pos])) pos++; else { data++; pos = 0; } } return NULL; } #define isbound(c) \ ((unsigned char) (c) < 128 && \ (i_isspace(c) || i_ispunct(c))) static char *strstr_full_case(const char *data, const char *key, int icase) { const char *start, *max; int keylen, datalen, pos, match; keylen = strlen(key); datalen = strlen(data); if (keylen > datalen) return NULL; if (keylen == 0) return (char *) data; max = data+datalen-keylen; start = data; pos = 0; while (data <= max) { if (key[pos] == '\0') { if (data[pos] != '\0' && !isbound(data[pos])) { data++; pos = 0; continue; } return (char *) data; } match = icase ? (i_toupper(data[pos]) == i_toupper(key[pos])) : data[pos] == key[pos]; if (match && (pos != 0 || data == start || isbound(data[-1]))) pos++; else { data++; pos = 0; } } return NULL; } char *strstr_full(const char *data, const char *key) { return strstr_full_case(data, key, FALSE); } char *stristr_full(const char *data, const char *key) { return strstr_full_case(data, key, TRUE); } /* convert ~/ to $HOME */ char *convert_home(const char *path) { const char *home; if (*path == '~' && (*(path+1) == '/' || *(path+1) == '\0')) { home = g_get_home_dir(); if (home == NULL) home = "."; return g_strconcat(home, path+1, NULL); } else { return g_strdup(path); } } int g_istr_equal(gconstpointer v, gconstpointer v2) { return g_ascii_strcasecmp((const char *) v, (const char *) v2) == 0; } int g_istr_cmp(gconstpointer v, gconstpointer v2) { return g_ascii_strcasecmp((const char *) v, (const char *) v2); } guint g_istr_hash(gconstpointer v) { const signed char *p; guint32 h = 5381; for (p = v; *p != '\0'; p++) h = (h << 5) + h + g_ascii_toupper(*p); return h; } /* Find `mask' from `data', you can use * and ? wildcards. */ int match_wildcards(const char *cmask, const char *data) { char *mask, *newmask, *p1, *p2; int ret; newmask = mask = g_strdup(cmask); for (; *mask != '\0' && *data != '\0'; mask++) { if (*mask != '*') { if (*mask != '?' && i_toupper(*mask) != i_toupper(*data)) break; data++; continue; } while (*mask == '?' || *mask == '*') mask++; if (*mask == '\0') { data += strlen(data); break; } p1 = strchr(mask, '*'); p2 = strchr(mask, '?'); if (p1 == NULL || (p2 < p1 && p2 != NULL)) p1 = p2; if (p1 != NULL) *p1 = '\0'; data = stristr(data, mask); if (data == NULL) break; data += strlen(mask); mask += strlen(mask)-1; if (p1 != NULL) *p1 = p1 == p2 ? '?' : '*'; } while (*mask == '*') mask++; ret = data != NULL && *data == '\0' && *mask == '\0'; g_free(newmask); return ret; } /* Return TRUE if all characters in `str' are numbers. Stop when `end_char' is found from string. */ int is_numeric(const char *str, char end_char) { g_return_val_if_fail(str != NULL, FALSE); if (*str == '\0' || *str == end_char) return FALSE; while (*str != '\0' && *str != end_char) { if (!i_isdigit(*str)) return FALSE; str++; } return TRUE; } /* replace all `from' chars in string to `to' chars. returns `str' */ char *replace_chars(char *str, char from, char to) { char *p; for (p = str; *p != '\0'; p++) { if (*p == from) *p = to; } return str; } int octal2dec(int octal) { int dec, n; dec = 0; n = 1; while (octal != 0) { dec += n*(octal%10); octal /= 10; n *= 8; } return dec; } int dec2octal(int decimal) { int octal, pos; octal = 0; pos = 0; while (decimal > 0) { octal += (decimal & 7)*(pos == 0 ? 1 : pos); decimal /= 8; pos += 10; } return octal; } /* string -> uoff_t */ uoff_t str_to_uofft(const char *str) { #ifdef UOFF_T_LONG_LONG return (uoff_t)strtoull(str, NULL, 10); #else return (uoff_t)strtoul(str, NULL, 10); #endif } /* convert all low-ascii (<32) to ^<A..> combinations */ char *show_lowascii(const char *str) { char *ret, *p; ret = p = g_malloc(strlen(str)*2+1); while (*str != '\0') { if ((unsigned char) *str >= 32) *p++ = *str; else { *p++ = '^'; *p++ = *str + 'A'-1; } str++; } *p = '\0'; return ret; } /* Get time in human readable form with localtime() + asctime() */ char *my_asctime(time_t t) { struct tm *tm; char *str; int len; tm = localtime(&t); if (tm == NULL) return g_strdup("???"); str = g_strdup(asctime(tm)); len = strlen(str); if (len > 0) str[len-1] = '\0'; return str; } /* Returns number of columns needed to print items. save_column_widths is filled with length of each column. */ int get_max_column_count(GSList *items, COLUMN_LEN_FUNC len_func, int max_width, int max_columns, int item_extra, int item_min_size, int **save_column_widths, int *rows) { GSList *tmp; int **columns, *columns_width, *columns_rows; int item_pos, items_count; int ret, len, max_len, n, col; items_count = g_slist_length(items); if (items_count == 0) { *save_column_widths = NULL; *rows = 0; return 0; } len = max_width/(item_extra+item_min_size); if (len <= 0) len = 1; if (max_columns <= 0 || len < max_columns) max_columns = len; columns = g_new0(int *, max_columns); columns_width = g_new0(int, max_columns); columns_rows = g_new0(int, max_columns); for (n = 1; n < max_columns; n++) { columns[n] = g_new0(int, n+1); columns_rows[n] = items_count <= n+1 ? 1 : (items_count+n)/(n+1); } /* for each possible column count, save the column widths and find the biggest column count that fits to screen. */ item_pos = 0; max_len = 0; for (tmp = items; tmp != NULL; tmp = tmp->next) { len = item_extra+len_func(tmp->data); if (max_len < len) max_len = len; for (n = 1; n < max_columns; n++) { if (columns_width[n] > max_width) continue; /* too wide */ col = item_pos/columns_rows[n]; if (columns[n][col] < len) { columns_width[n] += len-columns[n][col]; columns[n][col] = len; } } item_pos++; } for (n = max_columns-1; n >= 1; n--) { if (columns_width[n] <= max_width && columns[n][n] > 0) break; } ret = n+1; *save_column_widths = g_new(int, ret); if (ret == 1) { **save_column_widths = max_len; *rows = 1; } else { memcpy(*save_column_widths, columns[ret-1], sizeof(int)*ret); *rows = columns_rows[ret-1]; } for (n = 1; n < max_columns; n++) g_free(columns[n]); g_free(columns_width); g_free(columns_rows); g_free(columns); return ret; } /* Return a column sorted copy of a list. */ GSList *columns_sort_list(GSList *list, int rows) { GSList *tmp, *sorted; int row, skip; if (list == NULL || rows == 0) return list; sorted = NULL; for (row = 0; row < rows; row++) { tmp = g_slist_nth(list, row); skip = 1; for (; tmp != NULL; tmp = tmp->next) { if (--skip == 0) { skip = rows; sorted = g_slist_append(sorted, tmp->data); } } } g_return_val_if_fail(g_slist_length(sorted) == g_slist_length(list), sorted); return sorted; } /* Expand escape string, the first character in data should be the one after '\'. Returns the expanded character or -1 if error. */ int expand_escape(const char **data) { char digit[4]; switch (**data) { case 't': return '\t'; case 'r': return '\r'; case 'n': return '\n'; case 'e': return 27; /* ESC */ case '\\': return '\\'; case 'x': /* hex digit */ if (!i_isxdigit((*data)[1]) || !i_isxdigit((*data)[2])) return -1; digit[0] = (*data)[1]; digit[1] = (*data)[2]; digit[2] = '\0'; *data += 2; return strtol(digit, NULL, 16); case 'c': /* control character (\cA = ^A) */ (*data)++; return i_toupper(**data) - 64; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': /* octal */ digit[1] = digit[2] = digit[3] = '\0'; digit[0] = (*data)[0]; if ((*data)[1] >= '0' && (*data)[1] <= '7') { ++*data; digit[1] = **data; if ((*data)[1] >= '0' && (*data)[1] <= '7') { ++*data; digit[2] = **data; } } return strtol(digit, NULL, 8); default: return -1; } } /* Escape all '"', "'" and '\' chars with '\' */ char *escape_string(const char *str) { char *ret, *p; p = ret = g_malloc(strlen(str)*2+1); while (*str != '\0') { if (*str == '"' || *str == '\'' || *str == '\\') *p++ = '\\'; *p++ = *str++; } *p = '\0'; return ret; } int nearest_power(int num) { int n = 1; while (n < num) n <<= 1; return n; } /* Parses unsigned integers from strings with decent error checking. * Returns true on success, false otherwise (overflow, no valid number, etc) * There's a 31 bit limit so the output can be assigned to signed positive ints */ int parse_uint(const char *nptr, char **endptr, int base, guint *number) { char *endptr_; gulong parsed; /* strtoul accepts whitespace and plus/minus signs, for some reason */ if (!i_isdigit(*nptr)) { return FALSE; } errno = 0; parsed = strtoul(nptr, &endptr_, base); if (errno || endptr_ == nptr || parsed >= (1U << 31)) { return FALSE; } if (endptr) { *endptr = endptr_; } if (number) { *number = (guint) parsed; } return TRUE; } static int parse_number_sign(const char *input, char **endptr, int *sign) { int sign_ = 1; while (i_isspace(*input)) input++; if (*input == '-') { sign_ = -sign_; input++; } *sign = sign_; *endptr = (char *) input; return TRUE; } static int parse_time_interval_uint(const char *time, guint *msecs) { const char *desc; guint number; int len, ret, digits; *msecs = 0; /* max. return value is around 24 days */ number = 0; ret = TRUE; digits = FALSE; while (i_isspace(*time)) time++; for (;;) { if (i_isdigit(*time)) { char *endptr; if (!parse_uint(time, &endptr, 10, &number)) { return FALSE; } time = endptr; digits = TRUE; continue; } if (!digits) return FALSE; /* skip punctuation */ while (*time != '\0' && i_ispunct(*time) && *time != '-') time++; /* get description */ for (len = 0, desc = time; i_isalpha(*time); time++) len++; while (i_isspace(*time)) time++; if (len == 0) { if (*time != '\0') return FALSE; *msecs += number * 1000; /* assume seconds */ return TRUE; } if (g_ascii_strncasecmp(desc, "days", len) == 0) { if (number > 24) { /* would overflow */ return FALSE; } *msecs += number * 1000*3600*24; } else if (g_ascii_strncasecmp(desc, "hours", len) == 0) *msecs += number * 1000*3600; else if (g_ascii_strncasecmp(desc, "minutes", len) == 0 || g_ascii_strncasecmp(desc, "mins", len) == 0) *msecs += number * 1000*60; else if (g_ascii_strncasecmp(desc, "seconds", len) == 0 || g_ascii_strncasecmp(desc, "secs", len) == 0) *msecs += number * 1000; else if (g_ascii_strncasecmp(desc, "milliseconds", len) == 0 || g_ascii_strncasecmp(desc, "millisecs", len) == 0 || g_ascii_strncasecmp(desc, "mseconds", len) == 0 || g_ascii_strncasecmp(desc, "msecs", len) == 0) *msecs += number; else { ret = FALSE; } /* skip punctuation */ while (*time != '\0' && i_ispunct(*time) && *time != '-') time++; if (*time == '\0') break; number = 0; digits = FALSE; } return ret; } static int parse_size_uint(const char *size, guint *bytes) { const char *desc; guint number, multiplier, limit; int len; *bytes = 0; /* max. return value is about 1.6 years */ number = 0; while (*size != '\0') { if (i_isdigit(*size)) { char *endptr; if (!parse_uint(size, &endptr, 10, &number)) { return FALSE; } size = endptr; continue; } /* skip punctuation */ while (*size != '\0' && i_ispunct(*size)) size++; /* get description */ for (len = 0, desc = size; i_isalpha(*size); size++) len++; if (len == 0) { if (number == 0) { /* "0" - allow it */ return TRUE; } *bytes += number*1024; /* assume kilobytes */ return FALSE; } multiplier = 0; limit = 0; if (g_ascii_strncasecmp(desc, "gbytes", len) == 0) { multiplier = 1U << 30; limit = 2U << 0; } if (g_ascii_strncasecmp(desc, "mbytes", len) == 0) { multiplier = 1U << 20; limit = 2U << 10; } if (g_ascii_strncasecmp(desc, "kbytes", len) == 0) { multiplier = 1U << 10; limit = 2U << 20; } if (g_ascii_strncasecmp(desc, "bytes", len) == 0) { multiplier = 1; limit = 2U << 30; } if (limit && number > limit) { return FALSE; } *bytes += number * multiplier; /* skip punctuation */ while (*size != '\0' && i_ispunct(*size)) size++; } return TRUE; } int parse_size(const char *size, int *bytes) { guint bytes_; int ret; ret = parse_size_uint(size, &bytes_); if (bytes_ > (1U << 31)) { return FALSE; } *bytes = bytes_; return ret; } int parse_time_interval(const char *time, int *msecs) { guint msecs_; char *number; int ret, sign; parse_number_sign(time, &number, &sign); ret = parse_time_interval_uint(number, &msecs_); if (msecs_ > (1U << 31)) { return FALSE; } *msecs = msecs_ * sign; return ret; } char *ascii_strup(char *str) { char *s; for (s = str; *s; s++) *s = g_ascii_toupper (*s); return str; } char *ascii_strdown(char *str) { char *s; for (s = str; *s; s++) *s = g_ascii_tolower (*s); return str; } char **strsplit_len(const char *str, int len, gboolean onspace) { char **ret = g_new(char *, 1); int n; int offset; for (n = 0; *str != '\0'; n++, str += offset) { offset = MIN(len, strlen(str)); if (onspace && strlen(str) > len) { /* * Try to find a space to split on and leave * the space on the previous line. */ int i; for (i = len - 1; i > 0; i--) { if (str[i] == ' ') { offset = i; break; } } } ret[n] = g_strndup(str, offset); ret = g_renew(char *, ret, n + 2); } ret[n] = NULL; return ret; } char *binary_to_hex(unsigned char *buffer, size_t size) { static const char hex[] = "0123456789ABCDEF"; char *result = NULL; int i; if (buffer == NULL || size == 0) return NULL; result = g_malloc(3 * size); for (i = 0; i < size; i++) { result[i * 3 + 0] = hex[(buffer[i] >> 4) & 0xf]; result[i * 3 + 1] = hex[(buffer[i] >> 0) & 0xf]; result[i * 3 + 2] = i == size - 1 ? '\0' : ':'; } return result; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_2561_0
crossvul-cpp_data_good_1319_2
/* ** 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-476/c/good_1319_2
crossvul-cpp_data_good_2606_0
/* Generic associative array implementation. * * See Documentation/core-api/assoc_array.rst for information. * * Copyright (C) 2013 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. */ //#define DEBUG #include <linux/rcupdate.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/assoc_array_priv.h> /* * Iterate over an associative array. The caller must hold the RCU read lock * or better. */ static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root, const struct assoc_array_ptr *stop, int (*iterator)(const void *leaf, void *iterator_data), void *iterator_data) { const struct assoc_array_shortcut *shortcut; const struct assoc_array_node *node; const struct assoc_array_ptr *cursor, *ptr, *parent; unsigned long has_meta; int slot, ret; cursor = root; begin_node: if (assoc_array_ptr_is_shortcut(cursor)) { /* Descend through a shortcut */ shortcut = assoc_array_ptr_to_shortcut(cursor); smp_read_barrier_depends(); cursor = ACCESS_ONCE(shortcut->next_node); } node = assoc_array_ptr_to_node(cursor); smp_read_barrier_depends(); slot = 0; /* We perform two passes of each node. * * The first pass does all the leaves in this node. This means we * don't miss any leaves if the node is split up by insertion whilst * we're iterating over the branches rooted here (we may, however, see * some leaves twice). */ has_meta = 0; for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); has_meta |= (unsigned long)ptr; if (ptr && assoc_array_ptr_is_leaf(ptr)) { /* We need a barrier between the read of the pointer * and dereferencing the pointer - but only if we are * actually going to dereference it. */ smp_read_barrier_depends(); /* Invoke the callback */ ret = iterator(assoc_array_ptr_to_leaf(ptr), iterator_data); if (ret) return ret; } } /* The second pass attends to all the metadata pointers. If we follow * one of these we may find that we don't come back here, but rather go * back to a replacement node with the leaves in a different layout. * * We are guaranteed to make progress, however, as the slot number for * a particular portion of the key space cannot change - and we * continue at the back pointer + 1. */ if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE)) goto finished_node; slot = 0; continue_node: node = assoc_array_ptr_to_node(cursor); smp_read_barrier_depends(); for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); if (assoc_array_ptr_is_meta(ptr)) { cursor = ptr; goto begin_node; } } finished_node: /* Move up to the parent (may need to skip back over a shortcut) */ parent = ACCESS_ONCE(node->back_pointer); slot = node->parent_slot; if (parent == stop) return 0; if (assoc_array_ptr_is_shortcut(parent)) { shortcut = assoc_array_ptr_to_shortcut(parent); smp_read_barrier_depends(); cursor = parent; parent = ACCESS_ONCE(shortcut->back_pointer); slot = shortcut->parent_slot; if (parent == stop) return 0; } /* Ascend to next slot in parent node */ cursor = parent; slot++; goto continue_node; } /** * assoc_array_iterate - Pass all objects in the array to a callback * @array: The array to iterate over. * @iterator: The callback function. * @iterator_data: Private data for the callback function. * * Iterate over all the objects in an associative array. Each one will be * presented to the iterator function. * * If the array is being modified concurrently with the iteration then it is * possible that some objects in the array will be passed to the iterator * callback more than once - though every object should be passed at least * once. If this is undesirable then the caller must lock against modification * for the duration of this function. * * The function will return 0 if no objects were in the array or else it will * return the result of the last iterator function called. Iteration stops * immediately if any call to the iteration function results in a non-zero * return. * * The caller should hold the RCU read lock or better if concurrent * modification is possible. */ int assoc_array_iterate(const struct assoc_array *array, int (*iterator)(const void *object, void *iterator_data), void *iterator_data) { struct assoc_array_ptr *root = ACCESS_ONCE(array->root); if (!root) return 0; return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data); } enum assoc_array_walk_status { assoc_array_walk_tree_empty, assoc_array_walk_found_terminal_node, assoc_array_walk_found_wrong_shortcut, }; struct assoc_array_walk_result { struct { struct assoc_array_node *node; /* Node in which leaf might be found */ int level; int slot; } terminal_node; struct { struct assoc_array_shortcut *shortcut; int level; int sc_level; unsigned long sc_segments; unsigned long dissimilarity; } wrong_shortcut; }; /* * Navigate through the internal tree looking for the closest node to the key. */ static enum assoc_array_walk_status assoc_array_walk(const struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *cursor, *ptr; unsigned long sc_segments, dissimilarity; unsigned long segments; int level, sc_level, next_sc_level; int slot; pr_devel("-->%s()\n", __func__); cursor = ACCESS_ONCE(array->root); if (!cursor) return assoc_array_walk_tree_empty; level = 0; /* Use segments from the key for the new leaf to navigate through the * internal tree, skipping through nodes and shortcuts that are on * route to the destination. Eventually we'll come to a slot that is * either empty or contains a leaf at which point we've found a node in * which the leaf we're looking for might be found or into which it * should be inserted. */ jumped: segments = ops->get_key_chunk(index_key, level); pr_devel("segments[%d]: %lx\n", level, segments); if (assoc_array_ptr_is_shortcut(cursor)) goto follow_shortcut; consider_node: node = assoc_array_ptr_to_node(cursor); smp_read_barrier_depends(); slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK); slot &= ASSOC_ARRAY_FAN_MASK; ptr = ACCESS_ONCE(node->slots[slot]); pr_devel("consider slot %x [ix=%d type=%lu]\n", slot, level, (unsigned long)ptr & 3); if (!assoc_array_ptr_is_meta(ptr)) { /* The node doesn't have a node/shortcut pointer in the slot * corresponding to the index key that we have to follow. */ result->terminal_node.node = node; result->terminal_node.level = level; result->terminal_node.slot = slot; pr_devel("<--%s() = terminal_node\n", __func__); return assoc_array_walk_found_terminal_node; } if (assoc_array_ptr_is_node(ptr)) { /* There is a pointer to a node in the slot corresponding to * this index key segment, so we need to follow it. */ cursor = ptr; level += ASSOC_ARRAY_LEVEL_STEP; if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) goto consider_node; goto jumped; } /* There is a shortcut in the slot corresponding to the index key * segment. We follow the shortcut if its partial index key matches * this leaf's. Otherwise we need to split the shortcut. */ cursor = ptr; follow_shortcut: shortcut = assoc_array_ptr_to_shortcut(cursor); smp_read_barrier_depends(); pr_devel("shortcut to %d\n", shortcut->skip_to_level); sc_level = level + ASSOC_ARRAY_LEVEL_STEP; BUG_ON(sc_level > shortcut->skip_to_level); do { /* Check the leaf against the shortcut's index key a word at a * time, trimming the final word (the shortcut stores the index * key completely from the root to the shortcut's target). */ if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0) segments = ops->get_key_chunk(index_key, sc_level); sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT]; dissimilarity = segments ^ sc_segments; if (round_up(sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE) > shortcut->skip_to_level) { /* Trim segments that are beyond the shortcut */ int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK; dissimilarity &= ~(ULONG_MAX << shift); next_sc_level = shortcut->skip_to_level; } else { next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE; next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); } if (dissimilarity != 0) { /* This shortcut points elsewhere */ result->wrong_shortcut.shortcut = shortcut; result->wrong_shortcut.level = level; result->wrong_shortcut.sc_level = sc_level; result->wrong_shortcut.sc_segments = sc_segments; result->wrong_shortcut.dissimilarity = dissimilarity; return assoc_array_walk_found_wrong_shortcut; } sc_level = next_sc_level; } while (sc_level < shortcut->skip_to_level); /* The shortcut matches the leaf's index to this point. */ cursor = ACCESS_ONCE(shortcut->next_node); if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) { level = sc_level; goto jumped; } else { level = sc_level; goto consider_node; } } /** * assoc_array_find - Find an object by index key * @array: The associative array to search. * @ops: The operations to use. * @index_key: The key to the object. * * Find an object in an associative array by walking through the internal tree * to the node that should contain the object and then searching the leaves * there. NULL is returned if the requested object was not found in the array. * * The caller must hold the RCU read lock or better. */ void *assoc_array_find(const struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key) { struct assoc_array_walk_result result; const struct assoc_array_node *node; const struct assoc_array_ptr *ptr; const void *leaf; int slot; if (assoc_array_walk(array, ops, index_key, &result) != assoc_array_walk_found_terminal_node) return NULL; node = result.terminal_node.node; smp_read_barrier_depends(); /* If the target key is available to us, it's has to be pointed to by * the terminal node. */ for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); if (ptr && assoc_array_ptr_is_leaf(ptr)) { /* We need a barrier between the read of the pointer * and dereferencing the pointer - but only if we are * actually going to dereference it. */ leaf = assoc_array_ptr_to_leaf(ptr); smp_read_barrier_depends(); if (ops->compare_object(leaf, index_key)) return (void *)leaf; } } return NULL; } /* * Destructively iterate over an associative array. The caller must prevent * other simultaneous accesses. */ static void assoc_array_destroy_subtree(struct assoc_array_ptr *root, const struct assoc_array_ops *ops) { struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *cursor, *parent = NULL; int slot = -1; pr_devel("-->%s()\n", __func__); cursor = root; if (!cursor) { pr_devel("empty\n"); return; } move_to_meta: if (assoc_array_ptr_is_shortcut(cursor)) { /* Descend through a shortcut */ pr_devel("[%d] shortcut\n", slot); BUG_ON(!assoc_array_ptr_is_shortcut(cursor)); shortcut = assoc_array_ptr_to_shortcut(cursor); BUG_ON(shortcut->back_pointer != parent); BUG_ON(slot != -1 && shortcut->parent_slot != slot); parent = cursor; cursor = shortcut->next_node; slot = -1; BUG_ON(!assoc_array_ptr_is_node(cursor)); } pr_devel("[%d] node\n", slot); node = assoc_array_ptr_to_node(cursor); BUG_ON(node->back_pointer != parent); BUG_ON(slot != -1 && node->parent_slot != slot); slot = 0; continue_node: pr_devel("Node %p [back=%p]\n", node, node->back_pointer); for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { struct assoc_array_ptr *ptr = node->slots[slot]; if (!ptr) continue; if (assoc_array_ptr_is_meta(ptr)) { parent = cursor; cursor = ptr; goto move_to_meta; } if (ops) { pr_devel("[%d] free leaf\n", slot); ops->free_object(assoc_array_ptr_to_leaf(ptr)); } } parent = node->back_pointer; slot = node->parent_slot; pr_devel("free node\n"); kfree(node); if (!parent) return; /* Done */ /* Move back up to the parent (may need to free a shortcut on * the way up) */ if (assoc_array_ptr_is_shortcut(parent)) { shortcut = assoc_array_ptr_to_shortcut(parent); BUG_ON(shortcut->next_node != cursor); cursor = parent; parent = shortcut->back_pointer; slot = shortcut->parent_slot; pr_devel("free shortcut\n"); kfree(shortcut); if (!parent) return; BUG_ON(!assoc_array_ptr_is_node(parent)); } /* Ascend to next slot in parent node */ pr_devel("ascend to %p[%d]\n", parent, slot); cursor = parent; node = assoc_array_ptr_to_node(cursor); slot++; goto continue_node; } /** * assoc_array_destroy - Destroy an associative array * @array: The array to destroy. * @ops: The operations to use. * * Discard all metadata and free all objects in an associative array. The * array will be empty and ready to use again upon completion. This function * cannot fail. * * The caller must prevent all other accesses whilst this takes place as no * attempt is made to adjust pointers gracefully to permit RCU readlock-holding * accesses to continue. On the other hand, no memory allocation is required. */ void assoc_array_destroy(struct assoc_array *array, const struct assoc_array_ops *ops) { assoc_array_destroy_subtree(array->root, ops); array->root = NULL; } /* * Handle insertion into an empty tree. */ static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit) { struct assoc_array_node *new_n0; pr_devel("-->%s()\n", __func__); new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); edit->leaf_p = &new_n0->slots[0]; edit->adjust_count_on = new_n0; edit->set[0].ptr = &edit->array->root; edit->set[0].to = assoc_array_node_to_ptr(new_n0); pr_devel("<--%s() = ok [no root]\n", __func__); return true; } /* * Handle insertion into a terminal node. */ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0; struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; int slot, next_slot, free_slot, i, j; node = result->terminal_node.node; level = result->terminal_node.level; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel("-->%s()\n", __func__); /* We arrived at a node which doesn't have an onward node or shortcut * pointer that we have to follow. This means that (a) the leaf we * want must go here (either by insertion or replacement) or (b) we * need to split this node and insert in one of the fragments. */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's * a matching one we should replace in place. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (!ptr) { free_slot = i; continue; } if (assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { pr_devel("replace in slot %d\n", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; pr_devel("<--%s() = ok [replace]\n", __func__); return true; } } /* If there is a free slot in this node then we can just insert the * leaf here. */ if (free_slot >= 0) { pr_devel("insert in free slot %d\n", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; pr_devel("<--%s() = ok [insert]\n", __func__); return true; } /* The node has no spare slots - so we're either going to have to split * it or insert another node before it. * * Whatever, we're going to need at least two new nodes - so allocate * those now. We may also need a new shortcut, but we deal with that * when we need it. */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n1) return false; edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); /* We need to find out how similar the leaves are. */ pr_devel("no spare slots\n"); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { edit->segment_cache[i] = 0xff; have_meta = true; continue; } base_seg = ops->get_object_key_chunk( assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } if (have_meta) { pr_devel("have meta\n"); goto split_node; } /* The node contains only leaves */ dissimilarity = 0; base_seg = edit->segment_cache[0]; for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) dissimilarity |= edit->segment_cache[i] ^ base_seg; pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { /* The old leaves all cluster in the same slot. We will need * to insert a shortcut if the new node wants to cluster with them. */ if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) goto all_leaves_cluster_together; /* Otherwise all the old leaves cluster in the same slot, but * the new leaf wants to go into a different slot - so we * create a new node (n0) to hold the new leaf and a pointer to * a new node (n1) holding all the old leaves. * * This can be done by falling through to the node splitting * path. */ pr_devel("present leaves cluster but not new leaf\n"); } split_node: pr_devel("split node\n"); /* We need to split the current node. The node must contain anything * from a single leaf (in the one leaf case, this leaf will cluster * with the new leaf) and the rest meta-pointers, to all leaves, some * of which may cluster. * * It won't contain the case in which all the current leaves plus the * new leaves want to cluster in the same slot. * * We need to expel at least two leaves out of a set consisting of the * leaves in the node and the new leaf. The current meta pointers can * just be copied as they shouldn't cluster with any of the leaves. * * We need a new node (n0) to replace the current one and a new node to * take the expelled nodes (n1). */ edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: pr_devel("do_split_node\n"); new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; /* Begin by finding two matching leaves. There have to be at least two * that match - even if there are meta pointers - because any leaf that * would match a slot with a meta pointer in it must be somewhere * behind that meta pointer and cannot be here. Further, given N * remaining leaf slots, we now have N+1 leaves to go in them. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { slot = edit->segment_cache[i]; if (slot != 0xff) for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) if (edit->segment_cache[j] == slot) goto found_slot_for_multiple_occupancy; } found_slot_for_multiple_occupancy: pr_devel("same slot: %x %x [%02x]\n", i, j, slot); BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); new_n1->parent_slot = slot; /* Metadata pointers cannot change slot */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) if (assoc_array_ptr_is_meta(node->slots[i])) new_n0->slots[i] = node->slots[i]; else new_n0->slots[i] = NULL; BUG_ON(new_n0->slots[slot] != NULL); new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); /* Filter the leaf pointers between the new nodes */ free_slot = -1; next_slot = 0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (assoc_array_ptr_is_meta(node->slots[i])) continue; if (edit->segment_cache[i] == slot) { new_n1->slots[next_slot++] = node->slots[i]; new_n1->nr_leaves_on_branch++; } else { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); new_n0->slots[free_slot] = node->slots[i]; } } pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); edit->leaf_p = &new_n0->slots[free_slot]; edit->adjust_count_on = new_n0; } else { edit->leaf_p = &new_n1->slots[next_slot++]; edit->adjust_count_on = new_n1; } BUG_ON(next_slot <= 1); edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (edit->segment_cache[i] == 0xff) { ptr = node->slots[i]; BUG_ON(assoc_array_ptr_is_leaf(ptr)); if (assoc_array_ptr_is_node(ptr)) { side = assoc_array_ptr_to_node(ptr); edit->set_backpointers[i] = &side->back_pointer; } else { shortcut = assoc_array_ptr_to_shortcut(ptr); edit->set_backpointers[i] = &shortcut->back_pointer; } } } ptr = node->back_pointer; if (!ptr) edit->set[0].ptr = &edit->array->root; else if (assoc_array_ptr_is_node(ptr)) edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; else edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [split node]\n", __func__); return true; all_leaves_cluster_together: /* All the leaves, new and old, want to cluster together in this node * in the same slot, so we have to replace this node with a shortcut to * skip over the identical parts of the key and then place a pair of * nodes, one inside the other, at the end of the shortcut and * distribute the keys between them. * * Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * * We only need to make a single pass of N of the N+1 leaves because if * any keys differ between themselves at bit X then at least one of * them must also differ with the base key at bit X or before. */ pr_devel("all leaves cluster together\n"); diff = INT_MAX; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), index_key); if (x < diff) { BUG_ON(x < 0); diff = x; } } BUG_ON(diff == INT_MAX); BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel("skip_to_level = %d [diff %d]\n", level, diff); BUG_ON(level <= 0); for (i = 0; i < keylen; i++) new_s0->index_key[i] = ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); new_s0->index_key[keylen - 1] &= ~blank; /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; } /* * Handle insertion into the middle of a shortcut. */ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0, *new_s1; struct assoc_array_node *node, *new_n0, *side; unsigned long sc_segments, dissimilarity, blank; size_t keylen; int level, sc_level, diff; int sc_slot; shortcut = result->wrong_shortcut.shortcut; level = result->wrong_shortcut.level; sc_level = result->wrong_shortcut.sc_level; sc_segments = result->wrong_shortcut.sc_segments; dissimilarity = result->wrong_shortcut.dissimilarity; pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n", __func__, level, dissimilarity, sc_level); /* We need to split a shortcut and insert a node between the two * pieces. Zero-length pieces will be dispensed with entirely. * * First of all, we need to find out in which level the first * difference was. */ diff = __ffs(dissimilarity); diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK; diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK; pr_devel("diff=%d\n", diff); if (!shortcut->back_pointer) { edit->set[0].ptr = &edit->array->root; } else if (assoc_array_ptr_is_node(shortcut->back_pointer)) { node = assoc_array_ptr_to_node(shortcut->back_pointer); edit->set[0].ptr = &node->slots[shortcut->parent_slot]; } else { BUG(); } edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut); /* Create a new node now since we're going to need it anyway */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); edit->adjust_count_on = new_n0; /* Insert a new shortcut before the new node if this segment isn't of * zero length - otherwise we just connect the new node directly to the * parent. */ level += ASSOC_ARRAY_LEVEL_STEP; if (diff > level) { pr_devel("pre-shortcut %d...%d\n", level, diff); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = shortcut->back_pointer; new_s0->parent_slot = shortcut->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_s0->skip_to_level = diff; new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; memcpy(new_s0->index_key, shortcut->index_key, keylen * sizeof(unsigned long)); blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); new_s0->index_key[keylen - 1] &= ~blank; } else { pr_devel("no pre-shortcut\n"); edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = shortcut->back_pointer; new_n0->parent_slot = shortcut->parent_slot; } side = assoc_array_ptr_to_node(shortcut->next_node); new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch; /* We need to know which slot in the new node is going to take a * metadata pointer. */ sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); sc_slot &= ASSOC_ARRAY_FAN_MASK; pr_devel("new slot %lx >> %d -> %d\n", sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot); /* Determine whether we need to follow the new node with a replacement * for the current shortcut. We could in theory reuse the current * shortcut if its parent slot number doesn't change - but that's a * 1-in-16 chance so not worth expending the code upon. */ level = diff + ASSOC_ARRAY_LEVEL_STEP; if (level < shortcut->skip_to_level) { pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level); keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s1 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s1) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1); new_s1->back_pointer = assoc_array_node_to_ptr(new_n0); new_s1->parent_slot = sc_slot; new_s1->next_node = shortcut->next_node; new_s1->skip_to_level = shortcut->skip_to_level; new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1); memcpy(new_s1->index_key, shortcut->index_key, keylen * sizeof(unsigned long)); edit->set[1].ptr = &side->back_pointer; edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1); } else { pr_devel("no post-shortcut\n"); /* We don't have to replace the pointed-to node as long as we * use memory barriers to make sure the parent slot number is * changed before the back pointer (the parent slot number is * irrelevant to the old parent shortcut). */ new_n0->slots[sc_slot] = shortcut->next_node; edit->set_parent_slot[0].p = &side->parent_slot; edit->set_parent_slot[0].to = sc_slot; edit->set[1].ptr = &side->back_pointer; edit->set[1].to = assoc_array_node_to_ptr(new_n0); } /* Install the new leaf in a spare slot in the new node. */ if (sc_slot == 0) edit->leaf_p = &new_n0->slots[1]; else edit->leaf_p = &new_n0->slots[0]; pr_devel("<--%s() = ok [split shortcut]\n", __func__); return edit; } /** * assoc_array_insert - Script insertion of an object into an associative array * @array: The array to insert into. * @ops: The operations to use. * @index_key: The key to insert at. * @object: The object to insert. * * Precalculate and preallocate a script for the insertion or replacement of an * object in an associative array. This results in an edit script that can * either be applied or cancelled. * * The function returns a pointer to an edit script or -ENOMEM. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ struct assoc_array_edit *assoc_array_insert(struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key, void *object) { struct assoc_array_walk_result result; struct assoc_array_edit *edit; pr_devel("-->%s()\n", __func__); /* The leaf pointer we're given must not have the bottom bit set as we * use those for type-marking the pointer. NULL pointers are also not * allowed as they indicate an empty slot but we have to allow them * here as they can be updated later. */ BUG_ON(assoc_array_ptr_is_meta(object)); edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return ERR_PTR(-ENOMEM); edit->array = array; edit->ops = ops; edit->leaf = assoc_array_leaf_to_ptr(object); edit->adjust_count_by = 1; switch (assoc_array_walk(array, ops, index_key, &result)) { case assoc_array_walk_tree_empty: /* Allocate a root node if there isn't one yet */ if (!assoc_array_insert_in_empty_tree(edit)) goto enomem; return edit; case assoc_array_walk_found_terminal_node: /* We found a node that doesn't have a node/shortcut pointer in * the slot corresponding to the index key that we have to * follow. */ if (!assoc_array_insert_into_terminal_node(edit, ops, index_key, &result)) goto enomem; return edit; case assoc_array_walk_found_wrong_shortcut: /* We found a shortcut that didn't match our key in a slot we * needed to follow. */ if (!assoc_array_insert_mid_shortcut(edit, ops, &result)) goto enomem; return edit; } enomem: /* Clean up after an out of memory error */ pr_devel("enomem\n"); assoc_array_cancel_edit(edit); return ERR_PTR(-ENOMEM); } /** * assoc_array_insert_set_object - Set the new object pointer in an edit script * @edit: The edit script to modify. * @object: The object pointer to set. * * Change the object to be inserted in an edit script. The object pointed to * by the old object is not freed. This must be done prior to applying the * script. */ void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object) { BUG_ON(!object); edit->leaf = assoc_array_leaf_to_ptr(object); } struct assoc_array_delete_collapse_context { struct assoc_array_node *node; const void *skip_leaf; int slot; }; /* * Subtree collapse to node iterator. */ static int assoc_array_delete_collapse_iterator(const void *leaf, void *iterator_data) { struct assoc_array_delete_collapse_context *collapse = iterator_data; if (leaf == collapse->skip_leaf) return 0; BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT); collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf); return 0; } /** * assoc_array_delete - Script deletion of an object from an associative array * @array: The array to search. * @ops: The operations to use. * @index_key: The key to the object. * * Precalculate and preallocate a script for the deletion of an object from an * associative array. This results in an edit script that can either be * applied or cancelled. * * The function returns a pointer to an edit script if the object was found, * NULL if the object was not found or -ENOMEM. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key) { struct assoc_array_delete_collapse_context collapse; struct assoc_array_walk_result result; struct assoc_array_node *node, *new_n0; struct assoc_array_edit *edit; struct assoc_array_ptr *ptr; bool has_meta; int slot, i; pr_devel("-->%s()\n", __func__); edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return ERR_PTR(-ENOMEM); edit->array = array; edit->ops = ops; edit->adjust_count_by = -1; switch (assoc_array_walk(array, ops, index_key, &result)) { case assoc_array_walk_found_terminal_node: /* We found a node that should contain the leaf we've been * asked to remove - *if* it's in the tree. */ pr_devel("terminal_node\n"); node = result.terminal_node.node; for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = node->slots[slot]; if (ptr && assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) goto found_leaf; } case assoc_array_walk_tree_empty: case assoc_array_walk_found_wrong_shortcut: default: assoc_array_cancel_edit(edit); pr_devel("not found\n"); return NULL; } found_leaf: BUG_ON(array->nr_leaves_on_tree <= 0); /* In the simplest form of deletion we just clear the slot and release * the leaf after a suitable interval. */ edit->dead_leaf = node->slots[slot]; edit->set[0].ptr = &node->slots[slot]; edit->set[0].to = NULL; edit->adjust_count_on = node; /* If that concludes erasure of the last leaf, then delete the entire * internal array. */ if (array->nr_leaves_on_tree == 1) { edit->set[1].ptr = &array->root; edit->set[1].to = NULL; edit->adjust_count_on = NULL; edit->excised_subtree = array->root; pr_devel("all gone\n"); return edit; } /* However, we'd also like to clear up some metadata blocks if we * possibly can. * * We go for a simple algorithm of: if this node has FAN_OUT or fewer * leaves in it, then attempt to collapse it - and attempt to * recursively collapse up the tree. * * We could also try and collapse in partially filled subtrees to take * up space in this node. */ if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { struct assoc_array_node *parent, *grandparent; struct assoc_array_ptr *ptr; /* First of all, we need to know if this node has metadata so * that we don't try collapsing if all the leaves are already * here. */ has_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { has_meta = true; break; } } pr_devel("leaves: %ld [m=%d]\n", node->nr_leaves_on_branch - 1, has_meta); /* Look further up the tree to see if we can collapse this node * into a more proximal node too. */ parent = node; collapse_up: pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); ptr = parent->back_pointer; if (!ptr) goto do_collapse; if (assoc_array_ptr_is_shortcut(ptr)) { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); ptr = s->back_pointer; if (!ptr) goto do_collapse; } grandparent = assoc_array_ptr_to_node(ptr); if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { parent = grandparent; goto collapse_up; } do_collapse: /* There's no point collapsing if the original node has no meta * pointers to discard and if we didn't merge into one of that * node's ancestry. */ if (has_meta || parent != node) { node = parent; /* Create a new node to collapse into */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) goto enomem; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; edit->adjust_count_on = new_n0; collapse.node = new_n0; collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); collapse.slot = 0; assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), node->back_pointer, assoc_array_delete_collapse_iterator, &collapse); pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); if (!node->back_pointer) { edit->set[1].ptr = &array->root; } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { BUG(); } else if (assoc_array_ptr_is_node(node->back_pointer)) { struct assoc_array_node *p = assoc_array_ptr_to_node(node->back_pointer); edit->set[1].ptr = &p->slots[node->parent_slot]; } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(node->back_pointer); edit->set[1].ptr = &s->next_node; } edit->set[1].to = assoc_array_node_to_ptr(new_n0); edit->excised_subtree = assoc_array_node_to_ptr(node); } } return edit; enomem: /* Clean up after an out of memory error */ pr_devel("enomem\n"); assoc_array_cancel_edit(edit); return ERR_PTR(-ENOMEM); } /** * assoc_array_clear - Script deletion of all objects from an associative array * @array: The array to clear. * @ops: The operations to use. * * Precalculate and preallocate a script for the deletion of all the objects * from an associative array. This results in an edit script that can either * be applied or cancelled. * * The function returns a pointer to an edit script if there are objects to be * deleted, NULL if there are no objects in the array or -ENOMEM. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ struct assoc_array_edit *assoc_array_clear(struct assoc_array *array, const struct assoc_array_ops *ops) { struct assoc_array_edit *edit; pr_devel("-->%s()\n", __func__); if (!array->root) return NULL; edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return ERR_PTR(-ENOMEM); edit->array = array; edit->ops = ops; edit->set[1].ptr = &array->root; edit->set[1].to = NULL; edit->excised_subtree = array->root; edit->ops_for_excised_subtree = ops; pr_devel("all gone\n"); return edit; } /* * Handle the deferred destruction after an applied edit. */ static void assoc_array_rcu_cleanup(struct rcu_head *head) { struct assoc_array_edit *edit = container_of(head, struct assoc_array_edit, rcu); int i; pr_devel("-->%s()\n", __func__); if (edit->dead_leaf) edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf)); for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++) if (edit->excised_meta[i]) kfree(assoc_array_ptr_to_node(edit->excised_meta[i])); if (edit->excised_subtree) { BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree)); if (assoc_array_ptr_is_node(edit->excised_subtree)) { struct assoc_array_node *n = assoc_array_ptr_to_node(edit->excised_subtree); n->back_pointer = NULL; } else { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(edit->excised_subtree); s->back_pointer = NULL; } assoc_array_destroy_subtree(edit->excised_subtree, edit->ops_for_excised_subtree); } kfree(edit); } /** * assoc_array_apply_edit - Apply an edit script to an associative array * @edit: The script to apply. * * Apply an edit script to an associative array to effect an insertion, * deletion or clearance. As the edit script includes preallocated memory, * this is guaranteed not to fail. * * The edit script, dead objects and dead metadata will be scheduled for * destruction after an RCU grace period to permit those doing read-only * accesses on the array to continue to do so under the RCU read lock whilst * the edit is taking place. */ void assoc_array_apply_edit(struct assoc_array_edit *edit) { struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *ptr; int i; pr_devel("-->%s()\n", __func__); smp_wmb(); if (edit->leaf_p) *edit->leaf_p = edit->leaf; smp_wmb(); for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++) if (edit->set_parent_slot[i].p) *edit->set_parent_slot[i].p = edit->set_parent_slot[i].to; smp_wmb(); for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++) if (edit->set_backpointers[i]) *edit->set_backpointers[i] = edit->set_backpointers_to; smp_wmb(); for (i = 0; i < ARRAY_SIZE(edit->set); i++) if (edit->set[i].ptr) *edit->set[i].ptr = edit->set[i].to; if (edit->array->root == NULL) { edit->array->nr_leaves_on_tree = 0; } else if (edit->adjust_count_on) { node = edit->adjust_count_on; for (;;) { node->nr_leaves_on_branch += edit->adjust_count_by; ptr = node->back_pointer; if (!ptr) break; if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); ptr = shortcut->back_pointer; if (!ptr) break; } BUG_ON(!assoc_array_ptr_is_node(ptr)); node = assoc_array_ptr_to_node(ptr); } edit->array->nr_leaves_on_tree += edit->adjust_count_by; } call_rcu(&edit->rcu, assoc_array_rcu_cleanup); } /** * assoc_array_cancel_edit - Discard an edit script. * @edit: The script to discard. * * Free an edit script and all the preallocated data it holds without making * any changes to the associative array it was intended for. * * NOTE! In the case of an insertion script, this does _not_ release the leaf * that was to be inserted. That is left to the caller. */ void assoc_array_cancel_edit(struct assoc_array_edit *edit) { struct assoc_array_ptr *ptr; int i; pr_devel("-->%s()\n", __func__); /* Clean up after an out of memory error */ for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) { ptr = edit->new_meta[i]; if (ptr) { if (assoc_array_ptr_is_node(ptr)) kfree(assoc_array_ptr_to_node(ptr)); else kfree(assoc_array_ptr_to_shortcut(ptr)); } } kfree(edit); } /** * assoc_array_gc - Garbage collect an associative array. * @array: The array to clean. * @ops: The operations to use. * @iterator: A callback function to pass judgement on each object. * @iterator_data: Private data for the callback function. * * Collect garbage from an associative array and pack down the internal tree to * save memory. * * The iterator function is asked to pass judgement upon each object in the * array. If it returns false, the object is discard and if it returns true, * the object is kept. If it returns true, it must increment the object's * usage count (or whatever it needs to do to retain it) before returning. * * This function returns 0 if successful or -ENOMEM if out of memory. In the * latter case, the array is not changed. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ int assoc_array_gc(struct assoc_array *array, const struct assoc_array_ops *ops, bool (*iterator)(void *object, void *iterator_data), void *iterator_data) { struct assoc_array_shortcut *shortcut, *new_s; struct assoc_array_node *node, *new_n; struct assoc_array_edit *edit; struct assoc_array_ptr *cursor, *ptr; struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp; unsigned long nr_leaves_on_tree; int keylen, slot, nr_free, next_slot, i; pr_devel("-->%s()\n", __func__); if (!array->root) return 0; edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return -ENOMEM; edit->array = array; edit->ops = ops; edit->ops_for_excised_subtree = ops; edit->set[0].ptr = &array->root; edit->excised_subtree = array->root; new_root = new_parent = NULL; new_ptr_pp = &new_root; cursor = array->root; descend: /* If this point is a shortcut, then we need to duplicate it and * advance the target cursor. */ if (assoc_array_ptr_is_shortcut(cursor)) { shortcut = assoc_array_ptr_to_shortcut(cursor); keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s = kmalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s) goto enomem; pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); memcpy(new_s, shortcut, (sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long))); new_s->back_pointer = new_parent; new_s->parent_slot = shortcut->parent_slot; *new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s); new_ptr_pp = &new_s->next_node; cursor = shortcut->next_node; } /* Duplicate the node at this position */ node = assoc_array_ptr_to_node(cursor); new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n) goto enomem; pr_devel("dup node %p -> %p\n", node, new_n); new_n->back_pointer = new_parent; new_n->parent_slot = node->parent_slot; *new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n); new_ptr_pp = NULL; slot = 0; continue_node: /* Filter across any leaves and gc any subtrees */ for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = node->slots[slot]; if (!ptr) continue; if (assoc_array_ptr_is_leaf(ptr)) { if (iterator(assoc_array_ptr_to_leaf(ptr), iterator_data)) /* The iterator will have done any reference * counting on the object for us. */ new_n->slots[slot] = ptr; continue; } new_ptr_pp = &new_n->slots[slot]; cursor = ptr; goto descend; } pr_devel("-- compress node %p --\n", new_n); /* Count up the number of empty slots in this node and work out the * subtree leaf count. */ new_n->nr_leaves_on_branch = 0; nr_free = 0; for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = new_n->slots[slot]; if (!ptr) nr_free++; else if (assoc_array_ptr_is_leaf(ptr)) new_n->nr_leaves_on_branch++; } pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch); /* See what we can fold in */ next_slot = 0; for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { struct assoc_array_shortcut *s; struct assoc_array_node *child; ptr = new_n->slots[slot]; if (!ptr || assoc_array_ptr_is_leaf(ptr)) continue; s = NULL; if (assoc_array_ptr_is_shortcut(ptr)) { s = assoc_array_ptr_to_shortcut(ptr); ptr = s->next_node; } child = assoc_array_ptr_to_node(ptr); new_n->nr_leaves_on_branch += child->nr_leaves_on_branch; if (child->nr_leaves_on_branch <= nr_free + 1) { /* Fold the child node into this one */ pr_devel("[%d] fold node %lu/%d [nx %d]\n", slot, child->nr_leaves_on_branch, nr_free + 1, next_slot); /* We would already have reaped an intervening shortcut * on the way back up the tree. */ BUG_ON(s); new_n->slots[slot] = NULL; nr_free++; if (slot < next_slot) next_slot = slot; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { struct assoc_array_ptr *p = child->slots[i]; if (!p) continue; BUG_ON(assoc_array_ptr_is_meta(p)); while (new_n->slots[next_slot]) next_slot++; BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT); new_n->slots[next_slot++] = p; nr_free--; } kfree(child); } else { pr_devel("[%d] retain node %lu/%d [nx %d]\n", slot, child->nr_leaves_on_branch, nr_free + 1, next_slot); } } pr_devel("after: %lu\n", new_n->nr_leaves_on_branch); nr_leaves_on_tree = new_n->nr_leaves_on_branch; /* Excise this node if it is singly occupied by a shortcut */ if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) { for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) if ((ptr = new_n->slots[slot])) break; if (assoc_array_ptr_is_meta(ptr) && assoc_array_ptr_is_shortcut(ptr)) { pr_devel("excise node %p with 1 shortcut\n", new_n); new_s = assoc_array_ptr_to_shortcut(ptr); new_parent = new_n->back_pointer; slot = new_n->parent_slot; kfree(new_n); if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; new_root = ptr; goto gc_complete; } if (assoc_array_ptr_is_shortcut(new_parent)) { /* We can discard any preceding shortcut also */ struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(new_parent); pr_devel("excise preceding shortcut\n"); new_parent = new_s->back_pointer = s->back_pointer; slot = new_s->parent_slot = s->parent_slot; kfree(s); if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; new_root = ptr; goto gc_complete; } } new_s->back_pointer = new_parent; new_s->parent_slot = slot; new_n = assoc_array_ptr_to_node(new_parent); new_n->slots[slot] = ptr; goto ascend_old_tree; } } /* Excise any shortcuts we might encounter that point to nodes that * only contain leaves. */ ptr = new_n->back_pointer; if (!ptr) goto gc_complete; if (assoc_array_ptr_is_shortcut(ptr)) { new_s = assoc_array_ptr_to_shortcut(ptr); new_parent = new_s->back_pointer; slot = new_s->parent_slot; if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { struct assoc_array_node *n; pr_devel("excise shortcut\n"); new_n->back_pointer = new_parent; new_n->parent_slot = slot; kfree(new_s); if (!new_parent) { new_root = assoc_array_node_to_ptr(new_n); goto gc_complete; } n = assoc_array_ptr_to_node(new_parent); n->slots[slot] = assoc_array_node_to_ptr(new_n); } } else { new_parent = ptr; } new_n = assoc_array_ptr_to_node(new_parent); ascend_old_tree: ptr = node->back_pointer; if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); slot = shortcut->parent_slot; cursor = shortcut->back_pointer; if (!cursor) goto gc_complete; } else { slot = node->parent_slot; cursor = ptr; } BUG_ON(!cursor); node = assoc_array_ptr_to_node(cursor); slot++; goto continue_node; gc_complete: edit->set[0].to = new_root; assoc_array_apply_edit(edit); array->nr_leaves_on_tree = nr_leaves_on_tree; return 0; enomem: pr_devel("enomem\n"); assoc_array_destroy_subtree(new_root, edit->ops); kfree(edit); return -ENOMEM; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_2606_0
crossvul-cpp_data_good_588_0
/* $Id: form.c,v 1.35 2010/07/18 13:48:48 htrb Exp $ */ /* * HTML forms */ #include "fm.h" #include "parsetag.h" #include "parsetagx.h" #include "myctype.h" #include "local.h" #include "regex.h" extern Str *textarea_str; extern int max_textarea; #ifdef MENU_SELECT extern FormSelectOption *select_option; extern int max_select; #include "menu.h" #endif /* MENU_SELECT */ /* *INDENT-OFF* */ struct { char *action; void (*rout)(struct parsed_tagarg *); } internal_action[] = { {"map", follow_map}, {"option", panel_set_option}, #ifdef USE_COOKIE {"cookie", set_cookie_flag}, #endif /* USE_COOKIE */ {"download", download_action}, #ifdef USE_M17N { "charset", change_charset }, #endif {"none", NULL}, {NULL, NULL}, }; /* *INDENT-ON* */ struct form_list * newFormList(char *action, char *method, char *charset, char *enctype, char *target, char *name, struct form_list *_next) { struct form_list *l; Str a = Strnew_charp(action); int m = FORM_METHOD_GET; int e = FORM_ENCTYPE_URLENCODED; #ifdef USE_M17N wc_ces c = 0; #endif if (method == NULL || !strcasecmp(method, "get")) m = FORM_METHOD_GET; else if (!strcasecmp(method, "post")) m = FORM_METHOD_POST; else if (!strcasecmp(method, "internal")) m = FORM_METHOD_INTERNAL; /* unknown method is regarded as 'get' */ if (m != FORM_METHOD_GET && enctype != NULL && !strcasecmp(enctype, "multipart/form-data")) { e = FORM_ENCTYPE_MULTIPART; } #ifdef USE_M17N if (charset != NULL) c = wc_guess_charset(charset, 0); #endif l = New(struct form_list); l->item = l->lastitem = NULL; l->action = a; l->method = m; #ifdef USE_M17N l->charset = c; #endif l->enctype = e; l->target = target; l->name = name; l->next = _next; l->nitems = 0; l->body = NULL; l->length = 0; return l; } /* * add <input> element to form_list */ struct form_item_list * formList_addInput(struct form_list *fl, struct parsed_tag *tag) { struct form_item_list *item; char *p; int i; /* if not in <form>..</form> environment, just ignore <input> tag */ if (fl == NULL) return NULL; item = New(struct form_item_list); item->type = FORM_UNKNOWN; item->size = -1; item->rows = 0; item->checked = item->init_checked = 0; item->accept = 0; item->name = NULL; item->value = item->init_value = NULL; item->readonly = 0; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { item->type = formtype(p); if (item->size < 0 && (item->type == FORM_INPUT_TEXT || item->type == FORM_INPUT_FILE || item->type == FORM_INPUT_PASSWORD)) item->size = FORM_I_TEXT_DEFAULT_SIZE; } if (parsedtag_get_value(tag, ATTR_NAME, &p)) item->name = Strnew_charp(p); if (parsedtag_get_value(tag, ATTR_VALUE, &p)) item->value = item->init_value = Strnew_charp(p); item->checked = item->init_checked = parsedtag_exists(tag, ATTR_CHECKED); item->accept = parsedtag_exists(tag, ATTR_ACCEPT); parsedtag_get_value(tag, ATTR_SIZE, &item->size); parsedtag_get_value(tag, ATTR_MAXLENGTH, &item->maxlength); item->readonly = parsedtag_exists(tag, ATTR_READONLY); if (parsedtag_get_value(tag, ATTR_TEXTAREANUMBER, &i) && i >= 0 && i < max_textarea) item->value = item->init_value = textarea_str[i]; #ifdef MENU_SELECT if (parsedtag_get_value(tag, ATTR_SELECTNUMBER, &i) && i >= 0 && i < max_select) item->select_option = select_option[i].first; #endif /* MENU_SELECT */ if (parsedtag_get_value(tag, ATTR_ROWS, &p)) item->rows = atoi(p); if (item->type == FORM_UNKNOWN) { /* type attribute is missing. Ignore the tag. */ return NULL; } #ifdef MENU_SELECT if (item->type == FORM_SELECT) { chooseSelectOption(item, item->select_option); item->init_selected = item->selected; item->init_value = item->value; item->init_label = item->label; } #endif /* MENU_SELECT */ if (item->type == FORM_INPUT_FILE && item->value && item->value->length) { /* security hole ! */ return NULL; } item->parent = fl; item->next = NULL; if (fl->item == NULL) { fl->item = fl->lastitem = item; } else { fl->lastitem->next = item; fl->lastitem = item; } if (item->type == FORM_INPUT_HIDDEN) return NULL; fl->nitems++; return item; } static char *_formtypetbl[] = { "text", "password", "checkbox", "radio", "submit", "reset", "hidden", "image", "select", "textarea", "button", "file", NULL }; static char *_formmethodtbl[] = { "GET", "POST", "INTERNAL", "HEAD" }; char * form2str(FormItemList *fi) { Str tmp = Strnew(); if (fi->type != FORM_SELECT && fi->type != FORM_TEXTAREA) Strcat_charp(tmp, "input type="); Strcat_charp(tmp, _formtypetbl[fi->type]); if (fi->name && fi->name->length) Strcat_m_charp(tmp, " name=\"", fi->name->ptr, "\"", NULL); if ((fi->type == FORM_INPUT_RADIO || fi->type == FORM_INPUT_CHECKBOX || fi->type == FORM_SELECT) && fi->value) Strcat_m_charp(tmp, " value=\"", fi->value->ptr, "\"", NULL); Strcat_m_charp(tmp, " (", _formmethodtbl[fi->parent->method], " ", fi->parent->action->ptr, ")", NULL); return tmp->ptr; } int formtype(char *typestr) { int i; for (i = 0; _formtypetbl[i]; i++) { if (!strcasecmp(typestr, _formtypetbl[i])) return i; } return FORM_INPUT_TEXT; } void formRecheckRadio(Anchor *a, Buffer *buf, FormItemList *fi) { int i; Anchor *a2; FormItemList *f2; for (i = 0; i < buf->formitem->nanchor; i++) { a2 = &buf->formitem->anchors[i]; f2 = (FormItemList *)a2->url; if (f2->parent == fi->parent && f2 != fi && f2->type == FORM_INPUT_RADIO && Strcmp(f2->name, fi->name) == 0) { f2->checked = 0; formUpdateBuffer(a2, buf, f2); } } fi->checked = 1; formUpdateBuffer(a, buf, fi); } void formResetBuffer(Buffer *buf, AnchorList *formitem) { int i; Anchor *a; FormItemList *f1, *f2; if (buf == NULL || buf->formitem == NULL || formitem == NULL) return; for (i = 0; i < buf->formitem->nanchor && i < formitem->nanchor; i++) { a = &buf->formitem->anchors[i]; if (a->y != a->start.line) continue; f1 = (FormItemList *)a->url; f2 = (FormItemList *)formitem->anchors[i].url; if (f1->type != f2->type || strcmp(((f1->name == NULL) ? "" : f1->name->ptr), ((f2->name == NULL) ? "" : f2->name->ptr))) break; /* What's happening */ switch (f1->type) { case FORM_INPUT_TEXT: case FORM_INPUT_PASSWORD: case FORM_INPUT_FILE: case FORM_TEXTAREA: f1->value = f2->value; f1->init_value = f2->init_value; break; case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: f1->checked = f2->checked; f1->init_checked = f2->init_checked; break; case FORM_SELECT: #ifdef MENU_SELECT f1->select_option = f2->select_option; f1->value = f2->value; f1->label = f2->label; f1->selected = f2->selected; f1->init_value = f2->init_value; f1->init_label = f2->init_label; f1->init_selected = f2->init_selected; #endif /* MENU_SELECT */ break; default: continue; } formUpdateBuffer(a, buf, f1); } } static int form_update_line(Line *line, char **str, int spos, int epos, int width, int newline, int password) { int c_len = 1, c_width = 1, w, i, len, pos; char *p, *buf; Lineprop c_type, effect, *prop; for (p = *str, w = 0, pos = 0; *p && w < width;) { c_type = get_mctype((unsigned char *)p); #ifdef USE_M17N c_len = get_mclen(p); c_width = get_mcwidth(p); #endif if (c_type == PC_CTRL) { if (newline && *p == '\n') break; if (*p != '\r') { w++; pos++; } } else if (password) { #ifdef USE_M17N if (w + c_width > width) break; #endif w += c_width; pos += c_width; #ifdef USE_M17N } else if (c_type & PC_UNKNOWN) { w++; pos++; } else { if (w + c_width > width) break; #endif w += c_width; pos += c_len; } p += c_len; } pos += width - w; len = line->len + pos + spos - epos; buf = New_N(char, len + 1); buf[len] = '\0'; prop = New_N(Lineprop, len); bcopy((void *)line->lineBuf, (void *)buf, spos * sizeof(char)); bcopy((void *)line->propBuf, (void *)prop, spos * sizeof(Lineprop)); effect = CharEffect(line->propBuf[spos]); for (p = *str, w = 0, pos = spos; *p && w < width;) { c_type = get_mctype((unsigned char *)p); #ifdef USE_M17N c_len = get_mclen(p); c_width = get_mcwidth(p); #endif if (c_type == PC_CTRL) { if (newline && *p == '\n') break; if (*p != '\r') { buf[pos] = password ? '*' : ' '; prop[pos] = effect | PC_ASCII; pos++; w++; } } else if (password) { #ifdef USE_M17N if (w + c_width > width) break; #endif for (i = 0; i < c_width; i++) { buf[pos] = '*'; prop[pos] = effect | PC_ASCII; pos++; w++; } #ifdef USE_M17N } else if (c_type & PC_UNKNOWN) { buf[pos] = ' '; prop[pos] = effect | PC_ASCII; pos++; w++; } else { if (w + c_width > width) break; #else } else { #endif buf[pos] = *p; prop[pos] = effect | c_type; pos++; #ifdef USE_M17N c_type = (c_type & ~PC_WCHAR1) | PC_WCHAR2; for (i = 1; i < c_len; i++) { buf[pos] = p[i]; prop[pos] = effect | c_type; pos++; } #endif w += c_width; } p += c_len; } for (; w < width; w++) { buf[pos] = ' '; prop[pos] = effect | PC_ASCII; pos++; } if (newline) { if (!FoldTextarea) { while (*p && *p != '\r' && *p != '\n') p++; } if (*p == '\r') p++; if (*p == '\n') p++; } *str = p; bcopy((void *)&line->lineBuf[epos], (void *)&buf[pos], (line->len - epos) * sizeof(char)); bcopy((void *)&line->propBuf[epos], (void *)&prop[pos], (line->len - epos) * sizeof(Lineprop)); line->lineBuf = buf; line->propBuf = prop; line->len = len; line->size = len; return pos; } void formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (buf->currentLine == NULL || spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ { if (!form->value) break; p = form->value->ptr; } l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (l == NULL) break; if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0 || COLPOS(l, epos) < col) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); } Str textfieldrep(Str s, int width) { Lineprop c_type; Str n = Strnew_size(width + 2); int i, j, k, c_len; j = 0; for (i = 0; i < s->length; i += c_len) { c_type = get_mctype((unsigned char *)&s->ptr[i]); c_len = get_mclen(&s->ptr[i]); if (s->ptr[i] == '\r') continue; k = j + get_mcwidth(&s->ptr[i]); if (k > width) break; if (c_type == PC_CTRL) Strcat_char(n, ' '); #ifdef USE_M17N else if (c_type & PC_UNKNOWN) Strcat_char(n, ' '); #endif else if (s->ptr[i] == '&') Strcat_charp(n, "&amp;"); else if (s->ptr[i] == '<') Strcat_charp(n, "&lt;"); else if (s->ptr[i] == '>') Strcat_charp(n, "&gt;"); else Strcat_charp_n(n, &s->ptr[i], c_len); j = k; } for (; j < width; j++) Strcat_char(n, ' '); return n; } static void form_fputs_decode(Str s, FILE * f) { char *p; Str z = Strnew(); for (p = s->ptr; *p;) { switch (*p) { #if !defined( __CYGWIN__ ) && !defined( __EMX__ ) case '\r': if (*(p + 1) == '\n') p++; /* continue to the next label */ #endif /* !defined( __CYGWIN__ ) && !defined( __EMX__ * ) */ default: Strcat_char(z, *p); p++; break; } } #ifdef USE_M17N z = wc_Str_conv_strict(z, InnerCharset, DisplayCharset); #endif Strfputs(z, f); } void input_textarea(FormItemList *fi) { char *tmpf = tmpfname(TMPF_DFL, NULL)->ptr; Str tmp; FILE *f; #ifdef USE_M17N wc_ces charset = DisplayCharset; wc_uint8 auto_detect; #endif f = fopen(tmpf, "w"); if (f == NULL) { /* FIXME: gettextize? */ disp_err_message("Can't open temporary file", FALSE); return; } if (fi->value) form_fputs_decode(fi->value, f); fclose(f); fmTerm(); system(myEditor(Editor, tmpf, 1)->ptr); fmInit(); if (fi->readonly) goto input_end; f = fopen(tmpf, "r"); if (f == NULL) { /* FIXME: gettextize? */ disp_err_message("Can't open temporary file", FALSE); goto input_end; } fi->value = Strnew(); #ifdef USE_M17N auto_detect = WcOption.auto_detect; WcOption.auto_detect = WC_OPT_DETECT_ON; #endif while (tmp = Strfgets(f), tmp->length > 0) { if (tmp->length == 1 && tmp->ptr[tmp->length - 1] == '\n') { /* null line with bare LF */ tmp = Strnew_charp("\r\n"); } else if (tmp->length > 1 && tmp->ptr[tmp->length - 1] == '\n' && tmp->ptr[tmp->length - 2] != '\r') { Strshrink(tmp, 1); Strcat_charp(tmp, "\r\n"); } tmp = convertLine(NULL, tmp, RAW_MODE, &charset, DisplayCharset); Strcat(fi->value, tmp); } #ifdef USE_M17N WcOption.auto_detect = auto_detect; #endif fclose(f); input_end: unlink(tmpf); } void do_internal(char *action, char *data) { int i; for (i = 0; internal_action[i].action; i++) { if (strcasecmp(internal_action[i].action, action) == 0) { if (internal_action[i].rout) internal_action[i].rout(cgistr2tagarg(data)); return; } } } #ifdef MENU_SELECT void addSelectOption(FormSelectOption *fso, Str value, Str label, int chk) { FormSelectOptionItem *o; o = New(FormSelectOptionItem); if (value == NULL) value = label; o->value = value; Strremovefirstspaces(label); Strremovetrailingspaces(label); o->label = label; o->checked = chk; o->next = NULL; if (fso->first == NULL) fso->first = fso->last = o; else { fso->last->next = o; fso->last = o; } } void chooseSelectOption(FormItemList *fi, FormSelectOptionItem *item) { FormSelectOptionItem *opt; int i; fi->selected = 0; if (item == NULL) { fi->value = Strnew_size(0); fi->label = Strnew_size(0); return; } fi->value = item->value; fi->label = item->label; for (i = 0, opt = item; opt != NULL; i++, opt = opt->next) { if (opt->checked) { fi->value = opt->value; fi->label = opt->label; fi->selected = i; break; } } updateSelectOption(fi, item); } void updateSelectOption(FormItemList *fi, FormSelectOptionItem *item) { int i; if (fi == NULL || item == NULL) return; for (i = 0; item != NULL; i++, item = item->next) { if (i == fi->selected) item->checked = TRUE; else item->checked = FALSE; } } int formChooseOptionByMenu(struct form_item_list *fi, int x, int y) { int i, n, selected = -1, init_select = fi->selected; FormSelectOptionItem *opt; char **label; for (n = 0, opt = fi->select_option; opt != NULL; n++, opt = opt->next) ; label = New_N(char *, n + 1); for (i = 0, opt = fi->select_option; opt != NULL; i++, opt = opt->next) label[i] = opt->label->ptr; label[n] = NULL; optionMenu(x, y, label, &selected, init_select, NULL); if (selected < 0) return 0; for (i = 0, opt = fi->select_option; opt != NULL; i++, opt = opt->next) { if (i == selected) { fi->selected = selected; fi->value = opt->value; fi->label = opt->label; break; } } updateSelectOption(fi, fi->select_option); return 1; } #endif /* MENU_SELECT */ void form_write_data(FILE * f, char *boundary, char *name, char *value) { fprintf(f, "--%s\r\n", boundary); fprintf(f, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n", name); fprintf(f, "%s\r\n", value); } void form_write_from_file(FILE * f, char *boundary, char *name, char *filename, char *file) { FILE *fd; struct stat st; int c; char *type; fprintf(f, "--%s\r\n", boundary); fprintf(f, "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n", name, mybasename(filename)); type = guessContentType(file); fprintf(f, "Content-Type: %s\r\n\r\n", type ? type : "application/octet-stream"); if (lstat(file, &st) < 0) goto write_end; if (S_ISDIR(st.st_mode)) goto write_end; fd = fopen(file, "r"); if (fd != NULL) { while ((c = fgetc(fd)) != EOF) fputc(c, f); fclose(fd); } write_end: fprintf(f, "\r\n"); } struct pre_form_item { int type; char *name; char *value; int checked; struct pre_form_item *next; }; struct pre_form { char *url; Regex *re_url; char *name; char *action; struct pre_form_item *item; struct pre_form *next; }; static struct pre_form *PreForm = NULL; static struct pre_form * add_pre_form(struct pre_form *prev, char *url, Regex *re_url, char *name, char *action) { ParsedURL pu; struct pre_form *new; if (prev) new = prev->next = New(struct pre_form); else new = PreForm = New(struct pre_form); if (url && !re_url) { parseURL2(url, &pu, NULL); new->url = parsedURL2Str(&pu)->ptr; } else new->url = url; new->re_url = re_url; new->name = (name && *name) ? name : NULL; new->action = (action && *action) ? action : NULL; new->item = NULL; new->next = NULL; return new; } static struct pre_form_item * add_pre_form_item(struct pre_form *pf, struct pre_form_item *prev, int type, char *name, char *value, char *checked) { struct pre_form_item *new; if (!pf) return NULL; if (prev) new = prev->next = New(struct pre_form_item); else new = pf->item = New(struct pre_form_item); new->type = type; new->name = name; new->value = value; if (checked && *checked && (!strcmp(checked, "0") || !strcasecmp(checked, "off") || !strcasecmp(checked, "no"))) new->checked = 0; else new->checked = 1; new->next = NULL; return new; } /* * url <url>|/<re-url>/ * form [<name>] <action> * text <name> <value> * file <name> <value> * passwd <name> <value> * checkbox <name> <value> [<checked>] * radio <name> <value> * select <name> <value> * submit [<name> [<value>]] * image [<name> [<value>]] * textarea <name> * <value> * /textarea */ void loadPreForm(void) { FILE *fp; Str line = NULL, textarea = NULL; struct pre_form *pf = NULL; struct pre_form_item *pi = NULL; int type = -1; char *name = NULL; PreForm = NULL; fp = openSecretFile(pre_form_file); if (fp == NULL) return; while (1) { char *p, *s, *arg; Regex *re_arg; line = Strfgets(fp); if (line->length == 0) break; if (textarea && !(!strncmp(line->ptr, "/textarea", 9) && IS_SPACE(line->ptr[9]))) { Strcat(textarea, line); continue; } Strchop(line); Strremovefirstspaces(line); p = line->ptr; if (*p == '#' || *p == '\0') continue; /* comment or empty line */ s = getWord(&p); if (!strcmp(s, "url")) { arg = getRegexWord((const char **)&p, &re_arg); if (!arg || !*arg) continue; p = getQWord(&p); pf = add_pre_form(pf, arg, re_arg, NULL, p); pi = pf->item; continue; } if (!pf) continue; arg = getWord(&p); if (!strcmp(s, "form")) { if (!arg || !*arg) continue; s = getQWord(&p); p = getQWord(&p); if (!p || !*p) { p = s; s = NULL; } if (pf->item) { struct pre_form *prev = pf; pf = add_pre_form(prev, "", NULL, s, p); /* copy previous URL */ pf->url = prev->url; pf->re_url = prev->re_url; } else { pf->name = s; pf->action = (p && *p) ? p : NULL; } pi = pf->item; continue; } if (!strcmp(s, "text")) type = FORM_INPUT_TEXT; else if (!strcmp(s, "file")) type = FORM_INPUT_FILE; else if (!strcmp(s, "passwd") || !strcmp(s, "password")) type = FORM_INPUT_PASSWORD; else if (!strcmp(s, "checkbox")) type = FORM_INPUT_CHECKBOX; else if (!strcmp(s, "radio")) type = FORM_INPUT_RADIO; else if (!strcmp(s, "submit")) type = FORM_INPUT_SUBMIT; else if (!strcmp(s, "image")) type = FORM_INPUT_IMAGE; else if (!strcmp(s, "select")) type = FORM_SELECT; else if (!strcmp(s, "textarea")) { type = FORM_TEXTAREA; name = Strnew_charp(arg)->ptr; textarea = Strnew(); continue; } else if (textarea && name && !strcmp(s, "/textarea")) { pi = add_pre_form_item(pf, pi, type, name, textarea->ptr, NULL); textarea = NULL; name = NULL; continue; } else continue; s = getQWord(&p); pi = add_pre_form_item(pf, pi, type, arg, s, getQWord(&p)); } fclose(fp); } void preFormUpdateBuffer(Buffer *buf) { struct pre_form *pf; struct pre_form_item *pi; int i; Anchor *a; FormList *fl; FormItemList *fi; #ifdef MENU_SELECT FormSelectOptionItem *opt; int j; #endif if (!buf || !buf->formitem || !PreForm) return; for (pf = PreForm; pf; pf = pf->next) { if (pf->re_url) { Str url = parsedURL2Str(&buf->currentURL); if (!RegexMatch(pf->re_url, url->ptr, url->length, 1)) continue; } else if (pf->url) { if (Strcmp_charp(parsedURL2Str(&buf->currentURL), pf->url)) continue; } else continue; for (i = 0; i < buf->formitem->nanchor; i++) { a = &buf->formitem->anchors[i]; fi = (FormItemList *)a->url; fl = fi->parent; if (pf->name && (!fl->name || strcmp(fl->name, pf->name))) continue; if (pf->action && (!fl->action || Strcmp_charp(fl->action, pf->action))) continue; for (pi = pf->item; pi; pi = pi->next) { if (pi->type != fi->type) continue; if (pi->type == FORM_INPUT_SUBMIT || pi->type == FORM_INPUT_IMAGE) { if ((!pi->name || !*pi->name || (fi->name && !Strcmp_charp(fi->name, pi->name))) && (!pi->value || !*pi->value || (fi->value && !Strcmp_charp(fi->value, pi->value)))) buf->submit = a; continue; } if (!pi->name || !fi->name || Strcmp_charp(fi->name, pi->name)) continue; switch (pi->type) { case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: fi->value = Strnew_charp(pi->value); formUpdateBuffer(a, buf, fi); break; case FORM_INPUT_CHECKBOX: if (pi->value && fi->value && !Strcmp_charp(fi->value, pi->value)) { fi->checked = pi->checked; formUpdateBuffer(a, buf, fi); } break; case FORM_INPUT_RADIO: if (pi->value && fi->value && !Strcmp_charp(fi->value, pi->value)) formRecheckRadio(a, buf, fi); break; #ifdef MENU_SELECT case FORM_SELECT: for (j = 0, opt = fi->select_option; opt != NULL; j++, opt = opt->next) { if (pi->value && opt->value && !Strcmp_charp(opt->value, pi->value)) { fi->selected = j; fi->value = opt->value; fi->label = opt->label; updateSelectOption(fi, fi->select_option); formUpdateBuffer(a, buf, fi); break; } } break; #endif } } } } }
./CrossVul/dataset_final_sorted/CWE-476/c/good_588_0
crossvul-cpp_data_bad_635_0
/* * Copyright (c) 2007 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/pagemap.h> #include <linux/slab.h> #include <linux/rbtree.h> #include <linux/dma-mapping.h> /* for DMA_*_DEVICE */ #include "rds.h" /* * XXX * - build with sparse * - should we detect duplicate keys on a socket? hmm. * - an rdma is an mlock, apply rlimit? */ /* * get the number of pages by looking at the page indices that the start and * end addresses fall in. * * Returns 0 if the vec is invalid. It is invalid if the number of bytes * causes the address to wrap or overflows an unsigned int. This comes * from being stored in the 'length' member of 'struct scatterlist'. */ static unsigned int rds_pages_in_vec(struct rds_iovec *vec) { if ((vec->addr + vec->bytes <= vec->addr) || (vec->bytes > (u64)UINT_MAX)) return 0; return ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) - (vec->addr >> PAGE_SHIFT); } static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key, struct rds_mr *insert) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct rds_mr *mr; while (*p) { parent = *p; mr = rb_entry(parent, struct rds_mr, r_rb_node); if (key < mr->r_key) p = &(*p)->rb_left; else if (key > mr->r_key) p = &(*p)->rb_right; else return mr; } if (insert) { rb_link_node(&insert->r_rb_node, parent, p); rb_insert_color(&insert->r_rb_node, root); refcount_inc(&insert->r_refcount); } return NULL; } /* * Destroy the transport-specific part of a MR. */ static void rds_destroy_mr(struct rds_mr *mr) { struct rds_sock *rs = mr->r_sock; void *trans_private = NULL; unsigned long flags; rdsdebug("RDS: destroy mr key is %x refcnt %u\n", mr->r_key, refcount_read(&mr->r_refcount)); if (test_and_set_bit(RDS_MR_DEAD, &mr->r_state)) return; spin_lock_irqsave(&rs->rs_rdma_lock, flags); if (!RB_EMPTY_NODE(&mr->r_rb_node)) rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); trans_private = mr->r_trans_private; mr->r_trans_private = NULL; spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (trans_private) mr->r_trans->free_mr(trans_private, mr->r_invalidate); } void __rds_put_mr_final(struct rds_mr *mr) { rds_destroy_mr(mr); kfree(mr); } /* * By the time this is called we can't have any more ioctls called on * the socket so we don't need to worry about racing with others. */ void rds_rdma_drop_keys(struct rds_sock *rs) { struct rds_mr *mr; struct rb_node *node; unsigned long flags; /* Release any MRs associated with this socket */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); while ((node = rb_first(&rs->rs_rdma_keys))) { mr = rb_entry(node, struct rds_mr, r_rb_node); if (mr->r_trans == rs->rs_transport) mr->r_invalidate = 0; rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); rds_destroy_mr(mr); rds_mr_put(mr); spin_lock_irqsave(&rs->rs_rdma_lock, flags); } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (rs->rs_transport && rs->rs_transport->flush_mrs) rs->rs_transport->flush_mrs(); } /* * Helper function to pin user pages. */ static int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages, struct page **pages, int write) { int ret; ret = get_user_pages_fast(user_addr, nr_pages, write, pages); if (ret >= 0 && ret < nr_pages) { while (ret--) put_page(pages[ret]); ret = -EFAULT; } return ret; } static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args, u64 *cookie_ret, struct rds_mr **mr_ret) { struct rds_mr *mr = NULL, *found; unsigned int nr_pages; struct page **pages = NULL; struct scatterlist *sg; void *trans_private; unsigned long flags; rds_rdma_cookie_t cookie; unsigned int nents; long i; int ret; if (rs->rs_bound_addr == 0) { ret = -ENOTCONN; /* XXX not a great errno */ goto out; } if (!rs->rs_transport->get_mr) { ret = -EOPNOTSUPP; goto out; } nr_pages = rds_pages_in_vec(&args->vec); if (nr_pages == 0) { ret = -EINVAL; goto out; } /* Restrict the size of mr irrespective of underlying transport * To account for unaligned mr regions, subtract one from nr_pages */ if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) { ret = -EMSGSIZE; goto out; } rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n", args->vec.addr, args->vec.bytes, nr_pages); /* XXX clamp nr_pages to limit the size of this alloc? */ pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL); if (!mr) { ret = -ENOMEM; goto out; } refcount_set(&mr->r_refcount, 1); RB_CLEAR_NODE(&mr->r_rb_node); mr->r_trans = rs->rs_transport; mr->r_sock = rs; if (args->flags & RDS_RDMA_USE_ONCE) mr->r_use_once = 1; if (args->flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; if (args->flags & RDS_RDMA_READWRITE) mr->r_write = 1; /* * Pin the pages that make up the user buffer and transfer the page * pointers to the mr's sg array. We check to see if we've mapped * the whole region after transferring the partial page references * to the sg array so that we can have one page ref cleanup path. * * For now we have no flag that tells us whether the mapping is * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to * the zero page. */ ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1); if (ret < 0) goto out; nents = ret; sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL); if (!sg) { ret = -ENOMEM; goto out; } WARN_ON(!nents); sg_init_table(sg, nents); /* Stick all pages into the scatterlist */ for (i = 0 ; i < nents; i++) sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0); rdsdebug("RDS: trans_private nents is %u\n", nents); /* Obtain a transport specific MR. If this succeeds, the * s/g list is now owned by the MR. * Note that dma_map() implies that pending writes are * flushed to RAM, so no dma_sync is needed here. */ trans_private = rs->rs_transport->get_mr(sg, nents, rs, &mr->r_key); if (IS_ERR(trans_private)) { for (i = 0 ; i < nents; i++) put_page(sg_page(&sg[i])); kfree(sg); ret = PTR_ERR(trans_private); goto out; } mr->r_trans_private = trans_private; rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n", mr->r_key, (void *)(unsigned long) args->cookie_addr); /* The user may pass us an unaligned address, but we can only * map page aligned regions. So we keep the offset, and build * a 64bit cookie containing <R_Key, offset> and pass that * around. */ cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK); if (cookie_ret) *cookie_ret = cookie; if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) { ret = -EFAULT; goto out; } /* Inserting the new MR into the rbtree bumps its * reference count. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); BUG_ON(found && found != mr); rdsdebug("RDS: get_mr key is %x\n", mr->r_key); if (mr_ret) { refcount_inc(&mr->r_refcount); *mr_ret = mr; } ret = 0; out: kfree(pages); if (mr) rds_mr_put(mr); return ret; } int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_get_mr_args args; if (optlen != sizeof(struct rds_get_mr_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_get_mr_args __user *)optval, sizeof(struct rds_get_mr_args))) return -EFAULT; return __rds_rdma_map(rs, &args, NULL, NULL); } int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_get_mr_for_dest_args args; struct rds_get_mr_args new_args; if (optlen != sizeof(struct rds_get_mr_for_dest_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval, sizeof(struct rds_get_mr_for_dest_args))) return -EFAULT; /* * Initially, just behave like get_mr(). * TODO: Implement get_mr as wrapper around this * and deprecate it. */ new_args.vec = args.vec; new_args.cookie_addr = args.cookie_addr; new_args.flags = args.flags; return __rds_rdma_map(rs, &new_args, NULL, NULL); } /* * Free the MR indicated by the given R_Key */ int rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_free_mr_args args; struct rds_mr *mr; unsigned long flags; if (optlen != sizeof(struct rds_free_mr_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_free_mr_args __user *)optval, sizeof(struct rds_free_mr_args))) return -EFAULT; /* Special case - a null cookie means flush all unused MRs */ if (args.cookie == 0) { if (!rs->rs_transport || !rs->rs_transport->flush_mrs) return -EINVAL; rs->rs_transport->flush_mrs(); return 0; } /* Look up the MR given its R_key and remove it from the rbtree * so nobody else finds it. * This should also prevent races with rds_rdma_unuse. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL); if (mr) { rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); if (args.flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (!mr) return -EINVAL; /* * call rds_destroy_mr() ourselves so that we're sure it's done by the time * we return. If we let rds_mr_put() do it it might not happen until * someone else drops their ref. */ rds_destroy_mr(mr); rds_mr_put(mr); return 0; } /* * This is called when we receive an extension header that * tells us this MR was used. It allows us to implement * use_once semantics */ void rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force) { struct rds_mr *mr; unsigned long flags; int zot_me = 0; spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL); if (!mr) { pr_debug("rds: trying to unuse MR with unknown r_key %u!\n", r_key); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); return; } if (mr->r_use_once || force) { rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); zot_me = 1; } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); /* May have to issue a dma_sync on this memory region. * Note we could avoid this if the operation was a RDMA READ, * but at this point we can't tell. */ if (mr->r_trans->sync_mr) mr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE); /* If the MR was marked as invalidate, this will * trigger an async flush. */ if (zot_me) { rds_destroy_mr(mr); rds_mr_put(mr); } } void rds_rdma_free_op(struct rm_rdma_op *ro) { unsigned int i; for (i = 0; i < ro->op_nents; i++) { struct page *page = sg_page(&ro->op_sg[i]); /* Mark page dirty if it was possibly modified, which * is the case for a RDMA_READ which copies from remote * to local memory */ if (!ro->op_write) { WARN_ON(!page->mapping && irqs_disabled()); set_page_dirty(page); } put_page(page); } kfree(ro->op_notifier); ro->op_notifier = NULL; ro->op_active = 0; } void rds_atomic_free_op(struct rm_atomic_op *ao) { struct page *page = sg_page(ao->op_sg); /* Mark page dirty if it was possibly modified, which * is the case for a RDMA_READ which copies from remote * to local memory */ set_page_dirty(page); put_page(page); kfree(ao->op_notifier); ao->op_notifier = NULL; ao->op_active = 0; } /* * Count the number of pages needed to describe an incoming iovec array. */ static int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs) { int tot_pages = 0; unsigned int nr_pages; unsigned int i; /* figure out the number of pages in the vector */ for (i = 0; i < nr_iovecs; i++) { nr_pages = rds_pages_in_vec(&iov[i]); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages; } int rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); } /* * The application asks for a RDMA transfer. * Extract all arguments and set up the rdma_op */ int rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct rds_rdma_args *args; struct rm_rdma_op *op = &rm->rdma; int nr_pages; unsigned int nr_bytes; struct page **pages = NULL; struct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack; int iov_size; unsigned int i, j; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args)) || rm->rdma.op_active) return -EINVAL; args = CMSG_DATA(cmsg); if (rs->rs_bound_addr == 0) { ret = -ENOTCONN; /* XXX not a great errno */ goto out_ret; } if (args->nr_local > UIO_MAXIOV) { ret = -EMSGSIZE; goto out_ret; } /* Check whether to allocate the iovec area */ iov_size = args->nr_local * sizeof(struct rds_iovec); if (args->nr_local > UIO_FASTIOV) { iovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL); if (!iovs) { ret = -ENOMEM; goto out_ret; } } if (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) { ret = -EFAULT; goto out; } nr_pages = rds_rdma_pages(iovs, args->nr_local); if (nr_pages < 0) { ret = -EINVAL; goto out; } pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } op->op_write = !!(args->flags & RDS_RDMA_READWRITE); op->op_fence = !!(args->flags & RDS_RDMA_FENCE); op->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); op->op_silent = !!(args->flags & RDS_RDMA_SILENT); op->op_active = 1; op->op_recverr = rs->rs_recverr; WARN_ON(!nr_pages); op->op_sg = rds_message_alloc_sgs(rm, nr_pages); if (!op->op_sg) { ret = -ENOMEM; goto out; } if (op->op_notify || op->op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ op->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL); if (!op->op_notifier) { ret = -ENOMEM; goto out; } op->op_notifier->n_user_token = args->user_token; op->op_notifier->n_status = RDS_RDMA_SUCCESS; /* Enable rmda notification on data operation for composite * rds messages and make sure notification is enabled only * for the data operation which follows it so that application * gets notified only after full message gets delivered. */ if (rm->data.op_sg) { rm->rdma.op_notify = 0; rm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); } } /* The cookie contains the R_Key of the remote memory region, and * optionally an offset into it. This is how we implement RDMA into * unaligned memory. * When setting up the RDMA, we need to add that offset to the * destination address (which is really an offset into the MR) * FIXME: We may want to move this into ib_rdma.c */ op->op_rkey = rds_rdma_cookie_key(args->cookie); op->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie); nr_bytes = 0; rdsdebug("RDS: rdma prepare nr_local %llu rva %llx rkey %x\n", (unsigned long long)args->nr_local, (unsigned long long)args->remote_vec.addr, op->op_rkey); for (i = 0; i < args->nr_local; i++) { struct rds_iovec *iov = &iovs[i]; /* don't need to check, rds_rdma_pages() verified nr will be +nonzero */ unsigned int nr = rds_pages_in_vec(iov); rs->rs_user_addr = iov->addr; rs->rs_user_bytes = iov->bytes; /* If it's a WRITE operation, we want to pin the pages for reading. * If it's a READ operation, we need to pin the pages for writing. */ ret = rds_pin_pages(iov->addr, nr, pages, !op->op_write); if (ret < 0) goto out; else ret = 0; rdsdebug("RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\n", nr_bytes, nr, iov->bytes, iov->addr); nr_bytes += iov->bytes; for (j = 0; j < nr; j++) { unsigned int offset = iov->addr & ~PAGE_MASK; struct scatterlist *sg; sg = &op->op_sg[op->op_nents + j]; sg_set_page(sg, pages[j], min_t(unsigned int, iov->bytes, PAGE_SIZE - offset), offset); rdsdebug("RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\n", sg->offset, sg->length, iov->addr, iov->bytes); iov->addr += sg->length; iov->bytes -= sg->length; } op->op_nents += nr; } if (nr_bytes > args->remote_vec.bytes) { rdsdebug("RDS nr_bytes %u remote_bytes %u do not match\n", nr_bytes, (unsigned int) args->remote_vec.bytes); ret = -EINVAL; goto out; } op->op_bytes = nr_bytes; out: if (iovs != iovstack) sock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size); kfree(pages); out_ret: if (ret) rds_rdma_free_op(op); else rds_stats_inc(s_send_rdma); return ret; } /* * The application wants us to pass an RDMA destination (aka MR) * to the remote */ int rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { unsigned long flags; struct rds_mr *mr; u32 r_key; int err = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) || rm->m_rdma_cookie != 0) return -EINVAL; memcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie)); /* We are reusing a previously mapped MR here. Most likely, the * application has written to the buffer, so we need to explicitly * flush those writes to RAM. Otherwise the HCA may not see them * when doing a DMA from that buffer. */ r_key = rds_rdma_cookie_key(rm->m_rdma_cookie); spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL); if (!mr) err = -EINVAL; /* invalid r_key */ else refcount_inc(&mr->r_refcount); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (mr) { mr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE); rm->rdma.op_rdma_mr = mr; } return err; } /* * The application passes us an address range it wants to enable RDMA * to/from. We map the area, and save the <R_Key,offset> pair * in rm->m_rdma_cookie. This causes it to be sent along to the peer * in an extension header. */ int rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) || rm->m_rdma_cookie != 0) return -EINVAL; return __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr); } /* * Fill in rds_message for an atomic request. */ int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); kfree(rm->atomic.op_notifier); return ret; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_635_0
crossvul-cpp_data_good_4834_0
/********************************************************************\ * BitlBee -- An IRC to other IM-networks gateway * * * * Copyright 2010 Wilmer van der Gaast <wilmer@gaast.net> * \********************************************************************/ /* 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 with the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL; if not, write to the Free Software Foundation, Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110-1301 USA */ #define BITLBEE_CORE #include "bitlbee.h" #include "ft.h" file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start && bu) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } } gboolean imcb_file_recv_start(struct im_connection *ic, file_transfer_t *ft) { bee_t *bee = ic->bee; if (bee->ui->ft_out_start) { return bee->ui->ft_out_start(ic, ft); } else { return FALSE; } } void imcb_file_canceled(struct im_connection *ic, file_transfer_t *file, char *reason) { bee_t *bee = ic->bee; if (file->canceled) { file->canceled(file, reason); } if (bee->ui->ft_close) { bee->ui->ft_close(ic, file); } } void imcb_file_finished(struct im_connection *ic, file_transfer_t *file) { bee_t *bee = ic->bee; if (bee->ui->ft_finished) { bee->ui->ft_finished(ic, file); } }
./CrossVul/dataset_final_sorted/CWE-476/c/good_4834_0
crossvul-cpp_data_bad_61_0
/*- * Copyright (c) 2003-2010 Tim Kientzle * Copyright (c) 2016 Martin Matuska * 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(S) ``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(S) 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 "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_WCHAR_H #include <wchar.h> #endif #include "archive_acl_private.h" #include "archive_entry.h" #include "archive_private.h" #undef max #define max(a, b) ((a)>(b)?(a):(b)) #ifndef HAVE_WMEMCMP /* Good enough for simple equality testing, but not for sorting. */ #define wmemcmp(a,b,i) memcmp((a), (b), (i) * sizeof(wchar_t)) #endif static int acl_special(struct archive_acl *acl, int type, int permset, int tag); static struct archive_acl_entry *acl_new_entry(struct archive_acl *acl, int type, int permset, int tag, int id); static int archive_acl_add_entry_len_l(struct archive_acl *acl, int type, int permset, int tag, int id, const char *name, size_t len, struct archive_string_conv *sc); static int archive_acl_text_want_type(struct archive_acl *acl, int flags); static ssize_t archive_acl_text_len(struct archive_acl *acl, int want_type, int flags, int wide, struct archive *a, struct archive_string_conv *sc); static int isint_w(const wchar_t *start, const wchar_t *end, int *result); static int ismode_w(const wchar_t *start, const wchar_t *end, int *result); static int is_nfs4_flags_w(const wchar_t *start, const wchar_t *end, int *result); static int is_nfs4_perms_w(const wchar_t *start, const wchar_t *end, int *result); static void next_field_w(const wchar_t **wp, const wchar_t **start, const wchar_t **end, wchar_t *sep); static void append_entry_w(wchar_t **wp, const wchar_t *prefix, int type, int tag, int flags, const wchar_t *wname, int perm, int id); static void append_id_w(wchar_t **wp, int id); static int isint(const char *start, const char *end, int *result); static int ismode(const char *start, const char *end, int *result); static int is_nfs4_flags(const char *start, const char *end, int *result); static int is_nfs4_perms(const char *start, const char *end, int *result); static void next_field(const char **p, const char **start, const char **end, char *sep); static void append_entry(char **p, const char *prefix, int type, int tag, int flags, const char *name, int perm, int id); static void append_id(char **p, int id); static const struct { const int perm; const char c; const wchar_t wc; } nfsv4_acl_perm_map[] = { { ARCHIVE_ENTRY_ACL_READ_DATA | ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, 'r', L'r' }, { ARCHIVE_ENTRY_ACL_WRITE_DATA | ARCHIVE_ENTRY_ACL_ADD_FILE, 'w', L'w' }, { ARCHIVE_ENTRY_ACL_EXECUTE, 'x', L'x' }, { ARCHIVE_ENTRY_ACL_APPEND_DATA | ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, 'p', L'p' }, { ARCHIVE_ENTRY_ACL_DELETE, 'd', L'd' }, { ARCHIVE_ENTRY_ACL_DELETE_CHILD, 'D', L'D' }, { ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, 'a', L'a' }, { ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, 'A', L'A' }, { ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, 'R', L'R' }, { ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, 'W', L'W' }, { ARCHIVE_ENTRY_ACL_READ_ACL, 'c', L'c' }, { ARCHIVE_ENTRY_ACL_WRITE_ACL, 'C', L'C' }, { ARCHIVE_ENTRY_ACL_WRITE_OWNER, 'o', L'o' }, { ARCHIVE_ENTRY_ACL_SYNCHRONIZE, 's', L's' } }; static const int nfsv4_acl_perm_map_size = (int)(sizeof(nfsv4_acl_perm_map) / sizeof(nfsv4_acl_perm_map[0])); static const struct { const int perm; const char c; const wchar_t wc; } nfsv4_acl_flag_map[] = { { ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, 'f', L'f' }, { ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, 'd', L'd' }, { ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, 'i', L'i' }, { ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, 'n', L'n' }, { ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, 'S', L'S' }, { ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, 'F', L'F' }, { ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, 'I', L'I' } }; static const int nfsv4_acl_flag_map_size = (int)(sizeof(nfsv4_acl_flag_map) / sizeof(nfsv4_acl_flag_map[0])); void archive_acl_clear(struct archive_acl *acl) { struct archive_acl_entry *ap; while (acl->acl_head != NULL) { ap = acl->acl_head->next; archive_mstring_clean(&acl->acl_head->name); free(acl->acl_head); acl->acl_head = ap; } if (acl->acl_text_w != NULL) { free(acl->acl_text_w); acl->acl_text_w = NULL; } if (acl->acl_text != NULL) { free(acl->acl_text); acl->acl_text = NULL; } acl->acl_p = NULL; acl->acl_types = 0; acl->acl_state = 0; /* Not counting. */ } void archive_acl_copy(struct archive_acl *dest, struct archive_acl *src) { struct archive_acl_entry *ap, *ap2; archive_acl_clear(dest); dest->mode = src->mode; ap = src->acl_head; while (ap != NULL) { ap2 = acl_new_entry(dest, ap->type, ap->permset, ap->tag, ap->id); if (ap2 != NULL) archive_mstring_copy(&ap2->name, &ap->name); ap = ap->next; } } int archive_acl_add_entry(struct archive_acl *acl, int type, int permset, int tag, int id, const char *name) { struct archive_acl_entry *ap; if (acl_special(acl, type, permset, tag) == 0) return ARCHIVE_OK; ap = acl_new_entry(acl, type, permset, tag, id); if (ap == NULL) { /* XXX Error XXX */ return ARCHIVE_FAILED; } if (name != NULL && *name != '\0') archive_mstring_copy_mbs(&ap->name, name); else archive_mstring_clean(&ap->name); return ARCHIVE_OK; } int archive_acl_add_entry_w_len(struct archive_acl *acl, int type, int permset, int tag, int id, const wchar_t *name, size_t len) { struct archive_acl_entry *ap; if (acl_special(acl, type, permset, tag) == 0) return ARCHIVE_OK; ap = acl_new_entry(acl, type, permset, tag, id); if (ap == NULL) { /* XXX Error XXX */ return ARCHIVE_FAILED; } if (name != NULL && *name != L'\0' && len > 0) archive_mstring_copy_wcs_len(&ap->name, name, len); else archive_mstring_clean(&ap->name); return ARCHIVE_OK; } static int archive_acl_add_entry_len_l(struct archive_acl *acl, int type, int permset, int tag, int id, const char *name, size_t len, struct archive_string_conv *sc) { struct archive_acl_entry *ap; int r; if (acl_special(acl, type, permset, tag) == 0) return ARCHIVE_OK; ap = acl_new_entry(acl, type, permset, tag, id); if (ap == NULL) { /* XXX Error XXX */ return ARCHIVE_FAILED; } if (name != NULL && *name != '\0' && len > 0) { r = archive_mstring_copy_mbs_len_l(&ap->name, name, len, sc); } else { r = 0; archive_mstring_clean(&ap->name); } if (r == 0) return (ARCHIVE_OK); else if (errno == ENOMEM) return (ARCHIVE_FATAL); else return (ARCHIVE_WARN); } /* * If this ACL entry is part of the standard POSIX permissions set, * store the permissions in the stat structure and return zero. */ static int acl_special(struct archive_acl *acl, int type, int permset, int tag) { if (type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS && ((permset & ~007) == 0)) { switch (tag) { case ARCHIVE_ENTRY_ACL_USER_OBJ: acl->mode &= ~0700; acl->mode |= (permset & 7) << 6; return (0); case ARCHIVE_ENTRY_ACL_GROUP_OBJ: acl->mode &= ~0070; acl->mode |= (permset & 7) << 3; return (0); case ARCHIVE_ENTRY_ACL_OTHER: acl->mode &= ~0007; acl->mode |= permset & 7; return (0); } } return (1); } /* * Allocate and populate a new ACL entry with everything but the * name. */ static struct archive_acl_entry * acl_new_entry(struct archive_acl *acl, int type, int permset, int tag, int id) { struct archive_acl_entry *ap, *aq; /* Type argument must be a valid NFS4 or POSIX.1e type. * The type must agree with anything already set and * the permset must be compatible. */ if (type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) { if (acl->acl_types & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) { return (NULL); } if (permset & ~(ARCHIVE_ENTRY_ACL_PERMS_NFS4 | ARCHIVE_ENTRY_ACL_INHERITANCE_NFS4)) { return (NULL); } } else if (type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) { if (acl->acl_types & ~ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) { return (NULL); } if (permset & ~ARCHIVE_ENTRY_ACL_PERMS_POSIX1E) { return (NULL); } } else { return (NULL); } /* Verify the tag is valid and compatible with NFS4 or POSIX.1e. */ switch (tag) { case ARCHIVE_ENTRY_ACL_USER: case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: /* Tags valid in both NFS4 and POSIX.1e */ break; case ARCHIVE_ENTRY_ACL_MASK: case ARCHIVE_ENTRY_ACL_OTHER: /* Tags valid only in POSIX.1e. */ if (type & ~ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) { return (NULL); } break; case ARCHIVE_ENTRY_ACL_EVERYONE: /* Tags valid only in NFS4. */ if (type & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) { return (NULL); } break; default: /* No other values are valid. */ return (NULL); } if (acl->acl_text_w != NULL) { free(acl->acl_text_w); acl->acl_text_w = NULL; } if (acl->acl_text != NULL) { free(acl->acl_text); acl->acl_text = NULL; } /* * If there's a matching entry already in the list, overwrite it. * NFSv4 entries may be repeated and are not overwritten. * * TODO: compare names of no id is provided (needs more rework) */ ap = acl->acl_head; aq = NULL; while (ap != NULL) { if (((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) == 0) && ap->type == type && ap->tag == tag && ap->id == id) { if (id != -1 || (tag != ARCHIVE_ENTRY_ACL_USER && tag != ARCHIVE_ENTRY_ACL_GROUP)) { ap->permset = permset; return (ap); } } aq = ap; ap = ap->next; } /* Add a new entry to the end of the list. */ ap = (struct archive_acl_entry *)calloc(1, sizeof(*ap)); if (ap == NULL) return (NULL); if (aq == NULL) acl->acl_head = ap; else aq->next = ap; ap->type = type; ap->tag = tag; ap->id = id; ap->permset = permset; acl->acl_types |= type; return (ap); } /* * Return a count of entries matching "want_type". */ int archive_acl_count(struct archive_acl *acl, int want_type) { int count; struct archive_acl_entry *ap; count = 0; ap = acl->acl_head; while (ap != NULL) { if ((ap->type & want_type) != 0) count++; ap = ap->next; } if (count > 0 && ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0)) count += 3; return (count); } /* * Return a bitmask of stored ACL types in an ACL list */ int archive_acl_types(struct archive_acl *acl) { return (acl->acl_types); } /* * Prepare for reading entries from the ACL data. Returns a count * of entries matching "want_type", or zero if there are no * non-extended ACL entries of that type. */ int archive_acl_reset(struct archive_acl *acl, int want_type) { int count, cutoff; count = archive_acl_count(acl, want_type); /* * If the only entries are the three standard ones, * then don't return any ACL data. (In this case, * client can just use chmod(2) to set permissions.) */ if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) cutoff = 3; else cutoff = 0; if (count > cutoff) acl->acl_state = ARCHIVE_ENTRY_ACL_USER_OBJ; else acl->acl_state = 0; acl->acl_p = acl->acl_head; return (count); } /* * Return the next ACL entry in the list. Fake entries for the * standard permissions and include them in the returned list. */ int archive_acl_next(struct archive *a, struct archive_acl *acl, int want_type, int *type, int *permset, int *tag, int *id, const char **name) { *name = NULL; *id = -1; /* * The acl_state is either zero (no entries available), -1 * (reading from list), or an entry type (retrieve that type * from ae_stat.aest_mode). */ if (acl->acl_state == 0) return (ARCHIVE_WARN); /* The first three access entries are special. */ if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { switch (acl->acl_state) { case ARCHIVE_ENTRY_ACL_USER_OBJ: *permset = (acl->mode >> 6) & 7; *type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; *tag = ARCHIVE_ENTRY_ACL_USER_OBJ; acl->acl_state = ARCHIVE_ENTRY_ACL_GROUP_OBJ; return (ARCHIVE_OK); case ARCHIVE_ENTRY_ACL_GROUP_OBJ: *permset = (acl->mode >> 3) & 7; *type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; *tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; acl->acl_state = ARCHIVE_ENTRY_ACL_OTHER; return (ARCHIVE_OK); case ARCHIVE_ENTRY_ACL_OTHER: *permset = acl->mode & 7; *type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; *tag = ARCHIVE_ENTRY_ACL_OTHER; acl->acl_state = -1; acl->acl_p = acl->acl_head; return (ARCHIVE_OK); default: break; } } while (acl->acl_p != NULL && (acl->acl_p->type & want_type) == 0) acl->acl_p = acl->acl_p->next; if (acl->acl_p == NULL) { acl->acl_state = 0; *type = 0; *permset = 0; *tag = 0; *id = -1; *name = NULL; return (ARCHIVE_EOF); /* End of ACL entries. */ } *type = acl->acl_p->type; *permset = acl->acl_p->permset; *tag = acl->acl_p->tag; *id = acl->acl_p->id; if (archive_mstring_get_mbs(a, &acl->acl_p->name, name) != 0) { if (errno == ENOMEM) return (ARCHIVE_FATAL); *name = NULL; } acl->acl_p = acl->acl_p->next; return (ARCHIVE_OK); } /* * Determine what type of ACL do we want */ static int archive_acl_text_want_type(struct archive_acl *acl, int flags) { int want_type; /* Check if ACL is NFSv4 */ if ((acl->acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { /* NFSv4 should never mix with POSIX.1e */ if ((acl->acl_types & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) return (0); else return (ARCHIVE_ENTRY_ACL_TYPE_NFS4); } /* Now deal with POSIX.1e ACLs */ want_type = 0; if ((flags & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) want_type |= ARCHIVE_ENTRY_ACL_TYPE_ACCESS; if ((flags & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) want_type |= ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; /* By default we want both access and default ACLs */ if (want_type == 0) return (ARCHIVE_ENTRY_ACL_TYPE_POSIX1E); return (want_type); } /* * Calculate ACL text string length */ static ssize_t archive_acl_text_len(struct archive_acl *acl, int want_type, int flags, int wide, struct archive *a, struct archive_string_conv *sc) { struct archive_acl_entry *ap; const char *name; const wchar_t *wname; int count, idlen, tmp, r; ssize_t length; size_t len; count = 0; length = 0; for (ap = acl->acl_head; ap != NULL; ap = ap->next) { if ((ap->type & want_type) == 0) continue; /* * Filemode-mapping ACL entries are stored exclusively in * ap->mode so they should not be in the list */ if ((ap->type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) && (ap->tag == ARCHIVE_ENTRY_ACL_USER_OBJ || ap->tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ || ap->tag == ARCHIVE_ENTRY_ACL_OTHER)) continue; count++; if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0 && (ap->type & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0) length += 8; /* "default:" */ switch (ap->tag) { case ARCHIVE_ENTRY_ACL_USER_OBJ: if (want_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { length += 6; /* "owner@" */ break; } /* FALLTHROUGH */ case ARCHIVE_ENTRY_ACL_USER: case ARCHIVE_ENTRY_ACL_MASK: length += 4; /* "user", "mask" */ break; case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (want_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { length += 6; /* "group@" */ break; } /* FALLTHROUGH */ case ARCHIVE_ENTRY_ACL_GROUP: case ARCHIVE_ENTRY_ACL_OTHER: length += 5; /* "group", "other" */ break; case ARCHIVE_ENTRY_ACL_EVERYONE: length += 9; /* "everyone@" */ break; } length += 1; /* colon after tag */ if (ap->tag == ARCHIVE_ENTRY_ACL_USER || ap->tag == ARCHIVE_ENTRY_ACL_GROUP) { if (wide) { r = archive_mstring_get_wcs(a, &ap->name, &wname); if (r == 0 && wname != NULL) length += wcslen(wname); else if (r < 0 && errno == ENOMEM) return (0); else length += sizeof(uid_t) * 3 + 1; } else { r = archive_mstring_get_mbs_l(&ap->name, &name, &len, sc); if (r != 0) return (0); if (len > 0 && name != NULL) length += len; else length += sizeof(uid_t) * 3 + 1; } length += 1; /* colon after user or group name */ } else if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) length += 1; /* 2nd colon empty user,group or other */ if (((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) != 0) && ((want_type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) && (ap->tag == ARCHIVE_ENTRY_ACL_OTHER || ap->tag == ARCHIVE_ENTRY_ACL_MASK)) { /* Solaris has no colon after other: and mask: */ length = length - 1; } if (want_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* rwxpdDaARWcCos:fdinSFI:deny */ length += 27; if ((ap->type & ARCHIVE_ENTRY_ACL_TYPE_DENY) == 0) length += 1; /* allow, alarm, audit */ } else length += 3; /* rwx */ if ((ap->tag == ARCHIVE_ENTRY_ACL_USER || ap->tag == ARCHIVE_ENTRY_ACL_GROUP) && (flags & ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID) != 0) { length += 1; /* colon */ /* ID digit count */ idlen = 1; tmp = ap->id; while (tmp > 9) { tmp = tmp / 10; idlen++; } length += idlen; } length ++; /* entry separator */ } /* Add filemode-mapping access entries to the length */ if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { if ((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) != 0) { /* "user::rwx\ngroup::rwx\nother:rwx\n" */ length += 31; } else { /* "user::rwx\ngroup::rwx\nother::rwx\n" */ length += 32; } } else if (count == 0) return (0); /* The terminating character is included in count */ return (length); } /* * Generate a wide text version of the ACL. The flags parameter controls * the type and style of the generated ACL. */ wchar_t * archive_acl_to_text_w(struct archive_acl *acl, ssize_t *text_len, int flags, struct archive *a) { int count; ssize_t length; size_t len; const wchar_t *wname; const wchar_t *prefix; wchar_t separator; struct archive_acl_entry *ap; int id, r, want_type; wchar_t *wp, *ws; want_type = archive_acl_text_want_type(acl, flags); /* Both NFSv4 and POSIX.1 types found */ if (want_type == 0) return (NULL); if (want_type == ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) flags |= ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT; length = archive_acl_text_len(acl, want_type, flags, 1, a, NULL); if (length == 0) return (NULL); if (flags & ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA) separator = L','; else separator = L'\n'; /* Now, allocate the string and actually populate it. */ wp = ws = (wchar_t *)malloc(length * sizeof(wchar_t)); if (wp == NULL) { if (errno == ENOMEM) __archive_errx(1, "No memory"); return (NULL); } count = 0; if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { append_entry_w(&wp, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_USER_OBJ, flags, NULL, acl->mode & 0700, -1); *wp++ = separator; append_entry_w(&wp, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_GROUP_OBJ, flags, NULL, acl->mode & 0070, -1); *wp++ = separator; append_entry_w(&wp, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_OTHER, flags, NULL, acl->mode & 0007, -1); count += 3; } for (ap = acl->acl_head; ap != NULL; ap = ap->next) { if ((ap->type & want_type) == 0) continue; /* * Filemode-mapping ACL entries are stored exclusively in * ap->mode so they should not be in the list */ if ((ap->type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) && (ap->tag == ARCHIVE_ENTRY_ACL_USER_OBJ || ap->tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ || ap->tag == ARCHIVE_ENTRY_ACL_OTHER)) continue; if (ap->type == ARCHIVE_ENTRY_ACL_TYPE_DEFAULT && (flags & ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT) != 0) prefix = L"default:"; else prefix = NULL; r = archive_mstring_get_wcs(a, &ap->name, &wname); if (r == 0) { if (count > 0) *wp++ = separator; if (flags & ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID) id = ap->id; else id = -1; append_entry_w(&wp, prefix, ap->type, ap->tag, flags, wname, ap->permset, id); count++; } else if (r < 0 && errno == ENOMEM) { free(ws); return (NULL); } } /* Add terminating character */ *wp++ = L'\0'; len = wcslen(ws); if ((ssize_t)len > (length - 1)) __archive_errx(1, "Buffer overrun"); if (text_len != NULL) *text_len = len; return (ws); } static void append_id_w(wchar_t **wp, int id) { if (id < 0) id = 0; if (id > 9) append_id_w(wp, id / 10); *(*wp)++ = L"0123456789"[id % 10]; } static void append_entry_w(wchar_t **wp, const wchar_t *prefix, int type, int tag, int flags, const wchar_t *wname, int perm, int id) { int i; if (prefix != NULL) { wcscpy(*wp, prefix); *wp += wcslen(*wp); } switch (tag) { case ARCHIVE_ENTRY_ACL_USER_OBJ: wname = NULL; id = -1; if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { wcscpy(*wp, L"owner@"); break; } /* FALLTHROUGH */ case ARCHIVE_ENTRY_ACL_USER: wcscpy(*wp, L"user"); break; case ARCHIVE_ENTRY_ACL_GROUP_OBJ: wname = NULL; id = -1; if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { wcscpy(*wp, L"group@"); break; } /* FALLTHROUGH */ case ARCHIVE_ENTRY_ACL_GROUP: wcscpy(*wp, L"group"); break; case ARCHIVE_ENTRY_ACL_MASK: wcscpy(*wp, L"mask"); wname = NULL; id = -1; break; case ARCHIVE_ENTRY_ACL_OTHER: wcscpy(*wp, L"other"); wname = NULL; id = -1; break; case ARCHIVE_ENTRY_ACL_EVERYONE: wcscpy(*wp, L"everyone@"); wname = NULL; id = -1; break; } *wp += wcslen(*wp); *(*wp)++ = L':'; if (((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) || tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { if (wname != NULL) { wcscpy(*wp, wname); *wp += wcslen(*wp); } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { append_id_w(wp, id); if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) == 0) id = -1; } /* Solaris style has no second colon after other and mask */ if (((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) == 0) || (tag != ARCHIVE_ENTRY_ACL_OTHER && tag != ARCHIVE_ENTRY_ACL_MASK)) *(*wp)++ = L':'; } if ((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { /* POSIX.1e ACL perms */ *(*wp)++ = (perm & 0444) ? L'r' : L'-'; *(*wp)++ = (perm & 0222) ? L'w' : L'-'; *(*wp)++ = (perm & 0111) ? L'x' : L'-'; } else { /* NFSv4 ACL perms */ for (i = 0; i < nfsv4_acl_perm_map_size; i++) { if (perm & nfsv4_acl_perm_map[i].perm) *(*wp)++ = nfsv4_acl_perm_map[i].wc; else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) *(*wp)++ = L'-'; } *(*wp)++ = L':'; for (i = 0; i < nfsv4_acl_flag_map_size; i++) { if (perm & nfsv4_acl_flag_map[i].perm) *(*wp)++ = nfsv4_acl_flag_map[i].wc; else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) *(*wp)++ = L'-'; } *(*wp)++ = L':'; switch (type) { case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: wcscpy(*wp, L"allow"); break; case ARCHIVE_ENTRY_ACL_TYPE_DENY: wcscpy(*wp, L"deny"); break; case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: wcscpy(*wp, L"audit"); break; case ARCHIVE_ENTRY_ACL_TYPE_ALARM: wcscpy(*wp, L"alarm"); break; default: break; } *wp += wcslen(*wp); } if (id != -1) { *(*wp)++ = L':'; append_id_w(wp, id); } } /* * Generate a text version of the ACL. The flags parameter controls * the type and style of the generated ACL. */ char * archive_acl_to_text_l(struct archive_acl *acl, ssize_t *text_len, int flags, struct archive_string_conv *sc) { int count; ssize_t length; size_t len; const char *name; const char *prefix; char separator; struct archive_acl_entry *ap; int id, r, want_type; char *p, *s; want_type = archive_acl_text_want_type(acl, flags); /* Both NFSv4 and POSIX.1 types found */ if (want_type == 0) return (NULL); if (want_type == ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) flags |= ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT; length = archive_acl_text_len(acl, want_type, flags, 0, NULL, sc); if (length == 0) return (NULL); if (flags & ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA) separator = ','; else separator = '\n'; /* Now, allocate the string and actually populate it. */ p = s = (char *)malloc(length * sizeof(char)); if (p == NULL) { if (errno == ENOMEM) __archive_errx(1, "No memory"); return (NULL); } count = 0; if ((want_type & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) { append_entry(&p, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_USER_OBJ, flags, NULL, acl->mode & 0700, -1); *p++ = separator; append_entry(&p, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_GROUP_OBJ, flags, NULL, acl->mode & 0070, -1); *p++ = separator; append_entry(&p, NULL, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_OTHER, flags, NULL, acl->mode & 0007, -1); count += 3; } for (ap = acl->acl_head; ap != NULL; ap = ap->next) { if ((ap->type & want_type) == 0) continue; /* * Filemode-mapping ACL entries are stored exclusively in * ap->mode so they should not be in the list */ if ((ap->type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) && (ap->tag == ARCHIVE_ENTRY_ACL_USER_OBJ || ap->tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ || ap->tag == ARCHIVE_ENTRY_ACL_OTHER)) continue; if (ap->type == ARCHIVE_ENTRY_ACL_TYPE_DEFAULT && (flags & ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT) != 0) prefix = "default:"; else prefix = NULL; r = archive_mstring_get_mbs_l( &ap->name, &name, &len, sc); if (r != 0) { free(s); return (NULL); } if (count > 0) *p++ = separator; if (name == NULL || (flags & ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID)) { id = ap->id; } else { id = -1; } append_entry(&p, prefix, ap->type, ap->tag, flags, name, ap->permset, id); count++; } /* Add terminating character */ *p++ = '\0'; len = strlen(s); if ((ssize_t)len > (length - 1)) __archive_errx(1, "Buffer overrun"); if (text_len != NULL) *text_len = len; return (s); } static void append_id(char **p, int id) { if (id < 0) id = 0; if (id > 9) append_id(p, id / 10); *(*p)++ = "0123456789"[id % 10]; } static void append_entry(char **p, const char *prefix, int type, int tag, int flags, const char *name, int perm, int id) { int i; if (prefix != NULL) { strcpy(*p, prefix); *p += strlen(*p); } switch (tag) { case ARCHIVE_ENTRY_ACL_USER_OBJ: name = NULL; id = -1; if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { strcpy(*p, "owner@"); break; } /* FALLTHROUGH */ case ARCHIVE_ENTRY_ACL_USER: strcpy(*p, "user"); break; case ARCHIVE_ENTRY_ACL_GROUP_OBJ: name = NULL; id = -1; if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) { strcpy(*p, "group@"); break; } /* FALLTHROUGH */ case ARCHIVE_ENTRY_ACL_GROUP: strcpy(*p, "group"); break; case ARCHIVE_ENTRY_ACL_MASK: strcpy(*p, "mask"); name = NULL; id = -1; break; case ARCHIVE_ENTRY_ACL_OTHER: strcpy(*p, "other"); name = NULL; id = -1; break; case ARCHIVE_ENTRY_ACL_EVERYONE: strcpy(*p, "everyone@"); name = NULL; id = -1; break; } *p += strlen(*p); *(*p)++ = ':'; if (((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) || tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { if (name != NULL) { strcpy(*p, name); *p += strlen(*p); } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { append_id(p, id); if ((type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) == 0) id = -1; } /* Solaris style has no second colon after other and mask */ if (((flags & ARCHIVE_ENTRY_ACL_STYLE_SOLARIS) == 0) || (tag != ARCHIVE_ENTRY_ACL_OTHER && tag != ARCHIVE_ENTRY_ACL_MASK)) *(*p)++ = ':'; } if ((type & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) { /* POSIX.1e ACL perms */ *(*p)++ = (perm & 0444) ? 'r' : '-'; *(*p)++ = (perm & 0222) ? 'w' : '-'; *(*p)++ = (perm & 0111) ? 'x' : '-'; } else { /* NFSv4 ACL perms */ for (i = 0; i < nfsv4_acl_perm_map_size; i++) { if (perm & nfsv4_acl_perm_map[i].perm) *(*p)++ = nfsv4_acl_perm_map[i].c; else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) *(*p)++ = '-'; } *(*p)++ = ':'; for (i = 0; i < nfsv4_acl_flag_map_size; i++) { if (perm & nfsv4_acl_flag_map[i].perm) *(*p)++ = nfsv4_acl_flag_map[i].c; else if ((flags & ARCHIVE_ENTRY_ACL_STYLE_COMPACT) == 0) *(*p)++ = '-'; } *(*p)++ = ':'; switch (type) { case ARCHIVE_ENTRY_ACL_TYPE_ALLOW: strcpy(*p, "allow"); break; case ARCHIVE_ENTRY_ACL_TYPE_DENY: strcpy(*p, "deny"); break; case ARCHIVE_ENTRY_ACL_TYPE_AUDIT: strcpy(*p, "audit"); break; case ARCHIVE_ENTRY_ACL_TYPE_ALARM: strcpy(*p, "alarm"); break; } *p += strlen(*p); } if (id != -1) { *(*p)++ = ':'; append_id(p, id); } } /* * Parse a wide ACL text string. * * The want_type argument may be one of the following: * ARCHIVE_ENTRY_ACL_TYPE_ACCESS - text is a POSIX.1e ACL of type ACCESS * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT - text is a POSIX.1e ACL of type DEFAULT * ARCHIVE_ENTRY_ACL_TYPE_NFS4 - text is as a NFSv4 ACL * * POSIX.1e ACL entries prefixed with "default:" are treated as * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT unless type is ARCHIVE_ENTRY_ACL_TYPE_NFS4 */ int archive_acl_from_text_w(struct archive_acl *acl, const wchar_t *text, int want_type) { struct { const wchar_t *start; const wchar_t *end; } field[6], name; const wchar_t *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; wchar_t sep; ret = ARCHIVE_OK; types = 0; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } while (text != NULL && *text != L'\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const wchar_t *start, *end; next_field_w(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == L':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == L'#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword "default:user::rwx" * if found, we have one more field * * We also support old Solaris extension: * "defaultuser::rwx" is the default ACL corresponding * to "user::rwx", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == L'd' && (len == 1 || (len >= 7 && wmemcmp((s + 1), L"efault", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint_w(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > n+3) isint_w(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; switch (*s) { case L'u': if (len == 1 || (len == 4 && wmemcmp(st, L"ser", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case L'g': if (len == 1 || (len == 5 && wmemcmp(st, L"roup", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case L'o': if (len == 1 || (len == 5 && wmemcmp(st, L"ther", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case L'm': if (len == 1 || (len == 4 && wmemcmp(st, L"ask", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode_w(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style "other:rwx" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without "default:" we expect mode in field 2 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode_w(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (wmemcmp(s, L"user", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (wmemcmp(s, L"group", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (wmemcmp(s, L"owner@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (wmemcmp(s, L"group@", len) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (wmemcmp(s, L"everyone@", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint_w(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms_w(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags_w(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (wmemcmp(s, L"deny", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (wmemcmp(s, L"allow", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (wmemcmp(s, L"audit", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (wmemcmp(s, L"alarm", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint_w(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_w_len(acl, type, permset, tag, id, name.start, name.end - name.start); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); } /* * Parse a string to a positive decimal integer. Returns true if * the string is non-empty and consists only of decimal digits, * false otherwise. */ static int isint_w(const wchar_t *start, const wchar_t *end, int *result) { int n = 0; if (start >= end) return (0); while (start < end) { if (*start < '0' || *start > '9') return (0); if (n > (INT_MAX / 10) || (n == INT_MAX / 10 && (*start - '0') > INT_MAX % 10)) { n = INT_MAX; } else { n *= 10; n += *start - '0'; } start++; } *result = n; return (1); } /* * Parse a string as a mode field. Returns true if * the string is non-empty and consists only of mode characters, * false otherwise. */ static int ismode_w(const wchar_t *start, const wchar_t *end, int *permset) { const wchar_t *p; if (start >= end) return (0); p = start; *permset = 0; while (p < end) { switch (*p++) { case L'r': case L'R': *permset |= ARCHIVE_ENTRY_ACL_READ; break; case L'w': case L'W': *permset |= ARCHIVE_ENTRY_ACL_WRITE; break; case L'x': case L'X': *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; break; case L'-': break; default: return (0); } } return (1); } /* * Parse a string as a NFS4 ACL permission field. * Returns true if the string is non-empty and consists only of NFS4 ACL * permission characters, false otherwise */ static int is_nfs4_perms_w(const wchar_t *start, const wchar_t *end, int *permset) { const wchar_t *p = start; while (p < end) { switch (*p++) { case L'r': *permset |= ARCHIVE_ENTRY_ACL_READ_DATA; break; case L'w': *permset |= ARCHIVE_ENTRY_ACL_WRITE_DATA; break; case L'x': *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; break; case L'p': *permset |= ARCHIVE_ENTRY_ACL_APPEND_DATA; break; case L'D': *permset |= ARCHIVE_ENTRY_ACL_DELETE_CHILD; break; case L'd': *permset |= ARCHIVE_ENTRY_ACL_DELETE; break; case L'a': *permset |= ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES; break; case L'A': *permset |= ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES; break; case L'R': *permset |= ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS; break; case L'W': *permset |= ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS; break; case L'c': *permset |= ARCHIVE_ENTRY_ACL_READ_ACL; break; case L'C': *permset |= ARCHIVE_ENTRY_ACL_WRITE_ACL; break; case L'o': *permset |= ARCHIVE_ENTRY_ACL_WRITE_OWNER; break; case L's': *permset |= ARCHIVE_ENTRY_ACL_SYNCHRONIZE; break; case L'-': break; default: return(0); } } return (1); } /* * Parse a string as a NFS4 ACL flags field. * Returns true if the string is non-empty and consists only of NFS4 ACL * flag characters, false otherwise */ static int is_nfs4_flags_w(const wchar_t *start, const wchar_t *end, int *permset) { const wchar_t *p = start; while (p < end) { switch(*p++) { case L'f': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT; break; case L'd': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT; break; case L'i': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY; break; case L'n': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT; break; case L'S': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS; break; case L'F': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS; break; case L'I': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERITED; break; case L'-': break; default: return (0); } } return (1); } /* * Match "[:whitespace:]*(.*)[:whitespace:]*[:,\n]". *wp is updated * to point to just after the separator. *start points to the first * character of the matched text and *end just after the last * character of the matched identifier. In particular *end - *start * is the length of the field body, not including leading or trailing * whitespace. */ static void next_field_w(const wchar_t **wp, const wchar_t **start, const wchar_t **end, wchar_t *sep) { /* Skip leading whitespace to find start of field. */ while (**wp == L' ' || **wp == L'\t' || **wp == L'\n') { (*wp)++; } *start = *wp; /* Scan for the separator. */ while (**wp != L'\0' && **wp != L',' && **wp != L':' && **wp != L'\n' && **wp != L'#') { (*wp)++; } *sep = **wp; /* Locate end of field, trim trailing whitespace if necessary */ if (*wp == *start) { *end = *wp; } else { *end = *wp - 1; while (**end == L' ' || **end == L'\t' || **end == L'\n') { (*end)--; } (*end)++; } /* Handle in-field comments */ if (*sep == L'#') { while (**wp != L'\0' && **wp != L',' && **wp != L'\n') { (*wp)++; } *sep = **wp; } /* Adjust scanner location. */ if (**wp != L'\0') (*wp)++; } /* * Parse an ACL text string. * * The want_type argument may be one of the following: * ARCHIVE_ENTRY_ACL_TYPE_ACCESS - text is a POSIX.1e ACL of type ACCESS * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT - text is a POSIX.1e ACL of type DEFAULT * ARCHIVE_ENTRY_ACL_TYPE_NFS4 - text is as a NFSv4 ACL * * POSIX.1e ACL entries prefixed with "default:" are treated as * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT unless type is ARCHIVE_ENTRY_ACL_TYPE_NFS4 */ int archive_acl_from_text_l(struct archive_acl *acl, const char *text, int want_type, struct archive_string_conv *sc) { struct { const char *start; const char *end; } field[6], name; const char *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; char sep; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } ret = ARCHIVE_OK; types = 0; while (text != NULL && *text != '\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const char *start, *end; next_field(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == ':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == '#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword "default:user::rwx" * if found, we have one more field * * We also support old Solaris extension: * "defaultuser::rwx" is the default ACL corresponding * to "user::rwx", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == 'd' && (len == 1 || (len >= 7 && memcmp((s + 1), "efault", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > (n + 3)) isint(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; switch (*s) { case 'u': if (len == 1 || (len == 4 && memcmp(st, "ser", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case 'g': if (len == 1 || (len == 5 && memcmp(st, "roup", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 'o': if (len == 1 || (len == 5 && memcmp(st, "ther", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case 'm': if (len == 1 || (len == 4 && memcmp(st, "ask", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style "other:rwx" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without "default:" we expect mode in field 3 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (memcmp(s, "user", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (memcmp(s, "group", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (memcmp(s, "owner@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (memcmp(s, "group@", 6) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (memcmp(s, "everyone@", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; break; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (memcmp(s, "deny", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (memcmp(s, "allow", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (memcmp(s, "audit", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (memcmp(s, "alarm", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_len_l(acl, type, permset, tag, id, name.start, name.end - name.start, sc); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); } /* * Parse a string to a positive decimal integer. Returns true if * the string is non-empty and consists only of decimal digits, * false otherwise. */ static int isint(const char *start, const char *end, int *result) { int n = 0; if (start >= end) return (0); while (start < end) { if (*start < '0' || *start > '9') return (0); if (n > (INT_MAX / 10) || (n == INT_MAX / 10 && (*start - '0') > INT_MAX % 10)) { n = INT_MAX; } else { n *= 10; n += *start - '0'; } start++; } *result = n; return (1); } /* * Parse a string as a mode field. Returns true if * the string is non-empty and consists only of mode characters, * false otherwise. */ static int ismode(const char *start, const char *end, int *permset) { const char *p; if (start >= end) return (0); p = start; *permset = 0; while (p < end) { switch (*p++) { case 'r': case 'R': *permset |= ARCHIVE_ENTRY_ACL_READ; break; case 'w': case 'W': *permset |= ARCHIVE_ENTRY_ACL_WRITE; break; case 'x': case 'X': *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; break; case '-': break; default: return (0); } } return (1); } /* * Parse a string as a NFS4 ACL permission field. * Returns true if the string is non-empty and consists only of NFS4 ACL * permission characters, false otherwise */ static int is_nfs4_perms(const char *start, const char *end, int *permset) { const char *p = start; while (p < end) { switch (*p++) { case 'r': *permset |= ARCHIVE_ENTRY_ACL_READ_DATA; break; case 'w': *permset |= ARCHIVE_ENTRY_ACL_WRITE_DATA; break; case 'x': *permset |= ARCHIVE_ENTRY_ACL_EXECUTE; break; case 'p': *permset |= ARCHIVE_ENTRY_ACL_APPEND_DATA; break; case 'D': *permset |= ARCHIVE_ENTRY_ACL_DELETE_CHILD; break; case 'd': *permset |= ARCHIVE_ENTRY_ACL_DELETE; break; case 'a': *permset |= ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES; break; case 'A': *permset |= ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES; break; case 'R': *permset |= ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS; break; case 'W': *permset |= ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS; break; case 'c': *permset |= ARCHIVE_ENTRY_ACL_READ_ACL; break; case 'C': *permset |= ARCHIVE_ENTRY_ACL_WRITE_ACL; break; case 'o': *permset |= ARCHIVE_ENTRY_ACL_WRITE_OWNER; break; case 's': *permset |= ARCHIVE_ENTRY_ACL_SYNCHRONIZE; break; case '-': break; default: return(0); } } return (1); } /* * Parse a string as a NFS4 ACL flags field. * Returns true if the string is non-empty and consists only of NFS4 ACL * flag characters, false otherwise */ static int is_nfs4_flags(const char *start, const char *end, int *permset) { const char *p = start; while (p < end) { switch(*p++) { case 'f': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT; break; case 'd': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT; break; case 'i': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY; break; case 'n': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT; break; case 'S': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS; break; case 'F': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS; break; case 'I': *permset |= ARCHIVE_ENTRY_ACL_ENTRY_INHERITED; break; case '-': break; default: return (0); } } return (1); } /* * Match "[:whitespace:]*(.*)[:whitespace:]*[:,\n]". *wp is updated * to point to just after the separator. *start points to the first * character of the matched text and *end just after the last * character of the matched identifier. In particular *end - *start * is the length of the field body, not including leading or trailing * whitespace. */ static void next_field(const char **p, const char **start, const char **end, char *sep) { /* Skip leading whitespace to find start of field. */ while (**p == ' ' || **p == '\t' || **p == '\n') { (*p)++; } *start = *p; /* Scan for the separator. */ while (**p != '\0' && **p != ',' && **p != ':' && **p != '\n' && **p != '#') { (*p)++; } *sep = **p; /* Locate end of field, trim trailing whitespace if necessary */ if (*p == *start) { *end = *p; } else { *end = *p - 1; while (**end == ' ' || **end == '\t' || **end == '\n') { (*end)--; } (*end)++; } /* Handle in-field comments */ if (*sep == '#') { while (**p != '\0' && **p != ',' && **p != '\n') { (*p)++; } *sep = **p; } /* Adjust scanner location. */ if (**p != '\0') (*p)++; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_61_0
crossvul-cpp_data_bad_5485_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #ifdef __VMS #define JPEG_SUPPORT 1 #endif /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/profile.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread_.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *), WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *), WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(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 IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 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 ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged 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 ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(image,q)+0.5; if (b > 1.0) b-=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length,ExceptionInfo *exception) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping, ExceptionInfo *exception) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length,exception); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length, exception); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception); } static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text,exception); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text,exception); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text,exception); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text,exception); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text,exception); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text,exception); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text,exception); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text,exception); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MagickPathExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MagickPathExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value,exception); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif **value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* only support 8 bit for now */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG Marker */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; info.channels=(unsigned short) layers->number_channels; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown",exception); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric", exception)); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,image_info->ping,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,"tiff:exif-properties"); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MagickPathExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, "%dx%d",horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor,exception); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated", exception); } } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MagickPathExtent,"%u", (unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=(unsigned char *) GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image=DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties 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 RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MagickPathExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; entry->format_type=ImplicitFormatType; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags|=CoderStealthFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); RelinquishSemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image,ExceptionInfo *) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType,exception); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1,exception); (void) SetImageType(image,BilevelType,exception); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image,exception); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution=next->resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2; resolution.y/=2; pyramid_image=ResizeImage(next,columns,rows,image->filter,exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->resolution=resolution; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE", exception); AppendImageToList(&images,pyramid_image); } } images=GetFirstImageInList(images); /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent); (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent); status=WriteTIFFImage(write_info,images,exception); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(image,q)-0.5; if (b < 0.0) b+=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info, TIFF *tiff,TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { uint32 rows_per_strip; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); else if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0) rows_per_strip=0; /* use default */ rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } /* Create tiled TIFF, ignore "tiff:rows-per-strip". */ flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) ( tiff_info->tile_geometry.height*tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property,exception); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5485_1
crossvul-cpp_data_good_2852_0
/* Userspace key control operations * * Copyright (C) 2004-5 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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/sched/task.h> #include <linux/slab.h> #include <linux/syscalls.h> #include <linux/key.h> #include <linux/keyctl.h> #include <linux/fs.h> #include <linux/capability.h> #include <linux/cred.h> #include <linux/string.h> #include <linux/err.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/uio.h> #include <linux/uaccess.h> #include "internal.h" #define KEY_MAX_DESC_SIZE 4096 static int key_get_type_from_user(char *type, const char __user *_type, unsigned len) { int ret; ret = strncpy_from_user(type, _type, len); if (ret < 0) return ret; if (ret == 0 || ret >= len) return -EINVAL; if (type[0] == '.') return -EPERM; type[len - 1] = '\0'; return 0; } /* * Extract the description of a new key from userspace and either add it as a * new key to the specified keyring or update a matching key in that keyring. * * If the description is NULL or an empty string, the key type is asked to * generate one from the payload. * * The keyring must be writable so that we can attach the key to it. * * If successful, the new key's serial number is returned, otherwise an error * code is returned. */ SYSCALL_DEFINE5(add_key, const char __user *, _type, const char __user *, _description, const void __user *, _payload, size_t, plen, key_serial_t, ringid) { key_ref_t keyring_ref, key_ref; char type[32], *description; void *payload; long ret; ret = -EINVAL; if (plen > 1024 * 1024 - 1) goto error; /* draw all the data into kernel space */ ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; description = NULL; if (_description) { description = strndup_user(_description, KEY_MAX_DESC_SIZE); if (IS_ERR(description)) { ret = PTR_ERR(description); goto error; } if (!*description) { kfree(description); description = NULL; } else if ((description[0] == '.') && (strncmp(type, "keyring", 7) == 0)) { ret = -EPERM; goto error2; } } /* pull the payload in if one was supplied */ payload = NULL; if (plen) { ret = -ENOMEM; payload = kvmalloc(plen, GFP_KERNEL); if (!payload) goto error2; ret = -EFAULT; if (copy_from_user(payload, _payload, plen) != 0) goto error3; } /* find the target keyring (which must be writable) */ keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error3; } /* create or update the requested key and add it to the target * keyring */ key_ref = key_create_or_update(keyring_ref, type, description, payload, plen, KEY_PERM_UNDEF, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key_ref)) { ret = key_ref_to_ptr(key_ref)->serial; key_ref_put(key_ref); } else { ret = PTR_ERR(key_ref); } key_ref_put(keyring_ref); error3: kvfree(payload); error2: kfree(description); error: return ret; } /* * Search the process keyrings and keyring trees linked from those for a * matching key. Keyrings must have appropriate Search permission to be * searched. * * If a key is found, it will be attached to the destination keyring if there's * one specified and the serial number of the key will be returned. * * If no key is found, /sbin/request-key will be invoked if _callout_info is * non-NULL in an attempt to create a key. The _callout_info string will be * passed to /sbin/request-key to aid with completing the request. If the * _callout_info string is "" then it will be changed to "-". */ SYSCALL_DEFINE4(request_key, const char __user *, _type, const char __user *, _description, const char __user *, _callout_info, key_serial_t, destringid) { struct key_type *ktype; struct key *key; key_ref_t dest_ref; size_t callout_len; char type[32], *description, *callout_info; long ret; /* pull the type into kernel space */ ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; /* pull the description into kernel space */ description = strndup_user(_description, KEY_MAX_DESC_SIZE); if (IS_ERR(description)) { ret = PTR_ERR(description); goto error; } /* pull the callout info into kernel space */ callout_info = NULL; callout_len = 0; if (_callout_info) { callout_info = strndup_user(_callout_info, PAGE_SIZE); if (IS_ERR(callout_info)) { ret = PTR_ERR(callout_info); goto error2; } callout_len = strlen(callout_info); } /* get the destination keyring if specified */ dest_ref = NULL; if (destringid) { dest_ref = lookup_user_key(destringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(dest_ref)) { ret = PTR_ERR(dest_ref); goto error3; } } /* find the key type */ ktype = key_type_lookup(type); if (IS_ERR(ktype)) { ret = PTR_ERR(ktype); goto error4; } /* do the search */ key = request_key_and_link(ktype, description, callout_info, callout_len, NULL, key_ref_to_ptr(dest_ref), KEY_ALLOC_IN_QUOTA); if (IS_ERR(key)) { ret = PTR_ERR(key); goto error5; } /* wait for the key to finish being constructed */ ret = wait_for_key_construction(key, 1); if (ret < 0) goto error6; ret = key->serial; error6: key_put(key); error5: key_type_put(ktype); error4: key_ref_put(dest_ref); error3: kfree(callout_info); error2: kfree(description); error: return ret; } /* * Get the ID of the specified process keyring. * * The requested keyring must have search permission to be found. * * If successful, the ID of the requested keyring will be returned. */ long keyctl_get_keyring_ID(key_serial_t id, int create) { key_ref_t key_ref; unsigned long lflags; long ret; lflags = create ? KEY_LOOKUP_CREATE : 0; key_ref = lookup_user_key(id, lflags, KEY_NEED_SEARCH); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error; } ret = key_ref_to_ptr(key_ref)->serial; key_ref_put(key_ref); error: return ret; } /* * Join a (named) session keyring. * * Create and join an anonymous session keyring or join a named session * keyring, creating it if necessary. A named session keyring must have Search * permission for it to be joined. Session keyrings without this permit will * be skipped over. It is not permitted for userspace to create or join * keyrings whose name begin with a dot. * * If successful, the ID of the joined session keyring will be returned. */ long keyctl_join_session_keyring(const char __user *_name) { char *name; long ret; /* fetch the name from userspace */ name = NULL; if (_name) { name = strndup_user(_name, KEY_MAX_DESC_SIZE); if (IS_ERR(name)) { ret = PTR_ERR(name); goto error; } ret = -EPERM; if (name[0] == '.') goto error_name; } /* join the session */ ret = join_session_keyring(name); error_name: kfree(name); error: return ret; } /* * Update a key's data payload from the given data. * * The key must grant the caller Write permission and the key type must support * updating for this to work. A negative key can be positively instantiated * with this call. * * If successful, 0 will be returned. If the key type does not support * updating, then -EOPNOTSUPP will be returned. */ long keyctl_update_key(key_serial_t id, const void __user *_payload, size_t plen) { key_ref_t key_ref; void *payload; long ret; ret = -EINVAL; if (plen > PAGE_SIZE) goto error; /* pull the payload in if one was supplied */ payload = NULL; if (plen) { ret = -ENOMEM; payload = kmalloc(plen, GFP_KERNEL); if (!payload) goto error; ret = -EFAULT; if (copy_from_user(payload, _payload, plen) != 0) goto error2; } /* find the target key (which must be writable) */ key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error2; } /* update the key */ ret = key_update(key_ref, payload, plen); key_ref_put(key_ref); error2: kfree(payload); error: return ret; } /* * Revoke a key. * * The key must be grant the caller Write or Setattr permission for this to * work. The key type should give up its quota claim when revoked. The key * and any links to the key will be automatically garbage collected after a * certain amount of time (/proc/sys/kernel/keys/gc_delay). * * Keys with KEY_FLAG_KEEP set should not be revoked. * * If successful, 0 is returned. */ long keyctl_revoke_key(key_serial_t id) { key_ref_t key_ref; struct key *key; long ret; key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); if (ret != -EACCES) goto error; key_ref = lookup_user_key(id, 0, KEY_NEED_SETATTR); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error; } } key = key_ref_to_ptr(key_ref); ret = 0; if (test_bit(KEY_FLAG_KEEP, &key->flags)) ret = -EPERM; else key_revoke(key); key_ref_put(key_ref); error: return ret; } /* * Invalidate a key. * * The key must be grant the caller Invalidate permission for this to work. * The key and any links to the key will be automatically garbage collected * immediately. * * Keys with KEY_FLAG_KEEP set should not be invalidated. * * If successful, 0 is returned. */ long keyctl_invalidate_key(key_serial_t id) { key_ref_t key_ref; struct key *key; long ret; kenter("%d", id); key_ref = lookup_user_key(id, 0, KEY_NEED_SEARCH); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); /* Root is permitted to invalidate certain special keys */ if (capable(CAP_SYS_ADMIN)) { key_ref = lookup_user_key(id, 0, 0); if (IS_ERR(key_ref)) goto error; if (test_bit(KEY_FLAG_ROOT_CAN_INVAL, &key_ref_to_ptr(key_ref)->flags)) goto invalidate; goto error_put; } goto error; } invalidate: key = key_ref_to_ptr(key_ref); ret = 0; if (test_bit(KEY_FLAG_KEEP, &key->flags)) ret = -EPERM; else key_invalidate(key); error_put: key_ref_put(key_ref); error: kleave(" = %ld", ret); return ret; } /* * Clear the specified keyring, creating an empty process keyring if one of the * special keyring IDs is used. * * The keyring must grant the caller Write permission and not have * KEY_FLAG_KEEP set for this to work. If successful, 0 will be returned. */ long keyctl_keyring_clear(key_serial_t ringid) { key_ref_t keyring_ref; struct key *keyring; long ret; keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); /* Root is permitted to invalidate certain special keyrings */ if (capable(CAP_SYS_ADMIN)) { keyring_ref = lookup_user_key(ringid, 0, 0); if (IS_ERR(keyring_ref)) goto error; if (test_bit(KEY_FLAG_ROOT_CAN_CLEAR, &key_ref_to_ptr(keyring_ref)->flags)) goto clear; goto error_put; } goto error; } clear: keyring = key_ref_to_ptr(keyring_ref); if (test_bit(KEY_FLAG_KEEP, &keyring->flags)) ret = -EPERM; else ret = keyring_clear(keyring); error_put: key_ref_put(keyring_ref); error: return ret; } /* * Create a link from a keyring to a key if there's no matching key in the * keyring, otherwise replace the link to the matching key with a link to the * new key. * * The key must grant the caller Link permission and the the keyring must grant * the caller Write permission. Furthermore, if an additional link is created, * the keyring's quota will be extended. * * If successful, 0 will be returned. */ long keyctl_keyring_link(key_serial_t id, key_serial_t ringid) { key_ref_t keyring_ref, key_ref; long ret; keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error; } key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE, KEY_NEED_LINK); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error2; } ret = key_link(key_ref_to_ptr(keyring_ref), key_ref_to_ptr(key_ref)); key_ref_put(key_ref); error2: key_ref_put(keyring_ref); error: return ret; } /* * Unlink a key from a keyring. * * The keyring must grant the caller Write permission for this to work; the key * itself need not grant the caller anything. If the last link to a key is * removed then that key will be scheduled for destruction. * * Keys or keyrings with KEY_FLAG_KEEP set should not be unlinked. * * If successful, 0 will be returned. */ long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid) { key_ref_t keyring_ref, key_ref; struct key *keyring, *key; long ret; keyring_ref = lookup_user_key(ringid, 0, KEY_NEED_WRITE); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error; } key_ref = lookup_user_key(id, KEY_LOOKUP_FOR_UNLINK, 0); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error2; } keyring = key_ref_to_ptr(keyring_ref); key = key_ref_to_ptr(key_ref); if (test_bit(KEY_FLAG_KEEP, &keyring->flags) && test_bit(KEY_FLAG_KEEP, &key->flags)) ret = -EPERM; else ret = key_unlink(keyring, key); key_ref_put(key_ref); error2: key_ref_put(keyring_ref); error: return ret; } /* * Return a description of a key to userspace. * * The key must grant the caller View permission for this to work. * * If there's a buffer, we place up to buflen bytes of data into it formatted * in the following way: * * type;uid;gid;perm;description<NUL> * * If successful, we return the amount of description available, irrespective * of how much we may have copied into the buffer. */ long keyctl_describe_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key, *instkey; key_ref_t key_ref; char *infobuf; long ret; int desclen, infolen; key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, KEY_NEED_VIEW); if (IS_ERR(key_ref)) { /* viewing a key under construction is permitted if we have the * authorisation token handy */ if (PTR_ERR(key_ref) == -EACCES) { instkey = key_get_instantiation_authkey(keyid); if (!IS_ERR(instkey)) { key_put(instkey); key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0); if (!IS_ERR(key_ref)) goto okay; } } ret = PTR_ERR(key_ref); goto error; } okay: key = key_ref_to_ptr(key_ref); desclen = strlen(key->description); /* calculate how much information we're going to return */ ret = -ENOMEM; infobuf = kasprintf(GFP_KERNEL, "%s;%d;%d;%08x;", key->type->name, from_kuid_munged(current_user_ns(), key->uid), from_kgid_munged(current_user_ns(), key->gid), key->perm); if (!infobuf) goto error2; infolen = strlen(infobuf); ret = infolen + desclen + 1; /* consider returning the data */ if (buffer && buflen >= ret) { if (copy_to_user(buffer, infobuf, infolen) != 0 || copy_to_user(buffer + infolen, key->description, desclen + 1) != 0) ret = -EFAULT; } kfree(infobuf); error2: key_ref_put(key_ref); error: return ret; } /* * Search the specified keyring and any keyrings it links to for a matching * key. Only keyrings that grant the caller Search permission will be searched * (this includes the starting keyring). Only keys with Search permission can * be found. * * If successful, the found key will be linked to the destination keyring if * supplied and the key has Link permission, and the found key ID will be * returned. */ long keyctl_keyring_search(key_serial_t ringid, const char __user *_type, const char __user *_description, key_serial_t destringid) { struct key_type *ktype; key_ref_t keyring_ref, key_ref, dest_ref; char type[32], *description; long ret; /* pull the type and description into kernel space */ ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; description = strndup_user(_description, KEY_MAX_DESC_SIZE); if (IS_ERR(description)) { ret = PTR_ERR(description); goto error; } /* get the keyring at which to begin the search */ keyring_ref = lookup_user_key(ringid, 0, KEY_NEED_SEARCH); if (IS_ERR(keyring_ref)) { ret = PTR_ERR(keyring_ref); goto error2; } /* get the destination keyring if specified */ dest_ref = NULL; if (destringid) { dest_ref = lookup_user_key(destringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(dest_ref)) { ret = PTR_ERR(dest_ref); goto error3; } } /* find the key type */ ktype = key_type_lookup(type); if (IS_ERR(ktype)) { ret = PTR_ERR(ktype); goto error4; } /* do the search */ key_ref = keyring_search(keyring_ref, ktype, description); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); /* treat lack or presence of a negative key the same */ if (ret == -EAGAIN) ret = -ENOKEY; goto error5; } /* link the resulting key to the destination keyring if we can */ if (dest_ref) { ret = key_permission(key_ref, KEY_NEED_LINK); if (ret < 0) goto error6; ret = key_link(key_ref_to_ptr(dest_ref), key_ref_to_ptr(key_ref)); if (ret < 0) goto error6; } ret = key_ref_to_ptr(key_ref)->serial; error6: key_ref_put(key_ref); error5: key_type_put(ktype); error4: key_ref_put(dest_ref); error3: key_ref_put(keyring_ref); error2: kfree(description); error: return ret; } /* * Read a key's payload. * * The key must either grant the caller Read permission, or it must grant the * caller Search permission when searched for from the process keyrings. * * If successful, we place up to buflen bytes of data into the buffer, if one * is provided, and return the amount of data that is available in the key, * irrespective of how much we copied into the buffer. */ long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; } /* * Change the ownership of a key * * The key must grant the caller Setattr permission for this to work, though * the key need not be fully instantiated yet. For the UID to be changed, or * for the GID to be changed to a group the caller is not a member of, the * caller must have sysadmin capability. If either uid or gid is -1 then that * attribute is not changed. * * If the UID is to be changed, the new user must have sufficient quota to * accept the key. The quota deduction will be removed from the old user to * the new user should the attribute be changed. * * If successful, 0 will be returned. */ long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group) { struct key_user *newowner, *zapowner = NULL; struct key *key; key_ref_t key_ref; long ret; kuid_t uid; kgid_t gid; uid = make_kuid(current_user_ns(), user); gid = make_kgid(current_user_ns(), group); ret = -EINVAL; if ((user != (uid_t) -1) && !uid_valid(uid)) goto error; if ((group != (gid_t) -1) && !gid_valid(gid)) goto error; ret = 0; if (user == (uid_t) -1 && group == (gid_t) -1) goto error; key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL, KEY_NEED_SETATTR); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error; } key = key_ref_to_ptr(key_ref); /* make the changes with the locks held to prevent chown/chown races */ ret = -EACCES; down_write(&key->sem); if (!capable(CAP_SYS_ADMIN)) { /* only the sysadmin can chown a key to some other UID */ if (user != (uid_t) -1 && !uid_eq(key->uid, uid)) goto error_put; /* only the sysadmin can set the key's GID to a group other * than one of those that the current process subscribes to */ if (group != (gid_t) -1 && !gid_eq(gid, key->gid) && !in_group_p(gid)) goto error_put; } /* change the UID */ if (user != (uid_t) -1 && !uid_eq(uid, key->uid)) { ret = -ENOMEM; newowner = key_user_lookup(uid); if (!newowner) goto error_put; /* transfer the quota burden to the new user */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&newowner->lock); if (newowner->qnkeys + 1 >= maxkeys || newowner->qnbytes + key->quotalen >= maxbytes || newowner->qnbytes + key->quotalen < newowner->qnbytes) goto quota_overrun; newowner->qnkeys++; newowner->qnbytes += key->quotalen; spin_unlock(&newowner->lock); spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); atomic_inc(&newowner->nkeys); if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { atomic_dec(&key->user->nikeys); atomic_inc(&newowner->nikeys); } zapowner = key->user; key->user = newowner; key->uid = uid; } /* change the GID */ if (group != (gid_t) -1) key->gid = gid; ret = 0; error_put: up_write(&key->sem); key_put(key); if (zapowner) key_user_put(zapowner); error: return ret; quota_overrun: spin_unlock(&newowner->lock); zapowner = newowner; ret = -EDQUOT; goto error_put; } /* * Change the permission mask on a key. * * The key must grant the caller Setattr permission for this to work, though * the key need not be fully instantiated yet. If the caller does not have * sysadmin capability, it may only change the permission on keys that it owns. */ long keyctl_setperm_key(key_serial_t id, key_perm_t perm) { struct key *key; key_ref_t key_ref; long ret; ret = -EINVAL; if (perm & ~(KEY_POS_ALL | KEY_USR_ALL | KEY_GRP_ALL | KEY_OTH_ALL)) goto error; key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL, KEY_NEED_SETATTR); if (IS_ERR(key_ref)) { ret = PTR_ERR(key_ref); goto error; } key = key_ref_to_ptr(key_ref); /* make the changes with the locks held to prevent chown/chmod races */ ret = -EACCES; down_write(&key->sem); /* if we're not the sysadmin, we can only change a key that we own */ if (capable(CAP_SYS_ADMIN) || uid_eq(key->uid, current_fsuid())) { key->perm = perm; ret = 0; } up_write(&key->sem); key_put(key); error: return ret; } /* * Get the destination keyring for instantiation and check that the caller has * Write permission on it. */ static long get_instantiation_keyring(key_serial_t ringid, struct request_key_auth *rka, struct key **_dest_keyring) { key_ref_t dkref; *_dest_keyring = NULL; /* just return a NULL pointer if we weren't asked to make a link */ if (ringid == 0) return 0; /* if a specific keyring is nominated by ID, then use that */ if (ringid > 0) { dkref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE); if (IS_ERR(dkref)) return PTR_ERR(dkref); *_dest_keyring = key_ref_to_ptr(dkref); return 0; } if (ringid == KEY_SPEC_REQKEY_AUTH_KEY) return -EINVAL; /* otherwise specify the destination keyring recorded in the * authorisation key (any KEY_SPEC_*_KEYRING) */ if (ringid >= KEY_SPEC_REQUESTOR_KEYRING) { *_dest_keyring = key_get(rka->dest_keyring); return 0; } return -ENOKEY; } /* * Change the request_key authorisation key on the current process. */ static int keyctl_change_reqkey_auth(struct key *key) { struct cred *new; new = prepare_creds(); if (!new) return -ENOMEM; key_put(new->request_key_auth); new->request_key_auth = key_get(key); return commit_creds(new); } /* * Instantiate a key with the specified payload and link the key into the * destination keyring if one is given. * * The caller must have the appropriate instantiation permit set for this to * work (see keyctl_assume_authority). No other permissions are required. * * If successful, 0 will be returned. */ long keyctl_instantiate_key_common(key_serial_t id, struct iov_iter *from, key_serial_t ringid) { const struct cred *cred = current_cred(); struct request_key_auth *rka; struct key *instkey, *dest_keyring; size_t plen = from ? iov_iter_count(from) : 0; void *payload; long ret; kenter("%d,,%zu,%d", id, plen, ringid); if (!plen) from = NULL; ret = -EINVAL; if (plen > 1024 * 1024 - 1) goto error; /* the appropriate instantiation authorisation key must have been * assumed before calling this */ ret = -EPERM; instkey = cred->request_key_auth; if (!instkey) goto error; rka = instkey->payload.data[0]; if (rka->target_key->serial != id) goto error; /* pull the payload in if one was supplied */ payload = NULL; if (from) { ret = -ENOMEM; payload = kvmalloc(plen, GFP_KERNEL); if (!payload) goto error; ret = -EFAULT; if (!copy_from_iter_full(payload, plen, from)) goto error2; } /* find the destination keyring amongst those belonging to the * requesting task */ ret = get_instantiation_keyring(ringid, rka, &dest_keyring); if (ret < 0) goto error2; /* instantiate the key and link it into a keyring */ ret = key_instantiate_and_link(rka->target_key, payload, plen, dest_keyring, instkey); key_put(dest_keyring); /* discard the assumed authority if it's just been disabled by * instantiation of the key */ if (ret == 0) keyctl_change_reqkey_auth(NULL); error2: kvfree(payload); error: return ret; } /* * Instantiate a key with the specified payload and link the key into the * destination keyring if one is given. * * The caller must have the appropriate instantiation permit set for this to * work (see keyctl_assume_authority). No other permissions are required. * * If successful, 0 will be returned. */ long keyctl_instantiate_key(key_serial_t id, const void __user *_payload, size_t plen, key_serial_t ringid) { if (_payload && plen) { struct iovec iov; struct iov_iter from; int ret; ret = import_single_range(WRITE, (void __user *)_payload, plen, &iov, &from); if (unlikely(ret)) return ret; return keyctl_instantiate_key_common(id, &from, ringid); } return keyctl_instantiate_key_common(id, NULL, ringid); } /* * Instantiate a key with the specified multipart payload and link the key into * the destination keyring if one is given. * * The caller must have the appropriate instantiation permit set for this to * work (see keyctl_assume_authority). No other permissions are required. * * If successful, 0 will be returned. */ long keyctl_instantiate_key_iov(key_serial_t id, const struct iovec __user *_payload_iov, unsigned ioc, key_serial_t ringid) { struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; struct iov_iter from; long ret; if (!_payload_iov) ioc = 0; ret = import_iovec(WRITE, _payload_iov, ioc, ARRAY_SIZE(iovstack), &iov, &from); if (ret < 0) return ret; ret = keyctl_instantiate_key_common(id, &from, ringid); kfree(iov); return ret; } /* * Negatively instantiate the key with the given timeout (in seconds) and link * the key into the destination keyring if one is given. * * The caller must have the appropriate instantiation permit set for this to * work (see keyctl_assume_authority). No other permissions are required. * * The key and any links to the key will be automatically garbage collected * after the timeout expires. * * Negative keys are used to rate limit repeated request_key() calls by causing * them to return -ENOKEY until the negative key expires. * * If successful, 0 will be returned. */ long keyctl_negate_key(key_serial_t id, unsigned timeout, key_serial_t ringid) { return keyctl_reject_key(id, timeout, ENOKEY, ringid); } /* * Negatively instantiate the key with the given timeout (in seconds) and error * code and link the key into the destination keyring if one is given. * * The caller must have the appropriate instantiation permit set for this to * work (see keyctl_assume_authority). No other permissions are required. * * The key and any links to the key will be automatically garbage collected * after the timeout expires. * * Negative keys are used to rate limit repeated request_key() calls by causing * them to return the specified error code until the negative key expires. * * If successful, 0 will be returned. */ long keyctl_reject_key(key_serial_t id, unsigned timeout, unsigned error, key_serial_t ringid) { const struct cred *cred = current_cred(); struct request_key_auth *rka; struct key *instkey, *dest_keyring; long ret; kenter("%d,%u,%u,%d", id, timeout, error, ringid); /* must be a valid error code and mustn't be a kernel special */ if (error <= 0 || error >= MAX_ERRNO || error == ERESTARTSYS || error == ERESTARTNOINTR || error == ERESTARTNOHAND || error == ERESTART_RESTARTBLOCK) return -EINVAL; /* the appropriate instantiation authorisation key must have been * assumed before calling this */ ret = -EPERM; instkey = cred->request_key_auth; if (!instkey) goto error; rka = instkey->payload.data[0]; if (rka->target_key->serial != id) goto error; /* find the destination keyring if present (which must also be * writable) */ ret = get_instantiation_keyring(ringid, rka, &dest_keyring); if (ret < 0) goto error; /* instantiate the key and link it into a keyring */ ret = key_reject_and_link(rka->target_key, timeout, error, dest_keyring, instkey); key_put(dest_keyring); /* discard the assumed authority if it's just been disabled by * instantiation of the key */ if (ret == 0) keyctl_change_reqkey_auth(NULL); error: return ret; } /* * Read or set the default keyring in which request_key() will cache keys and * return the old setting. * * If a thread or process keyring is specified then it will be created if it * doesn't yet exist. The old setting will be returned if successful. */ long keyctl_set_reqkey_keyring(int reqkey_defl) { struct cred *new; int ret, old_setting; old_setting = current_cred_xxx(jit_keyring); if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE) return old_setting; new = prepare_creds(); if (!new) return -ENOMEM; switch (reqkey_defl) { case KEY_REQKEY_DEFL_THREAD_KEYRING: ret = install_thread_keyring_to_cred(new); if (ret < 0) goto error; goto set; case KEY_REQKEY_DEFL_PROCESS_KEYRING: ret = install_process_keyring_to_cred(new); if (ret < 0) goto error; goto set; case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_SESSION_KEYRING: case KEY_REQKEY_DEFL_USER_KEYRING: case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: goto set; case KEY_REQKEY_DEFL_NO_CHANGE: case KEY_REQKEY_DEFL_GROUP_KEYRING: default: ret = -EINVAL; goto error; } set: new->jit_keyring = reqkey_defl; commit_creds(new); return old_setting; error: abort_creds(new); return ret; } /* * Set or clear the timeout on a key. * * Either the key must grant the caller Setattr permission or else the caller * must hold an instantiation authorisation token for the key. * * The timeout is either 0 to clear the timeout, or a number of seconds from * the current time. The key and any links to the key will be automatically * garbage collected after the timeout expires. * * Keys with KEY_FLAG_KEEP set should not be timed out. * * If successful, 0 is returned. */ long keyctl_set_timeout(key_serial_t id, unsigned timeout) { struct key *key, *instkey; key_ref_t key_ref; long ret; key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL, KEY_NEED_SETATTR); if (IS_ERR(key_ref)) { /* setting the timeout on a key under construction is permitted * if we have the authorisation token handy */ if (PTR_ERR(key_ref) == -EACCES) { instkey = key_get_instantiation_authkey(id); if (!IS_ERR(instkey)) { key_put(instkey); key_ref = lookup_user_key(id, KEY_LOOKUP_PARTIAL, 0); if (!IS_ERR(key_ref)) goto okay; } } ret = PTR_ERR(key_ref); goto error; } okay: key = key_ref_to_ptr(key_ref); ret = 0; if (test_bit(KEY_FLAG_KEEP, &key->flags)) ret = -EPERM; else key_set_timeout(key, timeout); key_put(key); error: return ret; } /* * Assume (or clear) the authority to instantiate the specified key. * * This sets the authoritative token currently in force for key instantiation. * This must be done for a key to be instantiated. It has the effect of making * available all the keys from the caller of the request_key() that created a * key to request_key() calls made by the caller of this function. * * The caller must have the instantiation key in their process keyrings with a * Search permission grant available to the caller. * * If the ID given is 0, then the setting will be cleared and 0 returned. * * If the ID given has a matching an authorisation key, then that key will be * set and its ID will be returned. The authorisation key can be read to get * the callout information passed to request_key(). */ long keyctl_assume_authority(key_serial_t id) { struct key *authkey; long ret; /* special key IDs aren't permitted */ ret = -EINVAL; if (id < 0) goto error; /* we divest ourselves of authority if given an ID of 0 */ if (id == 0) { ret = keyctl_change_reqkey_auth(NULL); goto error; } /* attempt to assume the authority temporarily granted to us whilst we * instantiate the specified key * - the authorisation key must be in the current task's keyrings * somewhere */ authkey = key_get_instantiation_authkey(id); if (IS_ERR(authkey)) { ret = PTR_ERR(authkey); goto error; } ret = keyctl_change_reqkey_auth(authkey); if (ret < 0) goto error; key_put(authkey); ret = authkey->serial; error: return ret; } /* * Get a key's the LSM security label. * * The key must grant the caller View permission for this to work. * * If there's a buffer, then up to buflen bytes of data will be placed into it. * * If successful, the amount of information available will be returned, * irrespective of how much was copied (including the terminal NUL). */ long keyctl_get_security(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key, *instkey; key_ref_t key_ref; char *context; long ret; key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, KEY_NEED_VIEW); if (IS_ERR(key_ref)) { if (PTR_ERR(key_ref) != -EACCES) return PTR_ERR(key_ref); /* viewing a key under construction is also permitted if we * have the authorisation token handy */ instkey = key_get_instantiation_authkey(keyid); if (IS_ERR(instkey)) return PTR_ERR(instkey); key_put(instkey); key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0); if (IS_ERR(key_ref)) return PTR_ERR(key_ref); } key = key_ref_to_ptr(key_ref); ret = security_key_getsecurity(key, &context); if (ret == 0) { /* if no information was returned, give userspace an empty * string */ ret = 1; if (buffer && buflen > 0 && copy_to_user(buffer, "", 1) != 0) ret = -EFAULT; } else if (ret > 0) { /* return as much data as there's room for */ if (buffer && buflen > 0) { if (buflen > ret) buflen = ret; if (copy_to_user(buffer, context, buflen) != 0) ret = -EFAULT; } kfree(context); } key_ref_put(key_ref); return ret; } /* * Attempt to install the calling process's session keyring on the process's * parent process. * * The keyring must exist and must grant the caller LINK permission, and the * parent process must be single-threaded and must have the same effective * ownership as this process and mustn't be SUID/SGID. * * The keyring will be emplaced on the parent when it next resumes userspace. * * If successful, 0 will be returned. */ long keyctl_session_to_parent(void) { struct task_struct *me, *parent; const struct cred *mycred, *pcred; struct callback_head *newwork, *oldwork; key_ref_t keyring_r; struct cred *cred; int ret; keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_NEED_LINK); if (IS_ERR(keyring_r)) return PTR_ERR(keyring_r); ret = -ENOMEM; /* our parent is going to need a new cred struct, a new tgcred struct * and new security data, so we allocate them here to prevent ENOMEM in * our parent */ cred = cred_alloc_blank(); if (!cred) goto error_keyring; newwork = &cred->rcu; cred->session_keyring = key_ref_to_ptr(keyring_r); keyring_r = NULL; init_task_work(newwork, key_change_session_keyring); me = current; rcu_read_lock(); write_lock_irq(&tasklist_lock); ret = -EPERM; oldwork = NULL; parent = me->real_parent; /* the parent mustn't be init and mustn't be a kernel thread */ if (parent->pid <= 1 || !parent->mm) goto unlock; /* the parent must be single threaded */ if (!thread_group_empty(parent)) goto unlock; /* the parent and the child must have different session keyrings or * there's no point */ mycred = current_cred(); pcred = __task_cred(parent); if (mycred == pcred || mycred->session_keyring == pcred->session_keyring) { ret = 0; goto unlock; } /* the parent must have the same effective ownership and mustn't be * SUID/SGID */ if (!uid_eq(pcred->uid, mycred->euid) || !uid_eq(pcred->euid, mycred->euid) || !uid_eq(pcred->suid, mycred->euid) || !gid_eq(pcred->gid, mycred->egid) || !gid_eq(pcred->egid, mycred->egid) || !gid_eq(pcred->sgid, mycred->egid)) goto unlock; /* the keyrings must have the same UID */ if ((pcred->session_keyring && !uid_eq(pcred->session_keyring->uid, mycred->euid)) || !uid_eq(mycred->session_keyring->uid, mycred->euid)) goto unlock; /* cancel an already pending keyring replacement */ oldwork = task_work_cancel(parent, key_change_session_keyring); /* the replacement session keyring is applied just prior to userspace * restarting */ ret = task_work_add(parent, newwork, true); if (!ret) newwork = NULL; unlock: write_unlock_irq(&tasklist_lock); rcu_read_unlock(); if (oldwork) put_cred(container_of(oldwork, struct cred, rcu)); if (newwork) put_cred(cred); return ret; error_keyring: key_ref_put(keyring_r); return ret; } /* * Apply a restriction to a given keyring. * * The caller must have Setattr permission to change keyring restrictions. * * The requested type name may be a NULL pointer to reject all attempts * to link to the keyring. If _type is non-NULL, _restriction can be * NULL or a pointer to a string describing the restriction. If _type is * NULL, _restriction must also be NULL. * * Returns 0 if successful. */ long keyctl_restrict_keyring(key_serial_t id, const char __user *_type, const char __user *_restriction) { key_ref_t key_ref; bool link_reject = !_type; char type[32]; char *restriction = NULL; long ret; key_ref = lookup_user_key(id, 0, KEY_NEED_SETATTR); if (IS_ERR(key_ref)) return PTR_ERR(key_ref); if (_type) { ret = key_get_type_from_user(type, _type, sizeof(type)); if (ret < 0) goto error; } if (_restriction) { if (!_type) { ret = -EINVAL; goto error; } restriction = strndup_user(_restriction, PAGE_SIZE); if (IS_ERR(restriction)) { ret = PTR_ERR(restriction); goto error; } } ret = keyring_restrict(key_ref, link_reject ? NULL : type, restriction); kfree(restriction); error: key_ref_put(key_ref); return ret; } /* * The key control system call */ SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3, unsigned long, arg4, unsigned long, arg5) { switch (option) { case KEYCTL_GET_KEYRING_ID: return keyctl_get_keyring_ID((key_serial_t) arg2, (int) arg3); case KEYCTL_JOIN_SESSION_KEYRING: return keyctl_join_session_keyring((const char __user *) arg2); case KEYCTL_UPDATE: return keyctl_update_key((key_serial_t) arg2, (const void __user *) arg3, (size_t) arg4); case KEYCTL_REVOKE: return keyctl_revoke_key((key_serial_t) arg2); case KEYCTL_DESCRIBE: return keyctl_describe_key((key_serial_t) arg2, (char __user *) arg3, (unsigned) arg4); case KEYCTL_CLEAR: return keyctl_keyring_clear((key_serial_t) arg2); case KEYCTL_LINK: return keyctl_keyring_link((key_serial_t) arg2, (key_serial_t) arg3); case KEYCTL_UNLINK: return keyctl_keyring_unlink((key_serial_t) arg2, (key_serial_t) arg3); case KEYCTL_SEARCH: return keyctl_keyring_search((key_serial_t) arg2, (const char __user *) arg3, (const char __user *) arg4, (key_serial_t) arg5); case KEYCTL_READ: return keyctl_read_key((key_serial_t) arg2, (char __user *) arg3, (size_t) arg4); case KEYCTL_CHOWN: return keyctl_chown_key((key_serial_t) arg2, (uid_t) arg3, (gid_t) arg4); case KEYCTL_SETPERM: return keyctl_setperm_key((key_serial_t) arg2, (key_perm_t) arg3); case KEYCTL_INSTANTIATE: return keyctl_instantiate_key((key_serial_t) arg2, (const void __user *) arg3, (size_t) arg4, (key_serial_t) arg5); case KEYCTL_NEGATE: return keyctl_negate_key((key_serial_t) arg2, (unsigned) arg3, (key_serial_t) arg4); case KEYCTL_SET_REQKEY_KEYRING: return keyctl_set_reqkey_keyring(arg2); case KEYCTL_SET_TIMEOUT: return keyctl_set_timeout((key_serial_t) arg2, (unsigned) arg3); case KEYCTL_ASSUME_AUTHORITY: return keyctl_assume_authority((key_serial_t) arg2); case KEYCTL_GET_SECURITY: return keyctl_get_security((key_serial_t) arg2, (char __user *) arg3, (size_t) arg4); case KEYCTL_SESSION_TO_PARENT: return keyctl_session_to_parent(); case KEYCTL_REJECT: return keyctl_reject_key((key_serial_t) arg2, (unsigned) arg3, (unsigned) arg4, (key_serial_t) arg5); case KEYCTL_INSTANTIATE_IOV: return keyctl_instantiate_key_iov( (key_serial_t) arg2, (const struct iovec __user *) arg3, (unsigned) arg4, (key_serial_t) arg5); case KEYCTL_INVALIDATE: return keyctl_invalidate_key((key_serial_t) arg2); case KEYCTL_GET_PERSISTENT: return keyctl_get_persistent((uid_t)arg2, (key_serial_t)arg3); case KEYCTL_DH_COMPUTE: return keyctl_dh_compute((struct keyctl_dh_params __user *) arg2, (char __user *) arg3, (size_t) arg4, (struct keyctl_kdf_params __user *) arg5); case KEYCTL_RESTRICT_KEYRING: return keyctl_restrict_keyring((key_serial_t) arg2, (const char __user *) arg3, (const char __user *) arg4); default: return -EOPNOTSUPP; } }
./CrossVul/dataset_final_sorted/CWE-476/c/good_2852_0
crossvul-cpp_data_good_3402_0
/* * DNxHD/VC-3 parser * Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier@free.fr> * * 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 */ /** * @file * DNxHD/VC-3 parser */ #include "parser.h" #include "dnxhddata.h" typedef struct { ParseContext pc; int cur_byte; int remaining; int w, h; } DNXHDParserContext; static int dnxhd_get_hr_frame_size(int cid, int w, int h) { int result, i = ff_dnxhd_get_cid_table(cid); if (i < 0) return i; result = ((h + 15) / 16) * ((w + 15) / 16) * ff_dnxhd_cid_table[i].packet_scale.num / ff_dnxhd_cid_table[i].packet_scale.den; result = (result + 2048) / 4096 * 4096; return FFMAX(result, 8192); } static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; int remaining; if (cid <= 0) continue; remaining = avpriv_dnxhd_get_frame_size(cid); if (remaining <= 0) { remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (remaining <= 0) continue; } dctx->remaining = remaining; if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; } static int dnxhd_parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size) { DNXHDParserContext *dctx = s->priv_data; ParseContext *pc = &dctx->pc; int next; if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) { next = buf_size; } else { next = dnxhd_find_frame_end(dctx, buf, buf_size); if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) { *poutbuf = NULL; *poutbuf_size = 0; return buf_size; } } *poutbuf = buf; *poutbuf_size = buf_size; return next; } AVCodecParser ff_dnxhd_parser = { .codec_ids = { AV_CODEC_ID_DNXHD }, .priv_data_size = sizeof(DNXHDParserContext), .parser_parse = dnxhd_parse, .parser_close = ff_parse_close, };
./CrossVul/dataset_final_sorted/CWE-476/c/good_3402_0
crossvul-cpp_data_bad_5714_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Core * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "rdp.h" #include "info.h" #include "redirection.h" #include <freerdp/crypto/per.h> #ifdef WITH_DEBUG_RDP static const char* const DATA_PDU_TYPE_STRINGS[] = { "?", "?", /* 0x00 - 0x01 */ "Update", /* 0x02 */ "?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */ "?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */ "Control", /* 0x14 */ "?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */ "Pointer", /* 0x1B */ "Input", /* 0x1C */ "?", "?", /* 0x1D - 0x1E */ "Synchronize", /* 0x1F */ "?", /* 0x20 */ "Refresh Rect", /* 0x21 */ "Play Sound", /* 0x22 */ "Suppress Output", /* 0x23 */ "Shutdown Request", /* 0x24 */ "Shutdown Denied", /* 0x25 */ "Save Session Info", /* 0x26 */ "Font List", /* 0x27 */ "Font Map", /* 0x28 */ "Set Keyboard Indicators", /* 0x29 */ "?", /* 0x2A */ "Bitmap Cache Persistent List", /* 0x2B */ "Bitmap Cache Error", /* 0x2C */ "Set Keyboard IME Status", /* 0x2D */ "Offscreen Cache Error", /* 0x2E */ "Set Error Info", /* 0x2F */ "Draw Nine Grid Error", /* 0x30 */ "Draw GDI+ Error", /* 0x31 */ "ARC Status", /* 0x32 */ "?", "?", "?", /* 0x33 - 0x35 */ "Status Info", /* 0x36 */ "Monitor Layout" /* 0x37 */ "?", "?", "?", /* 0x38 - 0x40 */ "?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */ }; #endif /** * Read RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ BOOL rdp_read_security_header(STREAM* s, UINT16* flags) { /* Basic Security Header */ if(stream_get_left(s) < 4) return FALSE; stream_read_UINT16(s, *flags); /* flags */ stream_seek(s, 2); /* flagsHi (unused) */ return TRUE; } /** * Write RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ void rdp_write_security_header(STREAM* s, UINT16 flags) { /* Basic Security Header */ stream_write_UINT16(s, flags); /* flags */ stream_write_UINT16(s, 0); /* flagsHi (unused) */ } BOOL rdp_read_share_control_header(STREAM* s, UINT16* length, UINT16* type, UINT16* channel_id) { if (stream_get_left(s) < 2) return FALSE; /* Share Control Header */ stream_read_UINT16(s, *length); /* totalLength */ if (*length - 2 > stream_get_left(s)) return FALSE; stream_read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (*length > 4) stream_read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; } void rdp_write_share_control_header(STREAM* s, UINT16 length, UINT16 type, UINT16 channel_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; /* Share Control Header */ stream_write_UINT16(s, length); /* totalLength */ stream_write_UINT16(s, type | 0x10); /* pduType */ stream_write_UINT16(s, channel_id); /* pduSource */ } BOOL rdp_read_share_data_header(STREAM* s, UINT16* length, BYTE* type, UINT32* share_id, BYTE *compressed_type, UINT16 *compressed_len) { if (stream_get_left(s) < 12) return FALSE; /* Share Data Header */ stream_read_UINT32(s, *share_id); /* shareId (4 bytes) */ stream_seek_BYTE(s); /* pad1 (1 byte) */ stream_seek_BYTE(s); /* streamId (1 byte) */ stream_read_UINT16(s, *length); /* uncompressedLength (2 bytes) */ stream_read_BYTE(s, *type); /* pduType2, Data PDU Type (1 byte) */ stream_read_BYTE(s, *compressed_type); /* compressedType (1 byte) */ stream_read_UINT16(s, *compressed_len); /* compressedLength (2 bytes) */ return TRUE; } void rdp_write_share_data_header(STREAM* s, UINT16 length, BYTE type, UINT32 share_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; length -= RDP_SHARE_CONTROL_HEADER_LENGTH; length -= RDP_SHARE_DATA_HEADER_LENGTH; /* Share Data Header */ stream_write_UINT32(s, share_id); /* shareId (4 bytes) */ stream_write_BYTE(s, 0); /* pad1 (1 byte) */ stream_write_BYTE(s, STREAM_LOW); /* streamId (1 byte) */ stream_write_UINT16(s, length); /* uncompressedLength (2 bytes) */ stream_write_BYTE(s, type); /* pduType2, Data PDU Type (1 byte) */ stream_write_BYTE(s, 0); /* compressedType (1 byte) */ stream_write_UINT16(s, 0); /* compressedLength (2 bytes) */ } static int rdp_security_stream_init(rdpRdp* rdp, STREAM* s) { if (rdp->do_crypt) { stream_seek(s, 12); if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) stream_seek(s, 4); rdp->sec_flags |= SEC_ENCRYPT; if (rdp->do_secure_checksum) rdp->sec_flags |= SEC_SECURE_CHECKSUM; } else if (rdp->sec_flags != 0) { stream_seek(s, 4); } return 0; } /** * Initialize an RDP packet stream.\n * @param rdp rdp module * @return */ STREAM* rdp_send_stream_init(rdpRdp* rdp) { STREAM* s; s = transport_send_stream_init(rdp->transport, 2048); stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH); rdp_security_stream_init(rdp, s); return s; } STREAM* rdp_pdu_init(rdpRdp* rdp) { STREAM* s; s = transport_send_stream_init(rdp->transport, 2048); stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH); rdp_security_stream_init(rdp, s); stream_seek(s, RDP_SHARE_CONTROL_HEADER_LENGTH); return s; } STREAM* rdp_data_pdu_init(rdpRdp* rdp) { STREAM* s; s = transport_send_stream_init(rdp->transport, 2048); stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH); rdp_security_stream_init(rdp, s); stream_seek(s, RDP_SHARE_CONTROL_HEADER_LENGTH); stream_seek(s, RDP_SHARE_DATA_HEADER_LENGTH); return s; } /** * Read an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ BOOL rdp_read_header(rdpRdp* rdp, STREAM* s, UINT16* length, UINT16* channel_id) { UINT16 initiator; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication; if (!mcs_read_domain_mcspdu_header(s, &MCSPDU, length)) { if (MCSPDU != DomainMCSPDU_DisconnectProviderUltimatum) return FALSE; } if (*length - 8 > stream_get_left(s)) return FALSE; if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum) { BYTE reason; (void) per_read_enumerated(s, &reason, 0); DEBUG_RDP("DisconnectProviderUltimatum from server, reason code 0x%02x\n", reason); rdp->disconnect = TRUE; return TRUE; } if(stream_get_left(s) < 5) return FALSE; per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID); /* initiator (UserId) */ per_read_integer16(s, channel_id, 0); /* channelId */ stream_seek(s, 1); /* dataPriority + Segmentation (0x70) */ if(!per_read_length(s, length)) /* userData (OCTET_STRING) */ return FALSE; if (*length > stream_get_left(s)) return FALSE; return TRUE; } /** * Write an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ void rdp_write_header(rdpRdp* rdp, STREAM* s, UINT16 length, UINT16 channel_id) { int body_length; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest; if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)) { int pad; body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16; pad = 8 - (body_length % 8); if (pad != 8) length += pad; } mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0); per_write_integer16(s, rdp->mcs->user_id, MCS_BASE_CHANNEL_ID); /* initiator */ per_write_integer16(s, channel_id, 0); /* channelId */ stream_write_BYTE(s, 0x70); /* dataPriority + segmentation */ /* * We always encode length in two bytes, eventhough we could use * only one byte if length <= 0x7F. It is just easier that way, * because we can leave room for fixed-length header, store all * the data first and then store the header. */ length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000; stream_write_UINT16_be(s, length); /* userData (OCTET_STRING) */ } static UINT32 rdp_security_stream_out(rdpRdp* rdp, STREAM* s, int length) { BYTE* data; UINT32 sec_flags; UINT32 pad = 0; sec_flags = rdp->sec_flags; if (sec_flags != 0) { rdp_write_security_header(s, sec_flags); if (sec_flags & SEC_ENCRYPT) { if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { data = s->p + 12; length = length - (data - s->data); stream_write_UINT16(s, 0x10); /* length */ stream_write_BYTE(s, 0x1); /* TSFIPS_VERSION 1*/ /* handle padding */ pad = 8 - (length % 8); if (pad == 8) pad = 0; if (pad) memset(data+length, 0, pad); stream_write_BYTE(s, pad); security_hmac_signature(data, length, s->p, rdp); stream_seek(s, 8); security_fips_encrypt(data, length + pad, rdp); } else { data = s->p + 8; length = length - (data - s->data); if (sec_flags & SEC_SECURE_CHECKSUM) security_salted_mac_signature(rdp, data, length, TRUE, s->p); else security_mac_signature(rdp, data, length, s->p); stream_seek(s, 8); security_encrypt(s->p, length, rdp); } } rdp->sec_flags = 0; } return pad; } static UINT32 rdp_get_sec_bytes(rdpRdp* rdp) { UINT32 sec_bytes; if (rdp->sec_flags & SEC_ENCRYPT) { sec_bytes = 12; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) sec_bytes += 4; } else if (rdp->sec_flags != 0) { sec_bytes = 4; } else { sec_bytes = 0; } return sec_bytes; } /** * Send an RDP packet.\n * @param rdp RDP module * @param s stream * @param channel_id channel id */ BOOL rdp_send(rdpRdp* rdp, STREAM* s, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; BYTE* sec_hold; length = stream_get_length(s); stream_set_pos(s, 0); rdp_write_header(rdp, s, length, channel_id); sec_bytes = rdp_get_sec_bytes(rdp); sec_hold = s->p; stream_seek(s, sec_bytes); s->p = sec_hold; length += rdp_security_stream_out(rdp, s, length); stream_set_pos(s, length); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_pdu(rdpRdp* rdp, STREAM* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; BYTE* sec_hold; length = stream_get_length(s); stream_set_pos(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp); sec_hold = s->p; stream_seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); s->p = sec_hold; length += rdp_security_stream_out(rdp, s, length); stream_set_pos(s, length); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_data_pdu(rdpRdp* rdp, STREAM* s, BYTE type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; BYTE* sec_hold; length = stream_get_length(s); stream_set_pos(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp); sec_hold = s->p; stream_seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id); rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId); s->p = sec_hold; length += rdp_security_stream_out(rdp, s, length); stream_set_pos(s, length); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, STREAM* s) { if (stream_get_left(s) < 4) return FALSE; stream_read_UINT32(s, rdp->errorInfo); /* errorInfo (4 bytes) */ if (rdp->errorInfo != ERRINFO_SUCCESS) rdp_print_errinfo(rdp->errorInfo); return TRUE; } int rdp_recv_data_pdu(rdpRdp* rdp, STREAM* s) { BYTE type; UINT16 length; UINT32 share_id; BYTE compressed_type; UINT16 compressed_len; UINT32 roff; UINT32 rlen; STREAM* comp_stream; if (!rdp_read_share_data_header(s, &length, &type, &share_id, &compressed_type, &compressed_len)) return -1; comp_stream = s; if (compressed_type & PACKET_COMPRESSED) { if (stream_get_left(s) < compressed_len - 18) { printf("decompress_rdp: not enough bytes for compressed_len=%d\n", compressed_len); return -1; } if (decompress_rdp(rdp->mppc_dec, s->p, compressed_len - 18, compressed_type, &roff, &rlen)) { comp_stream = stream_new(0); comp_stream->data = rdp->mppc_dec->history_buf + roff; comp_stream->p = comp_stream->data; comp_stream->size = rlen; } else { printf("decompress_rdp() failed\n"); return -1; } stream_seek(s, compressed_len - 18); } #ifdef WITH_DEBUG_RDP /* if (type != DATA_PDU_TYPE_UPDATE) */ DEBUG_RDP("recv %s Data PDU (0x%02X), length:%d", type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length); #endif switch (type) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, comp_stream)) return -1; break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, comp_stream)) return -1; break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, comp_stream)) return -1; break; case DATA_PDU_TYPE_INPUT: break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, comp_stream)) return -1; break; case DATA_PDU_TYPE_REFRESH_RECT: break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, comp_stream)) return -1; break; case DATA_PDU_TYPE_SUPPRESS_OUTPUT: break; case DATA_PDU_TYPE_SHUTDOWN_REQUEST: break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if(!rdp_recv_save_session_info(rdp, comp_stream)) return -1; break; case DATA_PDU_TYPE_FONT_LIST: break; case DATA_PDU_TYPE_FONT_MAP: if(!rdp_recv_font_map_pdu(rdp, comp_stream)) return -1; break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: break; case DATA_PDU_TYPE_BITMAP_CACHE_PERSISTENT_LIST: break; case DATA_PDU_TYPE_BITMAP_CACHE_ERROR: break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: break; case DATA_PDU_TYPE_OFFSCREEN_CACHE_ERROR: break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, comp_stream)) return -1; break; case DATA_PDU_TYPE_DRAW_NINEGRID_ERROR: break; case DATA_PDU_TYPE_DRAW_GDIPLUS_ERROR: break; case DATA_PDU_TYPE_ARC_STATUS: break; case DATA_PDU_TYPE_STATUS_INFO: break; case DATA_PDU_TYPE_MONITOR_LAYOUT: break; default: break; } if (comp_stream != s) { stream_detach(comp_stream); stream_free(comp_stream); } return 0; } BOOL rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, STREAM* s) { UINT16 type; UINT16 length; UINT16 channelId; if (!rdp_read_share_control_header(s, &length, &type, &channelId)) return FALSE; if (type == PDU_TYPE_DATA) { return (rdp_recv_data_pdu(rdp, s) < 0) ? FALSE : TRUE; } else if (type == PDU_TYPE_SERVER_REDIRECTION) { return rdp_recv_enhanced_security_redirection_packet(rdp, s); } else { return FALSE; } } /** * Decrypt an RDP packet.\n * @param rdp RDP module * @param s stream * @param length int */ BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; if (stream_get_left(s) < 12) return FALSE; stream_read_UINT16(s, len); /* 0x10 */ stream_read_BYTE(s, version); /* 0x1 */ stream_read_BYTE(s, pad); sig = s->p; stream_seek(s, 8); /* signature */ length -= 12; if (!security_fips_decrypt(s->p, length, rdp)) { printf("FATAL: cannot decrypt\n"); return FALSE; /* TODO */ } if (!security_fips_check_signature(s->p, length - pad, sig, rdp)) { printf("FATAL: invalid packet signature\n"); return FALSE; /* TODO */ } /* is this what needs adjusting? */ s->size -= pad; return TRUE; } if (stream_get_left(s) < 8) return FALSE; stream_read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); security_decrypt(s->p, length, rdp); if (securityFlags & SEC_SECURE_CHECKSUM) security_salted_mac_signature(rdp, s->p, length, FALSE, cmac); else security_mac_signature(rdp, s->p, length, cmac); if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { printf("WARNING: invalid packet signature\n"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ //return FALSE; } return TRUE; } /** * Process an RDP packet.\n * @param rdp RDP module * @param s stream */ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, STREAM* s) { UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId; UINT16 securityFlags; BYTE* nextp; if (!rdp_read_header(rdp, s, &length, &channelId)) { printf("Incorrect RDP header.\n"); return -1; } if (rdp->settings->DisableEncryption) { if (!rdp_read_security_header(s, &securityFlags)) return -1; if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { if (!rdp_decrypt(rdp, s, length - 4, securityFlags)) { printf("rdp_decrypt failed\n"); return -1; } } if (securityFlags & SEC_REDIRECTION_PKT) { /* * [MS-RDPBCGR] 2.2.13.2.1 * - no share control header, nor the 2 byte pad */ s->p -= 2; rdp_recv_enhanced_security_redirection_packet(rdp, s); return -1; } } if (channelId != MCS_GLOBAL_CHANNEL_ID) { if (!freerdp_channel_process(rdp->instance, s, channelId)) return -1; } else { while (stream_get_left(s) > 3) { stream_get_mark(s, nextp); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) return -1; nextp += pduLength; rdp->settings->PduSource = pduSource; switch (pduType) { case PDU_TYPE_DATA: if (rdp_recv_data_pdu(rdp, s) < 0) { printf("rdp_recv_data_pdu failed\n"); return -1; } break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) return -1; break; case PDU_TYPE_SERVER_REDIRECTION: if (!rdp_recv_enhanced_security_redirection_packet(rdp, s)) return -1; break; default: printf("incorrect PDU type: 0x%04X\n", pduType); break; } stream_set_mark(s, nextp); } } return 0; } static int rdp_recv_fastpath_pdu(rdpRdp* rdp, STREAM* s) { UINT16 length; rdpFastPath* fastpath; fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) return -1; if ((length == 0) || (length > stream_get_left(s))) { printf("incorrect FastPath PDU header length %d\n", length); return -1; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, length, flags)) return -1; } return fastpath_recv_updates(rdp->fastpath, s); } static int rdp_recv_pdu(rdpRdp* rdp, STREAM* s) { if (tpkt_verify_header(s)) return rdp_recv_tpkt_pdu(rdp, s); else return rdp_recv_fastpath_pdu(rdp, s); } /** * Receive an RDP packet.\n * @param rdp RDP module */ void rdp_recv(rdpRdp* rdp) { STREAM* s; s = transport_recv_stream_init(rdp->transport, 4096); transport_read(rdp->transport, s); rdp_recv_pdu(rdp, s); } static int rdp_recv_callback(rdpTransport* transport, STREAM* s, void* extra) { int status = 0; rdpRdp* rdp = (rdpRdp*) extra; switch (rdp->state) { case CONNECTION_STATE_NEGO: if (!rdp_client_connect_mcs_connect_response(rdp, s)) status = -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_client_connect_mcs_attach_user_confirm(rdp, s)) status = -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) status = -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_client_connect_license(rdp, s)) status = -1; break; case CONNECTION_STATE_CAPABILITY: if (!rdp_client_connect_demand_active(rdp, s)) status = -1; break; case CONNECTION_STATE_FINALIZATION: status = rdp_recv_pdu(rdp, s); if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE)) rdp->state = CONNECTION_STATE_ACTIVE; break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); break; default: printf("Invalid state %d\n", rdp->state); status = -1; break; } return status; } int rdp_send_channel_data(rdpRdp* rdp, int channel_id, BYTE* data, int size) { return freerdp_channel_send(rdp, channel_id, data, size); } /** * Set non-blocking mode information. * @param rdp RDP module * @param blocking blocking mode */ void rdp_set_blocking_mode(rdpRdp* rdp, BOOL blocking) { rdp->transport->ReceiveCallback = rdp_recv_callback; rdp->transport->ReceiveExtra = rdp; transport_set_blocking_mode(rdp->transport, blocking); } int rdp_check_fds(rdpRdp* rdp) { return transport_check_fds(&(rdp->transport)); } /** * Instantiate new RDP module. * @return new RDP module */ rdpRdp* rdp_new(freerdp* instance) { rdpRdp* rdp; rdp = (rdpRdp*) malloc(sizeof(rdpRdp)); if (rdp != NULL) { ZeroMemory(rdp, sizeof(rdpRdp)); rdp->instance = instance; rdp->settings = freerdp_settings_new((void*) instance); if (instance != NULL) instance->settings = rdp->settings; rdp->extension = extension_new(instance); rdp->transport = transport_new(rdp->settings); rdp->license = license_new(rdp); rdp->input = input_new(rdp); rdp->update = update_new(rdp); rdp->fastpath = fastpath_new(rdp); rdp->nego = nego_new(rdp->transport); rdp->mcs = mcs_new(rdp->transport); rdp->redirection = redirection_new(); rdp->mppc_dec = mppc_dec_new(); rdp->mppc_enc = mppc_enc_new(PROTO_RDP_50); } return rdp; } /** * Free RDP module. * @param rdp RDP module to be freed */ void rdp_free(rdpRdp* rdp) { if (rdp != NULL) { crypto_rc4_free(rdp->rc4_decrypt_key); crypto_rc4_free(rdp->rc4_encrypt_key); crypto_des3_free(rdp->fips_encrypt); crypto_des3_free(rdp->fips_decrypt); crypto_hmac_free(rdp->fips_hmac); freerdp_settings_free(rdp->settings); extension_free(rdp->extension); transport_free(rdp->transport); license_free(rdp->license); input_free(rdp->input); update_free(rdp->update); fastpath_free(rdp->fastpath); nego_free(rdp->nego); mcs_free(rdp->mcs); redirection_free(rdp->redirection); mppc_dec_free(rdp->mppc_dec); mppc_enc_free(rdp->mppc_enc); free(rdp); } }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5714_0
crossvul-cpp_data_bad_5108_3
/* packet-usb-video.c * * Forked from packet-usb-masstorage.c 35224 2010-12-20 05:35:29Z guy * which was authored by Ronnie Sahlberg (2006) * * usb video dissector * Steven J. Magnani 2013 * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include <epan/expert.h> #include "packet-usb.h" void proto_register_usb_vid(void); void proto_reg_handoff_usb_vid(void); /* References are to sections in USB Video Class specifications - * specifically V1.5, but versions have tended to keep * the same numbering (as of this writing). * * http://www.usb.org/developers/devclass_docs/USB_Video_Class_1_5.zip */ /* Table 2-1. Interrupt originators */ #define INT_VIDEOCONTROL 1 #define INT_VIDEOSTREAMING 2 #define INT_ORIGINATOR_MASK 0xF /* Table 2-2. Video Control Status Packet bAttribute */ #define CONTROL_CHANGE_VALUE 0x00 #define CONTROL_CHANGE_INFO 0x01 #define CONTROL_CHANGE_FAILURE 0x02 #define CONTROL_CHANGE_MIN 0x03 /* UVC 1.5+ */ #define CONTROL_CHANGE_MAX 0x04 /* UVC 1.5+ */ /* A.2 Video Interface Subclass Codes */ #define SC_UNDEFINED 0 #define SC_VIDEOCONTROL 1 #define SC_VIDEOSTREAMING 2 #define SC_VIDEO_INTERFACE_COLLECTION 3 /* A.4. Video Class-Specific Descriptor Types */ #define CS_INTERFACE 0x24 #define CS_ENDPOINT 0x25 /* A.5 Video Class-Specific VC Interface Descriptor Subtypes */ #define VC_HEADER 1 #define VC_INPUT_TERMINAL 2 #define VC_OUTPUT_TERMINAL 3 #define VC_SELECTOR_UNIT 4 #define VC_PROCESSING_UNIT 5 #define VC_EXTENSION_UNIT 6 #define VC_ENCODING_UNIT 7 /* A.6 Video Class-Specific VS Interface Descriptor Subtypes */ #define VS_UNDEFINED 0x00 #define VS_INPUT_HEADER 0x01 #define VS_OUTPUT_HEADER 0x02 #define VS_STILL_IMAGE_FRAME 0x03 #define VS_FORMAT_UNCOMPRESSED 0x04 #define VS_FRAME_UNCOMPRESSED 0x05 #define VS_FORMAT_MJPEG 0x06 #define VS_FRAME_MJPEG 0x07 #define VS_FORMAT_MPEG1 0x08 /* Pre-UVC 1.1 */ #define VS_FORMAT_MPEG2PS 0x09 /* Pre-UVC 1.1 */ #define VS_FORMAT_MPEG2TS 0x0A #define VS_FORMAT_MPEG4SL 0x0B /* Pre-UVC 1.1 */ #define VS_FORMAT_DV 0x0C #define VS_COLORFORMAT 0x0D #define VS_FORMAT_VENDOR 0x0E /* Pre-UVC 1.1 */ #define VS_FRAME_VENDOR 0x0F /* Pre-UVC 1.1 */ #define VS_FORMAT_FRAME_BASED 0x10 #define VS_FRAME_FRAME_BASED 0x11 #define VS_FORMAT_STREAM_BASED 0x12 #define VS_FORMAT_H264 0x13 /* UVC 1.5 */ #define VS_FRAME_H264 0x14 /* UVC 1.5 */ #define VS_FORMAT_H264_SIMULCAST 0x15 /* UVC 1.5 */ #define VS_FORMAT_VP8 0x16 /* UVC 1.5 */ #define VS_FRAME_VP8 0x17 /* UVC 1.5 */ #define VS_FORMAT_VP8_SIMULCAST 0x18 /* UVC 1.5 */ /* A.7 Video Class-Specific Endpoint Descriptor Subtypes */ #define EP_INTERRUPT 0x03 /* A.9.1 Video Control Interface Control Selectors */ #define VC_CONTROL_UNDEFINED 0x00 #define VC_VIDEO_POWER_MODE_CONTROL 0x01 #define VC_REQUEST_ERROR_CODE_CONTROL 0x02 #define VC_REQUEST_INDICATE_HOST_CLOCK_CONTROL 0x03 /* Pre-UVC 1.1 */ /* A.9.3 Selector Unit Control Selectors */ #define SU_CONTROL_UNDEFINED 0x00 #define SU_INPUT_SELECT_CONTROL 0x01 /* A.9.4 Camera Terminal Control Selectors */ #define CT_CONTROL_UNDEFINED 0x00 #define CT_SCANNING_MODE_CONTROL 0x01 #define CT_AE_MODE_CONTROL 0x02 #define CT_AE_PRIORITY_CONTROL 0x03 #define CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x04 #define CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x05 #define CT_FOCUS_ABSOLUTE_CONTROL 0x06 #define CT_FOCUS_RELATIVE_CONTROL 0x07 #define CT_FOCUS_AUTO_CONTROL 0x08 #define CT_IRIS_ABSOLUTE_CONTROL 0x09 #define CT_IRIS_RELATIVE_CONTROL 0x0A #define CT_ZOOM_ABSOLUTE_CONTROL 0x0B #define CT_ZOOM_RELATIVE_CONTROL 0x0C #define CT_PANTILT_ABSOLUTE_CONTROL 0x0D #define CT_PANTILT_RELATIVE_CONTROL 0x0E #define CT_ROLL_ABSOLUTE_CONTROL 0x0F #define CT_ROLL_RELATIVE_CONTROL 0x10 #define CT_PRIVACY_CONTROL 0x11 #define CT_FOCUS_SIMPLE_CONTROL 0x12 /* UVC 1.5 */ #define CT_WINDOW_CONTROL 0x13 /* UVC 1.5 */ #define CT_REGION_OF_INTEREST_CONTROL 0x14 /* UVC 1.5 */ /* A.9.5 Processing Unit Control Selectors */ #define PU_CONTROL_UNDEFINED 0x00 #define PU_BACKLIGHT_COMPENSATION_CONTROL 0x01 #define PU_BRIGHTNESS_CONTROL 0x02 #define PU_CONTRAST_CONTROL 0x03 #define PU_GAIN_CONTROL 0x04 #define PU_POWER_LINE_FREQUENCY_CONTROL 0x05 #define PU_HUE_CONTROL 0x06 #define PU_SATURATION_CONTROL 0x07 #define PU_SHARPNESS_CONTROL 0x08 #define PU_GAMMA_CONTROL 0x09 #define PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x0A #define PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x0B #define PU_WHITE_BALANCE_COMPONENT_CONTROL 0x0C #define PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x0D #define PU_DIGITAL_MULTIPLIER_CONTROL 0x0E #define PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x0F #define PU_HUE_AUTO_CONTROL 0x10 #define PU_ANALOG_VIDEO_STANDARD_CONTROL 0x11 #define PU_ANALOG_LOCK_STATUS_CONTROL 0x12 #define PU_CONTRAST_AUTO_CONTROL 0x13 /* A.9.7 VideoStreaming Interface Control Selectors */ #define VS_CONTROL_UNDEFINED 0x00 #define VS_PROBE_CONTROL 0x01 #define VS_COMMIT_CONTROL 0x02 #define VS_STILL_PROBE_CONTROL 0x03 #define VS_STILL_COMMIT_CONTROL 0x04 #define VS_STILL_IMAGE_TRIGGER_CONTROL 0x05 #define VS_STREAM_ERROR_CODE_CONTROL 0x06 #define VS_GENERATE_KEY_FRAME_CONTROL 0x07 #define VS_UPDATE_FRAME_SEGMENT_CONTROL 0x08 #define VS_SYNCH_DELAY_CONTROL 0x09 /* Appendix B Terminal Types */ #define TT_VENDOR_SPECIFIC 0x100 #define TT_STREAMING 0x101 #define ITT_VENDOR_SPECIFIC 0x200 #define ITT_CAMERA 0x201 #define ITT_MEDIA_TRANSPORT_INPUT 0x202 #define OTT_VENDOR_SPECIFIC 0x300 #define OTT_DISPLAY 0x301 #define OTT_MEDIA_TRANSPORT_OUTPUT 0x302 #define EXTERNAL_VENDOR_SPECIFIC 0x400 #define COMPOSITE_CONNECTOR 0x401 #define SVIDEO_CONNECTOR 0x402 #define COMPONENT_CONNECTOR 0x403 /* Table 2-2 Status Packet Format (VideoControl Interface as the Originator) */ #define CONTROL_INTERRUPT_EVENT_CONTROL_CHANGE 0 /* Table 4-7 Request Error Code Control bRequestErrorCode */ #define UVC_ERROR_NONE 0 #define UVC_ERROR_NOT_READY 1 #define UVC_ERROR_WRONG_STATE 2 #define UVC_ERROR_POWER 3 #define UVC_ERROR_OUT_OF_RANGE 4 #define UVC_ERROR_INVALID_UNIT 5 #define UVC_ERROR_INVALID_CONTROL 6 #define UVC_ERROR_INVALID_REQUEST 7 #define UVC_ERROR_INVALID_VALUE 8 #define UVC_ERROR_UNKNOWN 255 /* A.8 Video Class-Specific Request Codes */ #define USB_SETUP_SET_CUR 0x01 #define USB_SETUP_SET_CUR_ALL 0x11 /* UVC 1.5 */ #define USB_SETUP_GET_CUR 0x81 #define USB_SETUP_GET_MIN 0x82 #define USB_SETUP_GET_MAX 0x83 #define USB_SETUP_GET_RES 0x84 #define USB_SETUP_GET_LEN 0x85 #define USB_SETUP_GET_INFO 0x86 #define USB_SETUP_GET_DEF 0x87 #define USB_SETUP_GET_CUR_ALL 0x91 /* UVC 1.5 */ #define USB_SETUP_GET_MIN_ALL 0x92 /* UVC 1.5 */ #define USB_SETUP_GET_MAX_ALL 0x93 /* UVC 1.5 */ #define USB_SETUP_GET_RES_ALL 0x94 /* UVC 1.5 */ #define USB_SETUP_GET_DEF_ALL 0x97 /* UVC 1.5 */ /* protocols and header fields */ static int proto_usb_vid = -1; static int hf_usb_vid_control_entity = -1; static int hf_usb_vid_control_interface = -1; static int hf_usb_vid_control_selector = -1; static int hf_usb_vid_epdesc_subtype = -1; static int hf_usb_vid_epdesc_max_transfer_sz = -1; static int hf_usb_vid_control_ifdesc_subtype = -1; static int hf_usb_vid_control_ifdesc_terminal_id = -1; static int hf_usb_vid_control_ifdesc_terminal_type = -1; static int hf_usb_vid_control_ifdesc_assoc_terminal = -1; static int hf_usb_vid_streaming_ifdesc_subtype = -1; static int hf_usb_vid_streaming_ifdesc_bNumFormats = -1; static int hf_usb_vid_control_ifdesc_unit_id = -1; static int hf_usb_vid_request = -1; static int hf_usb_vid_length = -1; static int hf_usb_vid_interrupt_bStatusType = -1; static int hf_usb_vid_interrupt_bOriginator = -1; static int hf_usb_vid_interrupt_bAttribute = -1; static int hf_usb_vid_control_interrupt_bEvent = -1; static int hf_usb_vid_control_ifdesc_bcdUVC = -1; static int hf_usb_vid_ifdesc_wTotalLength = -1; static int hf_usb_vid_control_ifdesc_dwClockFrequency = -1; static int hf_usb_vid_control_ifdesc_bInCollection = -1; static int hf_usb_vid_control_ifdesc_baInterfaceNr = -1; static int hf_usb_vid_control_ifdesc_iTerminal = -1; static int hf_usb_vid_control_ifdesc_src_id = -1; static int hf_usb_vid_cam_objective_focal_len_min = -1; static int hf_usb_vid_cam_objective_focal_len_max = -1; static int hf_usb_vid_cam_ocular_focal_len = -1; static int hf_usb_vid_bControlSize = -1; static int hf_usb_vid_bmControl = -1; static int hf_usb_vid_bmControl_bytes = -1; static int hf_usb_vid_control_default = -1; static int hf_usb_vid_control_min = -1; static int hf_usb_vid_control_max = -1; static int hf_usb_vid_control_res = -1; static int hf_usb_vid_control_cur = -1; static int hf_usb_vid_control_info = -1; static int hf_usb_vid_control_info_D[7] = { -1, -1, -1, -1, -1, -1, -1 }; static int hf_usb_vid_control_length = -1; static int hf_usb_vid_cam_control_D[22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static int hf_usb_vid_proc_control_D[19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static int hf_usb_vid_proc_standards_D[6] = { -1, -1, -1, -1, -1, -1 }; static int hf_usb_vid_exten_guid = -1; static int hf_usb_vid_exten_num_controls = -1; static int hf_usb_vid_num_inputs = -1; static int hf_usb_vid_sources = -1; static int hf_usb_vid_streaming_bmInfo = -1; static int hf_usb_vid_streaming_info_D[1] = { -1 }; static int hf_usb_vid_streaming_terminal_link = -1; static int hf_usb_vid_streaming_still_capture_method = -1; static int hf_usb_vid_streaming_trigger_support = -1; static int hf_usb_vid_streaming_trigger_usage = -1; static int hf_usb_vid_streaming_control_D[6] = { -1, -1, -1, -1, -1, -1 }; static int hf_usb_vid_format_index = -1; static int hf_usb_vid_format_num_frame_descriptors = -1; static int hf_usb_vid_format_guid = -1; static int hf_usb_vid_format_bits_per_pixel = -1; static int hf_usb_vid_default_frame_index = -1; static int hf_usb_vid_aspect_ratio_x = -1; static int hf_usb_vid_aspect_ratio_y = -1; static int hf_usb_vid_interlace_flags = -1; static int hf_usb_vid_is_interlaced = -1; static int hf_usb_vid_interlaced_fields = -1; static int hf_usb_vid_field_1_first = -1; static int hf_usb_vid_field_pattern = -1; static int hf_usb_vid_copy_protect = -1; static int hf_usb_vid_variable_size = -1; static int hf_usb_vid_frame_index = -1; static int hf_usb_vid_frame_capabilities = -1; static int hf_usb_vid_frame_stills_supported = -1; static int hf_usb_vid_frame_fixed_frame_rate = -1; static int hf_usb_vid_frame_width = -1; static int hf_usb_vid_frame_height = -1; static int hf_usb_vid_frame_min_bit_rate = -1; static int hf_usb_vid_frame_max_bit_rate = -1; static int hf_usb_vid_frame_max_frame_sz = -1; static int hf_usb_vid_frame_default_interval = -1; static int hf_usb_vid_frame_bytes_per_line = -1; static int hf_usb_vid_mjpeg_flags = -1; static int hf_usb_vid_mjpeg_fixed_samples = -1; static int hf_usb_vid_probe_hint = -1; static int hf_usb_vid_probe_hint_D[5] = { -1, -1, -1, -1, -1 }; static int hf_usb_vid_frame_interval = -1; static int hf_usb_vid_probe_key_frame_rate = -1; static int hf_usb_vid_probe_p_frame_rate = -1; static int hf_usb_vid_probe_comp_quality = -1; static int hf_usb_vid_probe_comp_window = -1; static int hf_usb_vid_probe_delay = -1; static int hf_usb_vid_probe_max_frame_sz = -1; static int hf_usb_vid_probe_max_payload_sz = -1; static int hf_usb_vid_probe_clock_freq = -1; static int hf_usb_vid_probe_framing = -1; static int hf_usb_vid_probe_framing_D[2] = { -1, -1 }; static int hf_usb_vid_probe_preferred_ver = -1; static int hf_usb_vid_probe_min_ver = -1; static int hf_usb_vid_probe_max_ver = -1; static int hf_usb_vid_frame_interval_type = -1; static int hf_usb_vid_frame_min_interval = -1; static int hf_usb_vid_frame_max_interval = -1; static int hf_usb_vid_frame_step_interval = -1; static int hf_usb_vid_color_primaries = -1; static int hf_usb_vid_transfer_characteristics = -1; static int hf_usb_vid_matrix_coefficients = -1; static int hf_usb_vid_max_multiplier = -1; static int hf_usb_vid_iProcessing = -1; static int hf_usb_vid_iExtension = -1; static int hf_usb_vid_iSelector = -1; static int hf_usb_vid_proc_standards = -1; static int hf_usb_vid_request_error = -1; static int hf_usb_vid_descriptor_data = -1; static int hf_usb_vid_control_data = -1; static int hf_usb_vid_control_value = -1; static int hf_usb_vid_value_data = -1; /* Subtrees */ static gint ett_usb_vid = -1; static gint ett_descriptor_video_endpoint = -1; static gint ett_descriptor_video_control = -1; static gint ett_descriptor_video_streaming = -1; static gint ett_camera_controls = -1; static gint ett_processing_controls = -1; static gint ett_streaming_controls = -1; static gint ett_streaming_info = -1; static gint ett_interlace_flags = -1; static gint ett_frame_capability_flags = -1; static gint ett_mjpeg_flags = -1; static gint ett_video_probe = -1; static gint ett_probe_hint = -1; static gint ett_probe_framing = -1; static gint ett_video_standards = -1; static gint ett_control_capabilities = -1; static expert_field ei_usb_vid_subtype_unknown = EI_INIT; static expert_field ei_usb_vid_bitmask_len = EI_INIT; /* Lookup tables */ static const value_string vc_ep_descriptor_subtypes[] = { { EP_INTERRUPT, "Interrupt" }, { 0, NULL } }; static const value_string vid_descriptor_type_vals[] = { {CS_INTERFACE, "video class interface"}, {CS_ENDPOINT, "video class endpoint"}, {0,NULL} }; static value_string_ext vid_descriptor_type_vals_ext = VALUE_STRING_EXT_INIT(vid_descriptor_type_vals); static const value_string vc_if_descriptor_subtypes[] = { { VC_HEADER, "Header" }, { VC_INPUT_TERMINAL, "Input Terminal" }, { VC_OUTPUT_TERMINAL, "Output Terminal" }, { VC_SELECTOR_UNIT, "Selector Unit" }, { VC_PROCESSING_UNIT, "Processing Unit" }, { VC_EXTENSION_UNIT, "Extension Unit" }, { VC_ENCODING_UNIT, "Encoding Unit" }, { 0, NULL } }; static value_string_ext vc_if_descriptor_subtypes_ext = VALUE_STRING_EXT_INIT(vc_if_descriptor_subtypes); static const value_string cs_control_interface[] = { { VC_CONTROL_UNDEFINED, "Undefined" }, { VC_VIDEO_POWER_MODE_CONTROL, "Video Power Mode" }, { VC_REQUEST_ERROR_CODE_CONTROL, "Request Error Code" }, { VC_REQUEST_INDICATE_HOST_CLOCK_CONTROL, "Request Indicate Host Clock" }, { 0, NULL } }; static value_string_ext cs_control_interface_ext = VALUE_STRING_EXT_INIT(cs_control_interface); static const value_string cs_streaming_interface[] = { { VS_CONTROL_UNDEFINED, "Undefined" }, { VS_PROBE_CONTROL, "Probe" }, { VS_COMMIT_CONTROL, "Commit" }, { VS_STILL_PROBE_CONTROL, "Still Probe" }, { VS_STILL_COMMIT_CONTROL, "Still Commit" }, { VS_STILL_IMAGE_TRIGGER_CONTROL, "Still Image Trigger" }, { VS_STREAM_ERROR_CODE_CONTROL, "Stream Error Code" }, { VS_GENERATE_KEY_FRAME_CONTROL, "Generate Key Frame" }, { VS_UPDATE_FRAME_SEGMENT_CONTROL, "Update Frame Segment" }, { VS_SYNCH_DELAY_CONTROL, "Synch Delay" }, { 0, NULL } }; static value_string_ext cs_streaming_interface_ext = VALUE_STRING_EXT_INIT(cs_streaming_interface); static const value_string cs_selector_unit[] = { { SU_CONTROL_UNDEFINED, "Undefined" }, { SU_INPUT_SELECT_CONTROL, "Input Select" }, { 0, NULL } }; static value_string_ext cs_selector_unit_ext = VALUE_STRING_EXT_INIT(cs_selector_unit); static const value_string cs_camera_terminal[] = { { CT_CONTROL_UNDEFINED, "Undefined" }, { CT_SCANNING_MODE_CONTROL, "Scanning Mode" }, { CT_AE_MODE_CONTROL, "Auto-Exposure Mode" }, { CT_AE_PRIORITY_CONTROL, "Auto-Exposure Priority" }, { CT_EXPOSURE_TIME_ABSOLUTE_CONTROL, "Exposure Time (Absolute)" }, { CT_EXPOSURE_TIME_RELATIVE_CONTROL, "Exposure Time (Relative)" }, { CT_FOCUS_ABSOLUTE_CONTROL, "Focus (Absolute)" }, { CT_FOCUS_RELATIVE_CONTROL, "Focus (Relative)" }, { CT_FOCUS_AUTO_CONTROL, "Focus, Auto" }, { CT_IRIS_ABSOLUTE_CONTROL, "Iris (Absolute)" }, { CT_IRIS_RELATIVE_CONTROL, "Iris (Relative)" }, { CT_ZOOM_ABSOLUTE_CONTROL, "Zoom (Absolute)" }, { CT_ZOOM_RELATIVE_CONTROL, "Zoom (Relative)" }, { CT_PANTILT_ABSOLUTE_CONTROL, "PanTilt (Absolute)" }, { CT_PANTILT_RELATIVE_CONTROL, "PanTilt (Relative)" }, { CT_ROLL_ABSOLUTE_CONTROL, "Roll (Absolute)" }, { CT_ROLL_RELATIVE_CONTROL, "Roll (Relative)" }, { CT_PRIVACY_CONTROL, "Privacy" }, { CT_FOCUS_SIMPLE_CONTROL, "Focus (Simple)" }, { CT_WINDOW_CONTROL, "Window" }, { CT_REGION_OF_INTEREST_CONTROL, "Region of Interest" }, { 0, NULL } }; static value_string_ext cs_camera_terminal_ext = VALUE_STRING_EXT_INIT(cs_camera_terminal); static const value_string cs_processing_unit[] = { { PU_CONTROL_UNDEFINED, "Undefined" }, { PU_BACKLIGHT_COMPENSATION_CONTROL, "Backlight Compensation" }, { PU_BRIGHTNESS_CONTROL, "Brightness" }, { PU_CONTRAST_CONTROL, "Contrast" }, { PU_GAIN_CONTROL, "Gain" }, { PU_POWER_LINE_FREQUENCY_CONTROL, "Power Line Frequency" }, { PU_HUE_CONTROL, "Hue" }, { PU_SATURATION_CONTROL, "Saturation" }, { PU_SHARPNESS_CONTROL, "Sharpness" }, { PU_GAMMA_CONTROL, "Gamma" }, { PU_WHITE_BALANCE_TEMPERATURE_CONTROL, "White Balance Temperature" }, { PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL,"White Balance Temperature Auto" }, { PU_WHITE_BALANCE_COMPONENT_CONTROL, "White Balance Component" }, { PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL, "White Balance Component Auto" }, { PU_DIGITAL_MULTIPLIER_CONTROL, "Digital Multiplier" }, { PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL, "Digital Multiplier Limit" }, { PU_HUE_AUTO_CONTROL, "Hue Auto" }, { PU_ANALOG_VIDEO_STANDARD_CONTROL, "Video Standard" }, { PU_ANALOG_LOCK_STATUS_CONTROL, "Analog Lock Status" }, { PU_CONTRAST_AUTO_CONTROL, "Contrast Auto" }, { 0, NULL } }; static value_string_ext cs_processing_unit_ext = VALUE_STRING_EXT_INIT(cs_processing_unit); static const value_string vc_terminal_types[] = { { TT_VENDOR_SPECIFIC, "Vendor Specific", }, { TT_STREAMING, "Streaming" }, { ITT_VENDOR_SPECIFIC, "Vendor Specific Input" }, { ITT_CAMERA, "Camera Input" }, { ITT_MEDIA_TRANSPORT_INPUT, "Media Transport Input" }, { OTT_VENDOR_SPECIFIC, "Vendor Specific Output" }, { OTT_DISPLAY, "Display Output" }, { OTT_MEDIA_TRANSPORT_OUTPUT, "Media Transport Output" }, { EXTERNAL_VENDOR_SPECIFIC, "Vendor Specific External" }, { COMPOSITE_CONNECTOR, "Composite Connector" }, { SVIDEO_CONNECTOR, "SVideo Connector" }, { COMPONENT_CONNECTOR, "Component Connector" }, { 0, NULL } }; static value_string_ext vc_terminal_types_ext = VALUE_STRING_EXT_INIT(vc_terminal_types); static const value_string vs_if_descriptor_subtypes[] = { { VS_UNDEFINED, "Undefined" }, { VS_INPUT_HEADER, "Input Header" }, { VS_OUTPUT_HEADER, "Output Header" }, { VS_STILL_IMAGE_FRAME, "Still Image Frame" }, { VS_FORMAT_UNCOMPRESSED, "Format Uncompressed" }, { VS_FRAME_UNCOMPRESSED, "Frame Uncompressed" }, { VS_FORMAT_MJPEG, "Format MJPEG" }, { VS_FRAME_MJPEG, "Frame MJPEG" }, { VS_FORMAT_MPEG1, "Format MPEG1" }, { VS_FORMAT_MPEG2PS, "Format MPEG2-PS" }, { VS_FORMAT_MPEG2TS, "Format MPEG2-TS" }, { VS_FORMAT_MPEG4SL, "Format MPEG4-SL" }, { VS_FORMAT_DV, "Format DV" }, { VS_COLORFORMAT, "Colorformat" }, { VS_FORMAT_VENDOR, "Format Vendor" }, { VS_FRAME_VENDOR, "Frame Vendor" }, { VS_FORMAT_FRAME_BASED, "Format Frame-Based" }, { VS_FRAME_FRAME_BASED, "Frame Frame-Based" }, { VS_FORMAT_STREAM_BASED, "Format Stream Based" }, { VS_FORMAT_H264, "Format H.264" }, { VS_FRAME_H264, "Frame H.264" }, { VS_FORMAT_H264_SIMULCAST, "Format H.264 Simulcast" }, { VS_FORMAT_VP8, "Format VP8" }, { VS_FRAME_VP8, "Frame VP8" }, { VS_FORMAT_VP8_SIMULCAST, "Format VP8 Simulcast" }, { 0, NULL } }; static value_string_ext vs_if_descriptor_subtypes_ext = VALUE_STRING_EXT_INIT(vs_if_descriptor_subtypes); static const value_string interrupt_status_types[] = { { INT_VIDEOCONTROL, "VideoControl Interface" }, { INT_VIDEOSTREAMING, "VideoStreaming Interface" }, { 0, NULL } }; static const value_string control_change_types[] = { { CONTROL_CHANGE_VALUE, "Value" }, { CONTROL_CHANGE_INFO, "Info" }, { CONTROL_CHANGE_FAILURE, "Failure" }, { CONTROL_CHANGE_MIN, "Min" }, { CONTROL_CHANGE_MAX, "Max" }, { 0, NULL } }; static value_string_ext control_change_types_ext = VALUE_STRING_EXT_INIT(control_change_types); static const value_string control_interrupt_events[] = { { CONTROL_INTERRUPT_EVENT_CONTROL_CHANGE, "Control Change" }, { 0, NULL } }; /* Table 3-13 VS Interface Input Header Descriptor - bStillCaptureMethod field */ static const value_string vs_still_capture_methods[] = { { 0, "None" }, { 1, "Uninterrupted streaming" }, { 2, "Suspended streaming" }, { 3, "Dedicated pipe" }, { 0, NULL } }; static value_string_ext vs_still_capture_methods_ext = VALUE_STRING_EXT_INIT(vs_still_capture_methods); /* Table 3-13 VS Interface Input Header Descriptor - bTriggerUsage field */ static const value_string vs_trigger_usage[] = { { 0, "Initiate still image capture" }, { 1, "General purpose button event" }, { 0, NULL } }; /* bmInterlaceFlags for format descriptors */ static const true_false_string is_interlaced_meaning = { "Interlaced", "Non-interlaced" }; /* bmInterlaceFlags for format descriptors */ static const true_false_string interlaced_fields_meaning = { "1 field", "2 fields" }; /* bmInterlaceFlags for format descriptors */ static const value_string field_pattern_meaning[] = { { 0, "Field 1 only" }, { 1, "Field 2 only" }, { 2, "Regular pattern of fields 1 and 2" }, { 3, "Random pattern of fields 1 and 2" }, {0, NULL}, }; static value_string_ext field_pattern_meaning_ext = VALUE_STRING_EXT_INIT(field_pattern_meaning); /* bCopyProtect for format descriptors */ static const value_string copy_protect_meaning[] = { { 0, "No restrictions" }, { 1, "Restrict duplication" }, {0, NULL}, }; /* Table 4-46 Video Probe and Commit Controls - bmHint field */ static const true_false_string probe_hint_meaning = { "Constant", "Variable" }; /* Table 3-19 Color Matching Descriptor - bColorPrimaries field */ static const value_string color_primaries_meaning[] = { { 0, "Unspecified" }, { 1, "BT.709, sRGB" }, { 2, "BT.470-2 (M)" }, { 3, "BT.470-2 (B,G)" }, { 4, "SMPTE 170M" }, { 5, "SMPTE 240M" }, {0, NULL}, }; static value_string_ext color_primaries_meaning_ext = VALUE_STRING_EXT_INIT(color_primaries_meaning); /* Table 3-19 Color Matching Descriptor - bTransferCharacteristics field */ static const value_string color_transfer_characteristics[] = { { 0, "Unspecified" }, { 1, "BT.709" }, { 2, "BT.470-2 (M)" }, { 3, "BT.470-2 (B,G)" }, { 4, "SMPTE 170M" }, { 5, "SMPTE 240M" }, { 6, "Linear (V=Lc)" }, { 7, "sRGB" }, {0, NULL}, }; static value_string_ext color_transfer_characteristics_ext = VALUE_STRING_EXT_INIT(color_transfer_characteristics); /* Table 3-19 Color Matching Descriptor - bMatrixCoefficients field */ static const value_string matrix_coefficients_meaning[] = { { 0, "Unspecified" }, { 1, "BT.709" }, { 2, "FCC" }, { 3, "BT.470-2 (B,G)" }, { 4, "SMPTE 170M (BT.601)" }, { 5, "SMPTE 240M" }, {0, NULL}, }; static value_string_ext matrix_coefficients_meaning_ext = VALUE_STRING_EXT_INIT(matrix_coefficients_meaning); static const value_string request_error_codes[] = { { UVC_ERROR_NONE, "No error" }, { UVC_ERROR_NOT_READY, "Not ready" }, { UVC_ERROR_WRONG_STATE, "Wrong state" }, { UVC_ERROR_POWER, "Insufficient power" } , { UVC_ERROR_OUT_OF_RANGE, "Out of range" }, { UVC_ERROR_INVALID_UNIT, "Invalid unit" }, { UVC_ERROR_INVALID_CONTROL, "Invalid control" }, { UVC_ERROR_INVALID_REQUEST, "Invalid request" }, { UVC_ERROR_INVALID_VALUE, "Invalid value within range" }, { UVC_ERROR_UNKNOWN, "Unknown" }, {0, NULL}, }; static value_string_ext request_error_codes_ext = VALUE_STRING_EXT_INIT(request_error_codes); /* There is one such structure per terminal or unit per interface */ typedef struct { guint8 entityID; guint8 subtype; guint16 terminalType; } video_entity_t; /* video_entity_t's (units/terminals) associated with each video interface */ /* There is one such structure for each video conversation (interface) */ typedef struct _video_conv_info_t { wmem_tree_t* entities; /* indexed by entity ID */ } video_conv_info_t; /*****************************************************************************/ /* UTILITY FUNCTIONS */ /*****************************************************************************/ /** * Dissector for variable-length bmControl bitmask / bControlSize pair. * * Creates an item for bControlSize, and a subtree for the bmControl bitmask. * * @param tree protocol tree to be the parent of the bitmask subtree * @param tvb the tv_buff with the (remaining) packet data * @param offset where in tvb to find bControlSize field * @param ett_subtree index of the subtree to use for this bitmask * @param bm_items NULL-terminated array of pointers that lists all the fields * of the bitmask * * @return offset within tvb at which dissection should continue */ static int dissect_bmControl(proto_tree *tree, tvbuff_t *tvb, int offset, gint ett_subtree, const int** bm_items) { guint8 bm_size = 0; bm_size = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_bControlSize, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (bm_size > 0) { proto_tree_add_bitmask_len(tree, tvb, offset, bm_size, hf_usb_vid_bmControl, ett_subtree, bm_items, &ei_usb_vid_bitmask_len, ENC_LITTLE_ENDIAN); offset += bm_size; } return offset; } /*****************************************************************************/ /* VIDEO CONTROL DESCRIPTORS */ /*****************************************************************************/ /* Dissect a Camera Terminal descriptor */ static int dissect_usb_video_camera_terminal(proto_tree *tree, tvbuff_t *tvb, int offset) { static const int *control_bits[] = { &hf_usb_vid_cam_control_D[0], &hf_usb_vid_cam_control_D[1], &hf_usb_vid_cam_control_D[2], &hf_usb_vid_cam_control_D[3], &hf_usb_vid_cam_control_D[4], &hf_usb_vid_cam_control_D[5], &hf_usb_vid_cam_control_D[6], &hf_usb_vid_cam_control_D[7], &hf_usb_vid_cam_control_D[8], &hf_usb_vid_cam_control_D[9], &hf_usb_vid_cam_control_D[10], &hf_usb_vid_cam_control_D[11], &hf_usb_vid_cam_control_D[12], &hf_usb_vid_cam_control_D[13], &hf_usb_vid_cam_control_D[14], &hf_usb_vid_cam_control_D[15], &hf_usb_vid_cam_control_D[16], &hf_usb_vid_cam_control_D[17], &hf_usb_vid_cam_control_D[18], &hf_usb_vid_cam_control_D[19], &hf_usb_vid_cam_control_D[20], &hf_usb_vid_cam_control_D[21], NULL }; DISSECTOR_ASSERT(array_length(control_bits) == (1+array_length(hf_usb_vid_cam_control_D))); proto_tree_add_item(tree, hf_usb_vid_cam_objective_focal_len_min, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_vid_cam_objective_focal_len_max, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_vid_cam_ocular_focal_len, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; offset = dissect_bmControl(tree, tvb, offset, ett_camera_controls, control_bits); return offset; } /* Dissect a Processing Unit descriptor */ static int dissect_usb_video_processing_unit(proto_tree *tree, tvbuff_t *tvb, int offset) { static const int *control_bits[] = { &hf_usb_vid_proc_control_D[0], &hf_usb_vid_proc_control_D[1], &hf_usb_vid_proc_control_D[2], &hf_usb_vid_proc_control_D[3], &hf_usb_vid_proc_control_D[4], &hf_usb_vid_proc_control_D[5], &hf_usb_vid_proc_control_D[6], &hf_usb_vid_proc_control_D[7], &hf_usb_vid_proc_control_D[8], &hf_usb_vid_proc_control_D[9], &hf_usb_vid_proc_control_D[10], &hf_usb_vid_proc_control_D[11], &hf_usb_vid_proc_control_D[12], &hf_usb_vid_proc_control_D[13], &hf_usb_vid_proc_control_D[14], &hf_usb_vid_proc_control_D[15], &hf_usb_vid_proc_control_D[16], &hf_usb_vid_proc_control_D[17], &hf_usb_vid_proc_control_D[18], NULL }; DISSECTOR_ASSERT(array_length(control_bits) == (1+array_length(hf_usb_vid_proc_control_D))); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_src_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_max_multiplier, tvb, offset+1, 2, ENC_LITTLE_ENDIAN); offset += 3; offset = dissect_bmControl(tree, tvb, offset, ett_processing_controls, control_bits); proto_tree_add_item(tree, hf_usb_vid_iProcessing, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; /* UVC 1.1 added bmVideoStandards */ if (tvb_reported_length_remaining(tvb, offset) > 0) { static const int *standard_bits[] = { &hf_usb_vid_proc_standards_D[0], &hf_usb_vid_proc_standards_D[1], &hf_usb_vid_proc_standards_D[2], &hf_usb_vid_proc_standards_D[3], &hf_usb_vid_proc_standards_D[4], &hf_usb_vid_proc_standards_D[5], NULL }; DISSECTOR_ASSERT(array_length(standard_bits) == (1+array_length(hf_usb_vid_proc_standards_D))); proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_proc_standards, ett_video_standards, standard_bits, ENC_NA); ++offset; } return offset; } /* Dissect a Selector Unit descriptor */ static int dissect_usb_video_selector_unit(proto_tree *tree, tvbuff_t *tvb, int offset) { guint8 num_inputs; num_inputs = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_num_inputs, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (num_inputs > 0) { proto_tree_add_item(tree, hf_usb_vid_sources, tvb, offset, num_inputs, ENC_NA); offset += num_inputs; } proto_tree_add_item(tree, hf_usb_vid_iSelector, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; return offset; } /* Dissect an Extension Unit descriptor */ static int dissect_usb_video_extension_unit(proto_tree *tree, tvbuff_t *tvb, int offset) { guint8 num_inputs; guint8 control_size; proto_tree_add_item(tree, hf_usb_vid_exten_guid, tvb, offset, 16, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_exten_num_controls, tvb, offset+16, 1, ENC_LITTLE_ENDIAN); offset += 17; num_inputs = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_num_inputs, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (num_inputs > 0) { proto_tree_add_item(tree, hf_usb_vid_sources, tvb, offset, num_inputs, ENC_NA); offset += num_inputs; } control_size = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_bControlSize, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (control_size > 0) { if (control_size <= proto_registrar_get_length(hf_usb_vid_bmControl)) { proto_tree_add_item(tree, hf_usb_vid_bmControl, tvb, offset, control_size, ENC_LITTLE_ENDIAN); } else { /* Too big to display as integer */ /* @todo Display as FT_BYTES with a big-endian disclaimer? * See https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=7933 */ proto_tree_add_bytes_format(tree, hf_usb_vid_bmControl_bytes, tvb, offset, control_size, NULL, "bmControl"); } offset += control_size; } proto_tree_add_item(tree, hf_usb_vid_iExtension, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; return offset; } /** * Dissector for video class control interface descriptors * * @param parent_tree the protocol tree to be the parent of the descriptor subtree * @param tvb the tv_buff with the (remaining) packet data * On entry the gaze is set to the descriptor length field. * @param descriptor_len Length of the descriptor to dissect * @param pinfo Information associated with the packet being dissected * * @return offset within tvb at which dissection should continue */ static int dissect_usb_video_control_interface_descriptor(proto_tree *parent_tree, tvbuff_t *tvb, guint8 descriptor_len, packet_info *pinfo, usb_conv_info_t *usb_conv_info) { video_conv_info_t *video_conv_info = NULL; video_entity_t *entity = NULL; proto_item *item = NULL; proto_item *subtype_item = NULL; proto_tree *tree = NULL; guint8 entity_id = 0; guint16 terminal_type = 0; int offset = 0; guint8 subtype; subtype = tvb_get_guint8(tvb, offset+2); if (parent_tree) { const gchar *subtype_str; subtype_str = val_to_str_ext(subtype, &vc_if_descriptor_subtypes_ext, "Unknown (0x%x)"); tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len, ett_descriptor_video_control, &item, "VIDEO CONTROL INTERFACE DESCRIPTOR [%s]", subtype_str); } /* Common fields */ dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext); subtype_item = proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; if (subtype == VC_HEADER) { guint8 num_vs_interfaces; proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bcdUVC, tvb, offset, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_ifdesc_wTotalLength, tvb, offset+2, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_dwClockFrequency, tvb, offset+4, 4, ENC_LITTLE_ENDIAN); num_vs_interfaces = tvb_get_guint8(tvb, offset+8); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bInCollection, tvb, offset+8, 1, ENC_LITTLE_ENDIAN); if (num_vs_interfaces > 0) { proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_baInterfaceNr, tvb, offset+9, num_vs_interfaces, ENC_NA); } offset += 9 + num_vs_interfaces; } else if ((subtype == VC_INPUT_TERMINAL) || (subtype == VC_OUTPUT_TERMINAL)) { /* Fields common to input and output terminals */ entity_id = tvb_get_guint8(tvb, offset); terminal_type = tvb_get_letohs(tvb, offset+1); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_type, tvb, offset+1, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_assoc_terminal, tvb, offset+3, 1, ENC_LITTLE_ENDIAN); offset += 4; if (subtype == VC_OUTPUT_TERMINAL) { proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_src_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; } proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_iTerminal, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (subtype == VC_INPUT_TERMINAL) { if (terminal_type == ITT_CAMERA) { offset = dissect_usb_video_camera_terminal(tree, tvb, offset); } else if (terminal_type == ITT_MEDIA_TRANSPORT_INPUT) { /* @todo */ } } if (subtype == VC_OUTPUT_TERMINAL) { if (terminal_type == OTT_MEDIA_TRANSPORT_OUTPUT) { /* @todo */ } } } else { /* Field common to extension / processing / selector / encoding units */ entity_id = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_unit_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (subtype == VC_PROCESSING_UNIT) { offset = dissect_usb_video_processing_unit(tree, tvb, offset); } else if (subtype == VC_SELECTOR_UNIT) { offset = dissect_usb_video_selector_unit(tree, tvb, offset); } else if (subtype == VC_EXTENSION_UNIT) { offset = dissect_usb_video_extension_unit(tree, tvb, offset); } else if (subtype == VC_ENCODING_UNIT) { /* @todo UVC 1.5 */ } else { expert_add_info_format(pinfo, subtype_item, &ei_usb_vid_subtype_unknown, "Unknown VC subtype %u", subtype); } } /* Soak up descriptor bytes beyond those we know how to dissect */ if (offset < descriptor_len) { proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA); /* offset = descriptor_len; */ } if (entity_id != 0) proto_item_append_text(item, " (Entity %d)", entity_id); if (subtype != VC_HEADER && usb_conv_info) { /* Switch to the usb_conv_info of the Video Control interface */ usb_conv_info = get_usb_iface_conv_info(pinfo, usb_conv_info->interfaceNum); video_conv_info = (video_conv_info_t *)usb_conv_info->class_data; if (!video_conv_info) { video_conv_info = wmem_new(wmem_file_scope(), video_conv_info_t); video_conv_info->entities = wmem_tree_new(wmem_file_scope()); usb_conv_info->class_data = video_conv_info; } entity = (video_entity_t*) wmem_tree_lookup32(video_conv_info->entities, entity_id); if (!entity) { entity = wmem_new(wmem_file_scope(), video_entity_t); entity->entityID = entity_id; entity->subtype = subtype; entity->terminalType = terminal_type; wmem_tree_insert32(video_conv_info->entities, entity_id, entity); } } return descriptor_len; } /*****************************************************************************/ /* VIDEO STREAMING DESCRIPTORS */ /*****************************************************************************/ /* Dissect a Video Streaming Input Header descriptor */ static int dissect_usb_video_streaming_input_header(proto_tree *tree, tvbuff_t *tvb, int offset) { guint8 num_formats; guint8 bm_size; static const int *info_bits[] = { &hf_usb_vid_streaming_info_D[0], NULL }; static const int *control_bits[] = { &hf_usb_vid_streaming_control_D[0], &hf_usb_vid_streaming_control_D[1], &hf_usb_vid_streaming_control_D[2], &hf_usb_vid_streaming_control_D[3], &hf_usb_vid_streaming_control_D[4], &hf_usb_vid_streaming_control_D[5], NULL }; DISSECTOR_ASSERT(array_length(control_bits) == (1+array_length(hf_usb_vid_streaming_control_D))); num_formats = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_streaming_ifdesc_bNumFormats, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_ifdesc_wTotalLength, tvb, offset+1, 2, ENC_LITTLE_ENDIAN); offset += 3; dissect_usb_endpoint_address(tree, tvb, offset); offset++; proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_streaming_bmInfo, ett_streaming_info, info_bits, ENC_NA); proto_tree_add_item(tree, hf_usb_vid_streaming_terminal_link, tvb, offset+1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_streaming_still_capture_method, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; proto_tree_add_item(tree, hf_usb_vid_streaming_trigger_support, tvb, offset, 1, ENC_NA); if (tvb_get_guint8(tvb, offset) > 0) { proto_tree_add_item(tree, hf_usb_vid_streaming_trigger_usage, tvb, offset+1, 1, ENC_LITTLE_ENDIAN); } else { proto_tree_add_uint_format_value(tree, hf_usb_vid_streaming_trigger_usage, tvb, offset+1, 1, 0, "Not applicable"); } offset += 2; /* NOTE: Can't use dissect_bmControl here because there's only one size * field for (potentially) multiple bmControl fields */ bm_size = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_bControlSize, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (bm_size > 0) { guint8 i; for (i=0; i<num_formats; ++i) { proto_tree_add_bitmask_len(tree, tvb, offset, bm_size, hf_usb_vid_bmControl, ett_streaming_controls, control_bits, &ei_usb_vid_bitmask_len, ENC_LITTLE_ENDIAN); offset += bm_size; } } return offset; } /** * Dissect a known Video Payload Format descriptor. * * @param tree protocol tree to which fields should be added * @param tvb the tv_buff with the (remaining) packet data * @param offset where in tvb to begin dissection. * On entry this refers to the bFormatIndex field. * @param subtype Type of format descriptor, from the * bDescriptorSubtype field * * @return offset within tvb at which dissection should continue */ static int dissect_usb_video_format(proto_tree *tree, tvbuff_t *tvb, int offset, guint8 subtype) { static const int *interlace_bits[] = { &hf_usb_vid_is_interlaced, &hf_usb_vid_interlaced_fields, &hf_usb_vid_field_1_first, &hf_usb_vid_field_pattern, NULL }; proto_item *desc_item; guint8 format_index; /* Augment the descriptor root item with the index of this descriptor */ format_index = tvb_get_guint8(tvb, offset); desc_item = proto_tree_get_parent(tree); proto_item_append_text(desc_item, " (Format %u)", format_index); proto_tree_add_item(tree, hf_usb_vid_format_index, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_format_num_frame_descriptors, tvb, offset+1, 1, ENC_LITTLE_ENDIAN); offset += 2; if ((subtype == VS_FORMAT_UNCOMPRESSED) || (subtype == VS_FORMAT_FRAME_BASED)) { /* Augment the descriptor root item with the format's four-character-code */ char fourcc[5]; tvb_memcpy(tvb, (guint8 *)fourcc, offset, 4); fourcc[4] = '\0'; proto_item_append_text(desc_item, ": %s", fourcc); proto_tree_add_item(tree, hf_usb_vid_format_guid, tvb, offset, 16, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_format_bits_per_pixel, tvb, offset+16, 1, ENC_LITTLE_ENDIAN); offset += 17; } else if (subtype == VS_FORMAT_MJPEG) { static const int * flags[] = { &hf_usb_vid_mjpeg_fixed_samples, NULL }; proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_mjpeg_flags, ett_mjpeg_flags, flags, ENC_NA); offset++; } else { /* We should only be called for known format descriptor subtypes */ DISSECTOR_ASSERT_NOT_REACHED(); } proto_tree_add_item(tree, hf_usb_vid_default_frame_index, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_aspect_ratio_x, tvb, offset+1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_aspect_ratio_y, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; #if 0 /* @todo Display "N/A" if Camera Terminal does not support scanning mode control */ if (something) proto_tree_add_uint_format_value(tree, hf_usb_vid_interlace_flags, tvb, offset, 1, tvb_get_guint8(tvb, offset), "Not applicable"); #endif proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_interlace_flags, ett_interlace_flags, interlace_bits, ENC_NA); offset++; proto_tree_add_item(tree, hf_usb_vid_copy_protect, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; if (subtype == VS_FORMAT_FRAME_BASED) { proto_tree_add_item(tree, hf_usb_vid_variable_size, tvb, offset, 1, ENC_NA); offset++; } return offset; } /** * Dissect a known Video Frame descriptor. * * @param tree protocol tree to which fields should be added * @param tvb the tv_buff with the (remaining) packet data * @param offset where in tvb to begin dissection. * On entry this refers to the bFrameIndex field. * @param subtype Type of frame descriptor, from the * bDescriptorSubtype field * * @return offset within tvb at which dissection should continue */ static int dissect_usb_video_frame(proto_tree *tree, tvbuff_t *tvb, int offset, guint8 subtype) { static const int *capability_bits[] = { &hf_usb_vid_frame_stills_supported, &hf_usb_vid_frame_fixed_frame_rate, NULL }; proto_item *desc_item; guint8 bFrameIntervalType; guint8 frame_index; guint16 frame_width; guint16 frame_height; frame_index = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_frame_index, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_frame_capabilities, ett_frame_capability_flags, capability_bits, ENC_NA); offset++; proto_tree_add_item(tree, hf_usb_vid_frame_width, tvb, offset, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_frame_height, tvb, offset+2, 2, ENC_LITTLE_ENDIAN); /* Augment the descriptor root item with useful information */ frame_width = tvb_get_letohs(tvb, offset); frame_height = tvb_get_letohs(tvb, offset+2); desc_item = proto_tree_get_parent(tree); proto_item_append_text(desc_item, " (Index %2u): %4u x %4u", frame_index, frame_width, frame_height); proto_tree_add_item(tree, hf_usb_vid_frame_min_bit_rate, tvb, offset+4, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_frame_max_bit_rate, tvb, offset+8, 4, ENC_LITTLE_ENDIAN); offset += 12; if (subtype != VS_FRAME_FRAME_BASED) { proto_tree_add_item(tree, hf_usb_vid_frame_max_frame_sz, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; } proto_tree_add_item(tree, hf_usb_vid_frame_default_interval, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; bFrameIntervalType = tvb_get_guint8(tvb, offset); if (bFrameIntervalType == 0) { proto_tree_add_uint_format_value(tree, hf_usb_vid_frame_interval_type, tvb, offset, 1, bFrameIntervalType, "Continuous (0)"); offset++; if (subtype == VS_FRAME_FRAME_BASED) { proto_tree_add_item(tree, hf_usb_vid_frame_bytes_per_line, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; } proto_tree_add_item(tree, hf_usb_vid_frame_min_interval, tvb, offset, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_frame_max_interval, tvb, offset+4, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_frame_step_interval, tvb, offset+8, 4, ENC_LITTLE_ENDIAN); offset += 12; } else { guint8 i; proto_tree_add_uint_format_value(tree, hf_usb_vid_frame_interval_type, tvb, offset, 1, bFrameIntervalType, "Discrete (%u choice%s)", bFrameIntervalType, (bFrameIntervalType > 1) ? "s" : ""); offset++; if (subtype == VS_FRAME_FRAME_BASED) { proto_tree_add_item(tree, hf_usb_vid_frame_bytes_per_line, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; } for (i=0; i<bFrameIntervalType; ++i) { proto_tree_add_item(tree, hf_usb_vid_frame_interval, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; } } return offset; } /* Dissect a Color Matching descriptor */ static int dissect_usb_video_colorformat(proto_tree *tree, tvbuff_t *tvb, int offset) { proto_tree_add_item(tree, hf_usb_vid_color_primaries, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_transfer_characteristics, tvb, offset+1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_matrix_coefficients, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset +=3; return offset; } /** * Dissector for video class streaming interface descriptors. * * @param parent_tree the protocol tree to be the parent of the descriptor subtree * @param tvb the tv_buff with the (remaining) packet data * On entry the gaze is set to the descriptor length field. * @param descriptor_len Length of the descriptor to dissect * * @return offset within tvb at which dissection should continue */ static int dissect_usb_video_streaming_interface_descriptor(proto_tree *parent_tree, tvbuff_t *tvb, guint8 descriptor_len) { proto_tree *tree; int offset = 0; const gchar *subtype_str; guint8 subtype; subtype = tvb_get_guint8(tvb, offset+2); subtype_str = val_to_str_ext(subtype, &vs_if_descriptor_subtypes_ext, "Unknown (0x%x)"); tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len, ett_descriptor_video_streaming, NULL, "VIDEO STREAMING INTERFACE DESCRIPTOR [%s]", subtype_str); dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext); proto_tree_add_item(tree, hf_usb_vid_streaming_ifdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; switch (subtype) { case VS_INPUT_HEADER: offset = dissect_usb_video_streaming_input_header(tree, tvb, offset); break; case VS_FORMAT_UNCOMPRESSED: case VS_FORMAT_MJPEG: case VS_FORMAT_FRAME_BASED: offset = dissect_usb_video_format(tree, tvb, offset, subtype); break; /* @todo MPEG2, H.264, VP8, Still Image Frame */ /* @todo Obsolete UVC-1.0 descriptors? */ case VS_FRAME_UNCOMPRESSED: case VS_FRAME_MJPEG: case VS_FRAME_FRAME_BASED: offset = dissect_usb_video_frame(tree, tvb, offset, subtype); break; case VS_COLORFORMAT: offset = dissect_usb_video_colorformat(tree, tvb, offset); break; default: break; } /* Soak up descriptor bytes beyond those we know how to dissect */ if (offset < descriptor_len) proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA); return descriptor_len; } /*****************************************************************************/ /** * Dissector for video class-specific endpoint descriptor. * * @param parent_tree the protocol tree to be the parent of the descriptor subtree * @param tvb the tv_buff with the (remaining) packet data * On entry the gaze is set to the descriptor length field. * @param descriptor_len Length of the descriptor to dissect * * @return offset within tvb at which dissection should continue */ static int dissect_usb_video_endpoint_descriptor(proto_tree *parent_tree, tvbuff_t *tvb, guint8 descriptor_len) { proto_tree *tree = NULL; int offset = 0; guint8 subtype; subtype = tvb_get_guint8(tvb, offset+2); if (parent_tree) { const gchar* subtype_str; subtype_str = val_to_str(subtype, vc_ep_descriptor_subtypes, "Unknown (0x%x)"); tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len, ett_descriptor_video_endpoint, NULL, "VIDEO CONTROL ENDPOINT DESCRIPTOR [%s]", subtype_str); } dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext); proto_tree_add_item(tree, hf_usb_vid_epdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; if (subtype == EP_INTERRUPT) { proto_tree_add_item(tree, hf_usb_vid_epdesc_max_transfer_sz, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; } /* Soak up descriptor bytes beyond those we know how to dissect */ if (offset < descriptor_len) proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA); return descriptor_len; } /** * Registered dissector for video class-specific descriptors * * @param tvb the tv_buff with the (remaining) packet data * On entry the gaze is set to the descriptor length field. * @param pinfo the packet info of this packet (additional info) * @param tree the protocol tree to be built or NULL * @param data Not used * * @return 0 no class specific dissector was found * @return <0 not enough data * @return >0 amount of data in the descriptor */ static int dissect_usb_vid_descriptor(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { int offset = 0; guint8 descriptor_len; guint8 descriptor_type; gint bytes_available; usb_conv_info_t *usb_conv_info = (usb_conv_info_t *)data; tvbuff_t *desc_tvb; descriptor_len = tvb_get_guint8(tvb, offset); descriptor_type = tvb_get_guint8(tvb, offset+1); bytes_available = tvb_captured_length_remaining(tvb, offset); desc_tvb = tvb_new_subset(tvb, 0, bytes_available, descriptor_len); if (descriptor_type == CS_ENDPOINT) { offset = dissect_usb_video_endpoint_descriptor(tree, desc_tvb, descriptor_len); } else if (descriptor_type == CS_INTERFACE) { if (usb_conv_info && usb_conv_info->interfaceSubclass == SC_VIDEOCONTROL) { offset = dissect_usb_video_control_interface_descriptor(tree, desc_tvb, descriptor_len, pinfo, usb_conv_info); } else if (usb_conv_info && usb_conv_info->interfaceSubclass == SC_VIDEOSTREAMING) { offset = dissect_usb_video_streaming_interface_descriptor(tree, desc_tvb, descriptor_len); } } /* else not something we recognize, just return offset = 0 */ return offset; } /*****************************************************************************/ /* CONTROL TRANSFERS */ /*****************************************************************************/ /** * Dissect GET/SET transactions on the Video Probe and Commit controls. * * @param parent_tree protocol tree to which the probe/commit subtree should be added * @param tvb the tv_buff with the (remaining) packet data * @param offset where in tvb to begin dissection. * On entry this refers to the probe/commit bmHint field. * * @return offset within tvb at which dissection should continue */ static int dissect_usb_vid_probe(proto_tree *parent_tree, tvbuff_t *tvb, int offset) { proto_tree *tree; static const int *hint_bits[] = { &hf_usb_vid_probe_hint_D[0], &hf_usb_vid_probe_hint_D[1], &hf_usb_vid_probe_hint_D[2], &hf_usb_vid_probe_hint_D[3], &hf_usb_vid_probe_hint_D[4], NULL }; DISSECTOR_ASSERT(array_length(hint_bits) == (1+array_length(hf_usb_vid_probe_hint_D))); tree = proto_tree_add_subtree(parent_tree, tvb, offset, -1, ett_video_probe, NULL, "Probe/Commit Info"); proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_probe_hint, ett_probe_hint, hint_bits, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_format_index, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_frame_index, tvb, offset+3, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_frame_interval, tvb, offset+4, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_key_frame_rate, tvb, offset+8, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_p_frame_rate, tvb, offset+10, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_comp_quality, tvb, offset+12, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_comp_window, tvb, offset+14, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_delay, tvb, offset+16, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_max_frame_sz, tvb, offset+18, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_max_payload_sz, tvb, offset+22, 4, ENC_LITTLE_ENDIAN); offset += 26; /* UVC 1.1 fields */ if (tvb_reported_length_remaining(tvb, offset) > 0) { static const int *framing_bits[] = { &hf_usb_vid_probe_framing_D[0], &hf_usb_vid_probe_framing_D[1], NULL }; DISSECTOR_ASSERT(array_length(framing_bits) == (1+array_length(hf_usb_vid_probe_framing_D))); proto_tree_add_item(tree, hf_usb_vid_probe_clock_freq, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_probe_framing, ett_probe_framing, framing_bits, ENC_NA); offset++; proto_tree_add_item(tree, hf_usb_vid_probe_preferred_ver, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_min_ver, tvb, offset+1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_probe_max_ver, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; } return offset; } /** * Fetch the table that describes known control selectors for the specified unit/terminal. * * @param entity_id Unit or terminal of interest * @param usb_conv_info Information about the interface the entity is part of * * @return Table describing control selectors for the specified entity (may be NULL) */ static value_string_ext* get_control_selector_values(guint8 entity_id, usb_conv_info_t *usb_conv_info) { video_conv_info_t *video_conv_info; video_entity_t *entity = NULL; value_string_ext *selectors = NULL; if (usb_conv_info == NULL) return NULL; video_conv_info = (video_conv_info_t *)usb_conv_info->class_data; if (video_conv_info) entity = (video_entity_t*) wmem_tree_lookup32(video_conv_info->entities, entity_id); if (entity_id == 0) { /* Interface Request*/ switch (usb_conv_info->interfaceSubclass) { case SC_VIDEOCONTROL: selectors = &cs_control_interface_ext; break; case SC_VIDEOSTREAMING: selectors = &cs_streaming_interface_ext; break; default: break; } } else if (entity) { switch (entity->subtype) { case VC_INPUT_TERMINAL: if (entity->terminalType == ITT_CAMERA) { selectors = &cs_camera_terminal_ext; } break; case VC_PROCESSING_UNIT: selectors = &cs_processing_unit_ext; break; case VC_SELECTOR_UNIT: selectors = &cs_selector_unit_ext; break; default: break; } } return selectors; } /** * Fetch the name of an entity's control. * * @param entity_id Unit or terminal of interest * @param control_sel Control of interest * @param usb_conv_info Information about the interface the entity is part of * * @return Table describing control selectors for the specified entity (may be NULL) */ static const gchar* get_control_selector_name(guint8 entity_id, guint8 control_sel, usb_conv_info_t *usb_conv_info) { const gchar *control_name = NULL; value_string_ext *selectors = NULL; selectors = get_control_selector_values(entity_id, usb_conv_info); if (selectors) control_name = try_val_to_str_ext(control_sel, selectors); return control_name; } /* Dissect the response to a GET INFO request */ static int dissect_usb_vid_control_info(proto_tree *tree, tvbuff_t *tvb, int offset) { static const int *capability_bits[] = { &hf_usb_vid_control_info_D[0], &hf_usb_vid_control_info_D[1], &hf_usb_vid_control_info_D[2], &hf_usb_vid_control_info_D[3], &hf_usb_vid_control_info_D[4], &hf_usb_vid_control_info_D[5], &hf_usb_vid_control_info_D[6], NULL }; DISSECTOR_ASSERT(array_length(capability_bits) == (1+array_length(hf_usb_vid_control_info_D))); proto_tree_add_bitmask(tree, tvb, offset, hf_usb_vid_control_info, ett_control_capabilities, capability_bits, ENC_NA); return offset+1; } /* Dissect all remaining bytes in the tvb as a specified type of UVC value. * These are displayed as an unsigned integer where possible, otherwise just as * a text item. * * @param tree the protocol tree to which an item will be added * @param tvb the tv_buff with the (remaining) packet data * @param offset How far into tvb the value data begins * @param request Identifies type of value - either bRequest from a CONTROL * transfer (i.e., USB_SETUP_GET_MAX), or bValue from an * INTERRUPT transfer (i.e., CONTROL_CHANGE_MAX). */ static void dissect_usb_vid_control_value(proto_tree *tree, tvbuff_t *tvb, int offset, guint8 request) { gint value_size; const char *fallback_name; int hf; switch (request) { case USB_SETUP_GET_DEF: hf = hf_usb_vid_control_default; fallback_name = "Default Value"; break; case USB_SETUP_GET_MIN: case CONTROL_CHANGE_MIN: hf = hf_usb_vid_control_min; fallback_name = "Min Value"; break; case USB_SETUP_GET_MAX: case CONTROL_CHANGE_MAX: hf = hf_usb_vid_control_max; fallback_name = "Max Value"; break; case USB_SETUP_GET_RES: hf = hf_usb_vid_control_res; fallback_name = "Resolution"; break; case USB_SETUP_GET_CUR: case USB_SETUP_SET_CUR: case CONTROL_CHANGE_VALUE: hf = hf_usb_vid_control_cur; fallback_name = "Current Value"; break; /* @todo UVC 1.5 USB_SETUP_x_ALL? * They are poorly specified. */ default: hf = -1; fallback_name = "Value"; break; } value_size = tvb_reported_length_remaining(tvb, offset); if (hf != -1) { header_field_info *hfinfo; hfinfo = proto_registrar_get_nth(hf); DISSECTOR_ASSERT(IS_FT_INT(hfinfo->type) || IS_FT_UINT(hfinfo->type)); } if ((hf != -1) && (value_size <= 4)) { proto_tree_add_item(tree, hf, tvb, offset, value_size, ENC_LITTLE_ENDIAN); } else { /* @todo Display as FT_BYTES with a big-endian disclaimer? * See https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=7933 */ proto_tree_add_bytes_format(tree, hf_usb_vid_control_value, tvb, offset, value_size, NULL, "%s", fallback_name); } } /** * Dissect video class GET/SET transactions. * * @param pinfo Information associated with the packet being dissected * @param tree protocol tree to which fields should be added * @param tvb the tv_buff with the (remaining) packet data * @param offset where in tvb to begin dissection. * On entry this refers to the bRequest field of the SETUP * transaction. * @param is_request true if the packet is host-to-device, * false if device-to-host * @param usb_trans_info Information specific to this request/response pair * @param usb_conv_info Information about the conversation with the host */ static int dissect_usb_vid_get_set(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info, usb_conv_info_t *usb_conv_info) { const gchar *short_name = NULL; guint8 control_sel; guint8 entity_id; entity_id = usb_trans_info->setup.wIndex >> 8; control_sel = usb_trans_info->setup.wValue >> 8; /* Display something informative in the INFO column */ col_append_str(pinfo->cinfo, COL_INFO, " ["); short_name = get_control_selector_name(entity_id, control_sel, usb_conv_info); if (short_name) col_append_str(pinfo->cinfo, COL_INFO, short_name); else { short_name = "Unknown"; if (entity_id == 0) { col_append_fstr(pinfo->cinfo, COL_INFO, "Interface %u control 0x%x", usb_conv_info->interfaceNum, control_sel); } else { col_append_fstr(pinfo->cinfo, COL_INFO, "Unit %u control 0x%x", entity_id, control_sel); } } col_append_str(pinfo->cinfo, COL_INFO, "]"); col_set_fence(pinfo->cinfo, COL_INFO); /* Add information on request context, * as GENERATED fields if not directly available (for filtering) */ if (is_request) { /* Move gaze to control selector (MSB of wValue) */ offset++; proto_tree_add_uint_format_value(tree, hf_usb_vid_control_selector, tvb, offset, 1, control_sel, "%s (0x%02x)", short_name, control_sel); offset++; proto_tree_add_item(tree, hf_usb_vid_control_interface, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; proto_tree_add_item(tree, hf_usb_vid_control_entity, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; proto_tree_add_item(tree, hf_usb_vid_length, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; } else { proto_item *ti; ti = proto_tree_add_uint(tree, hf_usb_vid_control_interface, tvb, 0, 0, usb_trans_info->setup.wIndex & 0xFF); PROTO_ITEM_SET_GENERATED(ti); ti = proto_tree_add_uint(tree, hf_usb_vid_control_entity, tvb, 0, 0, entity_id); PROTO_ITEM_SET_GENERATED(ti); ti = proto_tree_add_uint_format_value(tree, hf_usb_vid_control_selector, tvb, 0, 0, control_sel, "%s (0x%02x)", short_name, control_sel); PROTO_ITEM_SET_GENERATED(ti); } if (!is_request || (usb_trans_info->setup.request == USB_SETUP_SET_CUR)) { gint value_size = tvb_reported_length_remaining(tvb, offset); if (value_size != 0) { if ((entity_id == 0) && (usb_conv_info->interfaceSubclass == SC_VIDEOSTREAMING)) { if ((control_sel == VS_PROBE_CONTROL) || (control_sel == VS_COMMIT_CONTROL)) { int old_offset = offset; offset = dissect_usb_vid_probe(tree, tvb, offset); value_size -= (offset - old_offset); } } else { if (usb_trans_info->setup.request == USB_SETUP_GET_INFO) { dissect_usb_vid_control_info(tree, tvb, offset); offset++; value_size--; } else if (usb_trans_info->setup.request == USB_SETUP_GET_LEN) { proto_tree_add_item(tree, hf_usb_vid_control_length, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; value_size -= 2; } else if ( (usb_trans_info->setup.request == USB_SETUP_GET_CUR) && (entity_id == 0) && (usb_conv_info->interfaceSubclass == SC_VIDEOCONTROL) && (control_sel == VC_REQUEST_ERROR_CODE_CONTROL)) { proto_tree_add_item(tree, hf_usb_vid_request_error, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; value_size--; } else { dissect_usb_vid_control_value(tree, tvb, offset, usb_trans_info->setup.request); offset += value_size; value_size = 0; } } if (value_size > 0) { proto_tree_add_item(tree, hf_usb_vid_control_data, tvb, offset, -1, ENC_NA); offset += value_size; } } } return offset; } /* Table for dispatch of video class SETUP transactions based on bRequest. * At the moment this is overkill since the same function handles all defined * requests. */ typedef int (*usb_setup_dissector)(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info, usb_conv_info_t *usb_conv_info); typedef struct _usb_setup_dissector_table_t { guint8 request; usb_setup_dissector dissector; } usb_setup_dissector_table_t; static const usb_setup_dissector_table_t setup_dissectors[] = { {USB_SETUP_SET_CUR, dissect_usb_vid_get_set}, {USB_SETUP_SET_CUR_ALL, dissect_usb_vid_get_set}, {USB_SETUP_GET_CUR, dissect_usb_vid_get_set}, {USB_SETUP_GET_MIN, dissect_usb_vid_get_set}, {USB_SETUP_GET_MAX, dissect_usb_vid_get_set}, {USB_SETUP_GET_RES, dissect_usb_vid_get_set}, {USB_SETUP_GET_LEN, dissect_usb_vid_get_set}, {USB_SETUP_GET_INFO, dissect_usb_vid_get_set}, {USB_SETUP_GET_DEF, dissect_usb_vid_get_set}, {USB_SETUP_GET_CUR_ALL, dissect_usb_vid_get_set}, {USB_SETUP_GET_MIN_ALL, dissect_usb_vid_get_set}, {USB_SETUP_GET_MAX_ALL, dissect_usb_vid_get_set}, {USB_SETUP_GET_RES_ALL, dissect_usb_vid_get_set}, {0, NULL} }; static const value_string setup_request_names_vals[] = { {USB_SETUP_SET_CUR, "SET CUR"}, {USB_SETUP_SET_CUR_ALL, "SET CUR ALL"}, {USB_SETUP_GET_CUR, "GET CUR"}, {USB_SETUP_GET_MIN, "GET MIN"}, {USB_SETUP_GET_MAX, "GET MAX"}, {USB_SETUP_GET_RES, "GET RES"}, {USB_SETUP_GET_LEN, "GET LEN"}, {USB_SETUP_GET_INFO, "GET INFO"}, {USB_SETUP_GET_DEF, "GET DEF"}, {USB_SETUP_GET_CUR_ALL, "GET CUR ALL"}, {USB_SETUP_GET_MIN_ALL, "GET MIN ALL"}, {USB_SETUP_GET_MAX_ALL, "GET MAX ALL"}, {USB_SETUP_GET_RES_ALL, "GET RES ALL"}, {USB_SETUP_GET_DEF_ALL, "GET DEF ALL"}, {0, NULL} }; /* Registered dissector for video class-specific control requests. * Dispatch to an appropriate dissector function. * * @param tvb the tv_buff with the (remaining) packet data. * On entry, the gaze is set to SETUP bRequest field. * @param pinfo the packet info of this packet (additional info) * @param tree the protocol tree to be built or NULL * @param data Not used * * @return 0 no class specific dissector was found * @return <0 not enough data * @return >0 amount of data in the descriptor */ static int dissect_usb_vid_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { gboolean is_request = (pinfo->srcport == NO_ENDPOINT); usb_conv_info_t *usb_conv_info; usb_trans_info_t *usb_trans_info; int offset = 0; usb_setup_dissector dissector = NULL; const usb_setup_dissector_table_t *tmp; /* Reject the packet if data or usb_trans_info are NULL */ if (data == NULL || ((usb_conv_info_t *)data)->usb_trans_info == NULL) return 0; usb_conv_info = (usb_conv_info_t *)data; usb_trans_info = usb_conv_info->usb_trans_info; /* See if we can find a class specific dissector for this request */ for (tmp=setup_dissectors; tmp->dissector; tmp++) { if (tmp->request == usb_trans_info->setup.request) { dissector = tmp->dissector; break; } } /* No we could not find any class specific dissector for this request * return FALSE and let USB try any of the standard requests. */ if (!dissector) return 0; col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBVIDEO"); col_add_fstr(pinfo->cinfo, COL_INFO, "%s %s", val_to_str(usb_trans_info->setup.request, setup_request_names_vals, "Unknown type %x"), is_request?"Request ":"Response"); if (is_request) { proto_tree_add_item(tree, hf_usb_vid_request, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; } offset = dissector(pinfo, tree, tvb, offset, is_request, usb_trans_info, usb_conv_info); return offset; } /* Registered dissector for video class-specific URB_INTERRUPT * * @param tvb the tv_buff with the (remaining) packet data * @param pinfo the packet info of this packet (additional info) * @param tree the protocol tree to be built or NULL * @param data Unused API parameter * * @return 0 no class specific dissector was found * @return <0 not enough data * @return >0 amount of data in the descriptor */ static int dissect_usb_vid_interrupt(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { usb_conv_info_t *usb_conv_info; gint bytes_available; int offset = 0; usb_conv_info = (usb_conv_info_t *)data; bytes_available = tvb_reported_length_remaining(tvb, offset); col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBVIDEO"); if (bytes_available > 0) { guint8 originating_interface; guint8 originating_entity; originating_interface = tvb_get_guint8(tvb, offset) & INT_ORIGINATOR_MASK; proto_tree_add_item(tree, hf_usb_vid_interrupt_bStatusType, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; originating_entity = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_interrupt_bOriginator, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; if (originating_interface == INT_VIDEOCONTROL) { guint8 control_sel; guint8 attribute; const gchar *control_name; proto_tree_add_item(tree, hf_usb_vid_control_interrupt_bEvent, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; control_sel = tvb_get_guint8(tvb, offset); control_name = get_control_selector_name(originating_entity, control_sel, usb_conv_info); if (!control_name) control_name = "Unknown"; proto_tree_add_uint_format_value(tree, hf_usb_vid_control_selector, tvb, offset, 1, control_sel, "%s (0x%02x)", control_name, control_sel); offset++; attribute = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_interrupt_bAttribute, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; switch (attribute) { case CONTROL_CHANGE_FAILURE: proto_tree_add_item(tree, hf_usb_vid_request_error, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; break; case CONTROL_CHANGE_INFO: offset = dissect_usb_vid_control_info(tree, tvb, offset); break; case CONTROL_CHANGE_VALUE: case CONTROL_CHANGE_MIN: case CONTROL_CHANGE_MAX: dissect_usb_vid_control_value(tree, tvb, offset, attribute); offset += tvb_reported_length_remaining(tvb, offset); break; default: proto_tree_add_item(tree, hf_usb_vid_value_data, tvb, offset, -1, ENC_NA); offset += tvb_reported_length_remaining(tvb, offset); break; } } else if (originating_interface == INT_VIDEOSTREAMING) { /* @todo */ } } else offset = -2; return offset; } void proto_register_usb_vid(void) { static hf_register_info hf[] = { /***** Setup *****/ { &hf_usb_vid_request, { "bRequest", "usbvideo.setup.bRequest", FT_UINT8, BASE_HEX, VALS(setup_request_names_vals), 0x0, NULL, HFILL } }, { &hf_usb_vid_length, { "wLength", "usbvideo.setup.wLength", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, /***** Request Error Control *****/ { &hf_usb_vid_request_error, { "bRequestErrorCode", "usbvideo.reqerror.code", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &request_error_codes_ext, 0, "Request Error Code", HFILL } }, /***** Unit/Terminal Controls *****/ { &hf_usb_vid_control_selector, { "Control Selector", "usbvideo.control.selector", FT_UINT8, BASE_HEX, NULL, 0x0, "ID of the control within its entity", HFILL } }, { &hf_usb_vid_control_entity, { "Entity", "usbvideo.control.entity", FT_UINT8, BASE_HEX, NULL, 0x0, "Unit or terminal to which the control belongs", HFILL } }, { &hf_usb_vid_control_interface, { "Interface", "usbvideo.control.interface", FT_UINT8, BASE_HEX, NULL, 0x0, "Interface to which the control belongs", HFILL } }, { &hf_usb_vid_control_info, { "Info (Capabilities/State)", "usbvideo.control.info", FT_UINT8, BASE_HEX, NULL, 0, "Control capabilities and current state", HFILL } }, { &hf_usb_vid_control_info_D[0], { "Supports GET", "usbvideo.control.info.D0", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<0), NULL, HFILL } }, { &hf_usb_vid_control_info_D[1], { "Supports SET", "usbvideo.control.info.D1", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<1), NULL, HFILL } }, { &hf_usb_vid_control_info_D[2], { "Disabled due to automatic mode", "usbvideo.control.info.D2", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<2), NULL, HFILL } }, { &hf_usb_vid_control_info_D[3], { "Autoupdate", "usbvideo.control.info.D3", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<3), NULL, HFILL } }, { &hf_usb_vid_control_info_D[4], { "Asynchronous", "usbvideo.control.info.D4", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<4), NULL, HFILL } }, { &hf_usb_vid_control_info_D[5], { "Disabled due to incompatibility with Commit state", "usbvideo.control.info.D5", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<5), NULL, HFILL } }, { &hf_usb_vid_control_info_D[6], { "Reserved", "usbvideo.control.info.D6", FT_UINT8, BASE_HEX, NULL, (3<<6), NULL, HFILL } }, { &hf_usb_vid_control_length, { "Control Length", "usbvideo.control.len", FT_UINT16, BASE_DEC, NULL, 0, "Control size in bytes", HFILL } }, { &hf_usb_vid_control_default, { "Default value", "usbvideo.control.value.default", FT_UINT32, BASE_DEC_HEX, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_control_min, { "Minimum value", "usbvideo.control.value.min", FT_UINT32, BASE_DEC_HEX, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_control_max, { "Maximum value", "usbvideo.control.value.max", FT_UINT32, BASE_DEC_HEX, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_control_res, { "Resolution", "usbvideo.control.value.res", FT_UINT32, BASE_DEC_HEX, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_control_cur, { "Current value", "usbvideo.control.value.cur", FT_UINT32, BASE_DEC_HEX, NULL, 0, NULL, HFILL } }, /***** Terminal Descriptors *****/ /* @todo Decide whether to unify .name fields */ { &hf_usb_vid_control_ifdesc_iTerminal, { "iTerminal", "usbvideo.terminal.name", FT_UINT8, BASE_DEC, NULL, 0x0, "String Descriptor describing this terminal", HFILL } }, /* @todo Decide whether to unify .terminal.id and .unit.id under .entityID */ { &hf_usb_vid_control_ifdesc_terminal_id, { "bTerminalID", "usbvideo.terminal.id", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_usb_vid_control_ifdesc_terminal_type, { "wTerminalType", "usbvideo.terminal.type", FT_UINT16, BASE_HEX | BASE_EXT_STRING, &vc_terminal_types_ext, 0, NULL, HFILL } }, { &hf_usb_vid_control_ifdesc_assoc_terminal, { "bAssocTerminal", "usbvideo.terminal.assocTerminal", FT_UINT8, BASE_DEC, NULL, 0x0, "Associated Terminal", HFILL } }, /***** Camera Terminal Descriptor *****/ { &hf_usb_vid_cam_objective_focal_len_min, { "wObjectiveFocalLengthMin", "usbvideo.camera.objectiveFocalLengthMin", FT_UINT16, BASE_DEC, NULL, 0, "Minimum Focal Length for Optical Zoom", HFILL } }, { &hf_usb_vid_cam_objective_focal_len_max, { "wObjectiveFocalLengthMax", "usbvideo.camera.objectiveFocalLengthMax", FT_UINT16, BASE_DEC, NULL, 0, "Minimum Focal Length for Optical Zoom", HFILL } }, { &hf_usb_vid_cam_ocular_focal_len, { "wOcularFocalLength", "usbvideo.camera.ocularFocalLength", FT_UINT16, BASE_DEC, NULL, 0, "Ocular Focal Length for Optical Zoom", HFILL } }, { &hf_usb_vid_cam_control_D[0], { "Scanning Mode", "usbvideo.camera.control.D0", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<0), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[1], { "Auto Exposure Mode", "usbvideo.camera.control.D1", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<1), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[2], { "Auto Exposure Priority", "usbvideo.camera.control.D2", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<2), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[3], { "Exposure Time (Absolute)", "usbvideo.camera.control.D3", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<3), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[4], { "Exposure Time (Relative)", "usbvideo.camera.control.D4", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<4), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[5], { "Focus (Absolute)", "usbvideo.camera.control.D5", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<5), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[6], { "Focus (Relative)", "usbvideo.camera.control.D6", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<6), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[7], { "Iris (Absolute)", "usbvideo.camera.control.D7", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<7), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[8], { "Iris (Relative)", "usbvideo.camera.control.D8", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<8), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[9], { "Zoom (Absolute)", "usbvideo.camera.control.D9", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<9), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[10], { "Zoom (Relative)", "usbvideo.camera.control.D10", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<10), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[11], { "PanTilt (Absolute)", "usbvideo.camera.control.D11", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<11), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[12], { "PanTilt (Relative)", "usbvideo.camera.control.D12", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<12), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[13], { "Roll (Absolute)", "usbvideo.camera.control.D13", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<13), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[14], { "Roll (Relative)", "usbvideo.camera.control.D14", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<14), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[15], { "D15", "usbvideo.camera.control.D15", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<15), "Reserved", HFILL } }, { &hf_usb_vid_cam_control_D[16], { "D16", "usbvideo.camera.control.D16", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<16), "Reserved", HFILL } }, { &hf_usb_vid_cam_control_D[17], { "Auto Focus", "usbvideo.camera.control.D17", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<17), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[18], { "Privacy", "usbvideo.camera.control.D18", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<18), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[19], { "Focus (Simple)", "usbvideo.camera.control.D19", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<19), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[20], { "Window", "usbvideo.camera.control.D20", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<20), NULL, HFILL } }, { &hf_usb_vid_cam_control_D[21], { "Region of Interest", "usbvideo.camera.control.D21", FT_BOOLEAN, array_length(hf_usb_vid_cam_control_D), TFS(&tfs_yes_no), (1<<21), NULL, HFILL } }, /***** Unit Descriptors *****/ { &hf_usb_vid_control_ifdesc_unit_id, { "bUnitID", "usbvideo.unit.id", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_usb_vid_num_inputs, { "bNrInPins", "usbvideo.unit.numInputs", FT_UINT8, BASE_DEC, NULL, 0, "Number of input pins", HFILL } }, { &hf_usb_vid_sources, { "baSourceID", "usbvideo.unit.sources", FT_BYTES, BASE_NONE, NULL, 0, "Input entity IDs", HFILL } }, /***** Processing Unit Descriptor *****/ { &hf_usb_vid_iProcessing, { "iProcessing", "usbvideo.processor.name", FT_UINT8, BASE_DEC, NULL, 0x0, "String Descriptor describing this terminal", HFILL } }, { &hf_usb_vid_proc_control_D[0], { "Brightness", "usbvideo.processor.control.D0", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<0), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[1], { "Contrast", "usbvideo.processor.control.D1", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<1), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[2], { "Hue", "usbvideo.processor.control.D2", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<2), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[3], { "Saturation", "usbvideo.processor.control.D3", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<3), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[4], { "Sharpness", "usbvideo.processor.control.D4", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<4), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[5], { "Gamma", "usbvideo.processor.control.D5", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<5), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[6], { "White Balance Temperature", "usbvideo.processor.control.D6", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<6), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[7], { "White Balance Component", "usbvideo.processor.control.D7", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<7), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[8], { "Backlight Compensation", "usbvideo.processor.control.D8", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<8), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[9], { "Gain", "usbvideo.processor.control.D9", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<9), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[10], { "Power Line Frequency", "usbvideo.processor.control.D10", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<10), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[11], { "Hue, Auto", "usbvideo.processor.control.D11", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<11), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[12], { "White Balance Temperature, Auto", "usbvideo.processor.control.D12", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<12), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[13], { "White Balance Component, Auto", "usbvideo.processor.control.D13", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<13), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[14], { "Digital Multiplier", "usbvideo.processor.control.D14", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<14), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[15], { "Digital Multiplier Limit", "usbvideo.processor.control.D15", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<15), "Reserved", HFILL } }, { &hf_usb_vid_proc_control_D[16], { "Analog Video Standard", "usbvideo.processor.control.D16", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<16), "Reserved", HFILL } }, { &hf_usb_vid_proc_control_D[17], { "Analog Video Lock Status", "usbvideo.processor.control.D17", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<17), NULL, HFILL } }, { &hf_usb_vid_proc_control_D[18], { "Contrast, Auto", "usbvideo.processor.control.D18", FT_BOOLEAN, 24, TFS(&tfs_yes_no), (1<<18), NULL, HFILL } }, { &hf_usb_vid_proc_standards, { "bmVideoStandards", "usbvideo.processor.standards", FT_UINT8, BASE_HEX, NULL, 0, "Supported analog video standards", HFILL } }, { &hf_usb_vid_proc_standards_D[0], { "None", "usbvideo.processor.standards.D0", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<0), NULL, HFILL } }, { &hf_usb_vid_proc_standards_D[1], { "NTSC - 525/60", "usbvideo.processor.standards.D1", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<1), NULL, HFILL } }, { &hf_usb_vid_proc_standards_D[2], { "PAL - 625/50", "usbvideo.processor.standards.D2", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<2), NULL, HFILL } }, { &hf_usb_vid_proc_standards_D[3], { "SECAM - 625/50", "usbvideo.processor.standards.D3", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<3), NULL, HFILL } }, { &hf_usb_vid_proc_standards_D[4], { "NTSC - 625/50", "usbvideo.processor.standards.D4", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<4), NULL, HFILL } }, { &hf_usb_vid_proc_standards_D[5], { "PAL - 525/60", "usbvideo.processor.standards.D5", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<5), NULL, HFILL } }, { &hf_usb_vid_max_multiplier, { "wMaxMultiplier", "usbvideo.processor.maxMultiplier", FT_UINT16, BASE_DEC, NULL, 0, "100 x max digital multiplication", HFILL } }, /***** Selector Unit Descriptor *****/ { &hf_usb_vid_iSelector, { "iSelector", "usbvideo.selector.name", FT_UINT8, BASE_DEC, NULL, 0x0, "String Descriptor describing this terminal", HFILL } }, /***** Extension Unit Descriptor *****/ { &hf_usb_vid_iExtension, { "iExtension", "usbvideo.extension.name", FT_UINT8, BASE_DEC, NULL, 0x0, "String Descriptor describing this terminal", HFILL } }, { &hf_usb_vid_exten_guid, { "guid", "usbvideo.extension.guid", FT_GUID, BASE_NONE, NULL, 0, "Identifier", HFILL } }, { &hf_usb_vid_exten_num_controls, { "bNumControls", "usbvideo.extension.numControls", FT_UINT8, BASE_DEC, NULL, 0, "Number of controls", HFILL } }, /***** Probe/Commit *****/ { &hf_usb_vid_probe_hint, { "bmHint", "usbvideo.probe.hint", FT_UINT16, BASE_HEX, NULL, 0, "Fields to hold constant during negotiation", HFILL } }, { &hf_usb_vid_probe_hint_D[0], { "dwFrameInterval", "usbvideo.probe.hint.D0", FT_BOOLEAN, 5, TFS(&probe_hint_meaning), (1<<0), "Frame Rate", HFILL } }, { &hf_usb_vid_probe_hint_D[1], { "wKeyFrameRate", "usbvideo.probe.hint.D1", FT_BOOLEAN, 5, TFS(&probe_hint_meaning), (1<<1), "Key Frame Rate", HFILL } }, { &hf_usb_vid_probe_hint_D[2], { "wPFrameRate", "usbvideo.probe.hint.D2", FT_BOOLEAN, 5, TFS(&probe_hint_meaning), (1<<2), "P-Frame Rate", HFILL } }, { &hf_usb_vid_probe_hint_D[3], { "wCompQuality", "usbvideo.probe.hint.D3", FT_BOOLEAN, 5, TFS(&probe_hint_meaning), (1<<3), "Compression Quality", HFILL } }, { &hf_usb_vid_probe_hint_D[4], { "wCompWindowSize", "usbvideo.probe.hint.D4", FT_BOOLEAN, 5, TFS(&probe_hint_meaning), (1<<4), "Compression Window Size", HFILL } }, { &hf_usb_vid_probe_key_frame_rate, { "wKeyFrameRate", "usbvideo.probe.keyFrameRate", FT_UINT16, BASE_DEC, NULL, 0, "Key frame rate", HFILL } }, { &hf_usb_vid_probe_p_frame_rate, { "wPFrameRate", "usbvideo.probe.pFrameRate", FT_UINT16, BASE_DEC, NULL, 0, "P frame rate", HFILL } }, { &hf_usb_vid_probe_comp_quality, { "wCompQuality", "usbvideo.probe.compQuality", FT_UINT16, BASE_DEC, NULL, 0, "Compression quality [0-10000]", HFILL } }, { &hf_usb_vid_probe_comp_window, { "wCompWindow", "usbvideo.probe.compWindow", FT_UINT16, BASE_DEC, NULL, 0, "Window size for average bit rate control", HFILL } }, { &hf_usb_vid_probe_delay, { "wDelay", "usbvideo.probe.delay", FT_UINT16, BASE_DEC, NULL, 0, "Latency in ms from capture to USB", HFILL } }, { &hf_usb_vid_probe_max_frame_sz, { "dwMaxVideoFrameSize", "usbvideo.probe.maxVideoFrameSize", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_probe_max_payload_sz, { "dwMaxPayloadTransferSize", "usbvideo.probe.maxPayloadTransferSize", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_probe_clock_freq, { "dwClockFrequency", "usbvideo.probe.clockFrequency", FT_UINT32, BASE_DEC, NULL, 0, "Device clock frequency in Hz", HFILL } }, { &hf_usb_vid_probe_framing, { "bmFramingInfo", "usbvideo.probe.framing", FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_usb_vid_probe_framing_D[0], { "Frame ID required", "usbvideo.probe.framing.D0", FT_BOOLEAN, 2, TFS(&tfs_yes_no), (1<<0), NULL, HFILL } }, { &hf_usb_vid_probe_framing_D[1], { "EOF utilized", "usbvideo.probe.framing.D1", FT_BOOLEAN, 2, TFS(&tfs_yes_no), (1<<1), NULL, HFILL } }, { &hf_usb_vid_probe_preferred_ver, { "bPreferredVersion", "usbvideo.probe.preferredVersion", FT_UINT8, BASE_DEC, NULL, 0, "Preferred payload format version", HFILL } }, { &hf_usb_vid_probe_min_ver, { "bMinVersion", "usbvideo.probe.minVersion", FT_UINT8, BASE_DEC, NULL, 0, "Min supported payload format version", HFILL } }, { &hf_usb_vid_probe_max_ver, { "bPreferredVersion", "usbvideo.probe.maxVer", FT_UINT8, BASE_DEC, NULL, 0, "Max supported payload format version", HFILL } }, { &hf_usb_vid_control_ifdesc_dwClockFrequency, { "dwClockFrequency", "usbvideo.probe.clockFrequency", FT_UINT32, BASE_DEC, NULL, 0, "Device clock frequency (Hz) for selected format", HFILL } }, /***** Format Descriptors *****/ { &hf_usb_vid_format_index, { "bFormatIndex", "usbvideo.format.index", FT_UINT8, BASE_DEC, NULL, 0, "Index of this format descriptor", HFILL } }, { &hf_usb_vid_format_num_frame_descriptors, { "bNumFrameDescriptors", "usbvideo.format.numFrameDescriptors", FT_UINT8, BASE_DEC, NULL, 0, "Number of frame descriptors for this format", HFILL } }, { &hf_usb_vid_format_guid, { "guidFormat", "usbvideo.format.guid", FT_GUID, BASE_NONE, NULL, 0, "Stream encoding format", HFILL } }, { &hf_usb_vid_format_bits_per_pixel, { "bBitsPerPixel", "usbvideo.format.bitsPerPixel", FT_UINT8, BASE_DEC, NULL, 0, "Bits per pixel", HFILL } }, { &hf_usb_vid_default_frame_index, { "bDefaultFrameIndex", "usbvideo.format.defaultFrameIndex", FT_UINT8, BASE_DEC, NULL, 0, "Optimum frame index for this stream", HFILL } }, { &hf_usb_vid_aspect_ratio_x, { "bAspectRatioX", "usbvideo.format.aspectRatioX", FT_UINT8, BASE_DEC, NULL, 0, "X dimension of picture aspect ratio", HFILL } }, { &hf_usb_vid_aspect_ratio_y, { "bAspectRatioY", "usbvideo.format.aspectRatioY", FT_UINT8, BASE_DEC, NULL, 0, "Y dimension of picture aspect ratio", HFILL } }, { &hf_usb_vid_interlace_flags, { "bmInterlaceFlags", "usbvideo.format.interlace", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_usb_vid_is_interlaced, { "Interlaced stream", "usbvideo.format.interlace.D0", FT_BOOLEAN, 8, TFS(&is_interlaced_meaning), (1<<0), NULL, HFILL } }, { &hf_usb_vid_interlaced_fields, { "Fields per frame", "usbvideo.format.interlace.D1", FT_BOOLEAN, 8, TFS(&interlaced_fields_meaning), (1<<1), NULL, HFILL } }, { &hf_usb_vid_field_1_first, { "Field 1 first", "usbvideo.format.interlace.D2", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<2), NULL, HFILL } }, { &hf_usb_vid_field_pattern, { "Field pattern", "usbvideo.format.interlace.pattern", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &field_pattern_meaning_ext, (3<<4), NULL, HFILL } }, { &hf_usb_vid_copy_protect, { "bCopyProtect", "usbvideo.format.copyProtect", FT_UINT8, BASE_DEC, VALS(copy_protect_meaning), 0, NULL, HFILL } }, { &hf_usb_vid_variable_size, { "Variable size", "usbvideo.format.variableSize", FT_BOOLEAN, BASE_DEC, NULL, 0, NULL, HFILL } }, /***** MJPEG Format Descriptor *****/ { &hf_usb_vid_mjpeg_flags, { "bmFlags", "usbvideo.mjpeg.flags", FT_UINT8, BASE_HEX, NULL, 0, "Characteristics", HFILL } }, { &hf_usb_vid_mjpeg_fixed_samples, { "Fixed size samples", "usbvideo.mjpeg.fixed_size", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<0), NULL, HFILL } }, /***** Frame Descriptors *****/ { &hf_usb_vid_frame_index, { "bFrameIndex", "usbvideo.frame.index", FT_UINT8, BASE_DEC, NULL, 0, "Index of this frame descriptor", HFILL } }, { &hf_usb_vid_frame_capabilities, { "bmCapabilities", "usbvideo.frame.capabilities", FT_UINT8, BASE_HEX, NULL, 0, "Capabilities", HFILL } }, { &hf_usb_vid_frame_stills_supported, { "Still image", "usbvideo.frame.stills", FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), (1<<0), NULL, HFILL } }, { &hf_usb_vid_frame_interval, { "dwFrameInterval", "usbvideo.frame.interval", FT_UINT32, BASE_DEC, NULL, 0, "Frame interval multiple of 100 ns", HFILL } }, { &hf_usb_vid_frame_fixed_frame_rate, { "Fixed frame rate", "usbvideo.frame.fixedRate", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<1), NULL, HFILL } }, { &hf_usb_vid_frame_width, { "wWidth", "usbvideo.frame.width", FT_UINT16, BASE_DEC, NULL, 0, "Width of frame in pixels", HFILL } }, { &hf_usb_vid_frame_height, { "wHeight", "usbvideo.frame.height", FT_UINT16, BASE_DEC, NULL, 0, "Height of frame in pixels", HFILL } }, { &hf_usb_vid_frame_min_bit_rate, { "dwMinBitRate", "usbvideo.frame.minBitRate", FT_UINT32, BASE_DEC, NULL, 0, "Minimum bit rate in bps", HFILL } }, { &hf_usb_vid_frame_max_bit_rate, { "dwMaxBitRate", "usbvideo.frame.maxBitRate", FT_UINT32, BASE_DEC, NULL, 0, "Maximum bit rate in bps", HFILL } }, { &hf_usb_vid_frame_max_frame_sz, { "dwMaxVideoFrameBufferSize", "usbvideo.frame.maxBuffer", FT_UINT32, BASE_DEC, NULL, 0, "Maximum bytes per frame", HFILL } }, { &hf_usb_vid_frame_default_interval, { "dwDefaultFrameInterval", "usbvideo.frame.interval.default", FT_UINT32, BASE_DEC, NULL, 0, "Suggested default", HFILL } }, { &hf_usb_vid_frame_interval_type, { "bFrameIntervalType", "usbvideo.frame.interval.type", FT_UINT8, BASE_DEC, NULL, 0, "Frame rate control (continuous/discrete)", HFILL } }, { &hf_usb_vid_frame_min_interval, { "dwMinFrameInterval", "usbvideo.frame.interval.min", FT_UINT32, BASE_DEC, NULL, 0, "Shortest frame interval (* 100 ns)", HFILL } }, { &hf_usb_vid_frame_max_interval, { "dwMaxFrameInterval", "usbvideo.frame.interval.max", FT_UINT32, BASE_DEC, NULL, 0, "Longest frame interval (* 100 ns)", HFILL } }, { &hf_usb_vid_frame_step_interval, { "dwMinFrameInterval", "usbvideo.frame.interval.step", FT_UINT32, BASE_DEC, NULL, 0, "Granularity of frame interval (* 100 ns)", HFILL } }, { &hf_usb_vid_frame_bytes_per_line, { "dwBytesPerLine", "usbvideo.frame.bytesPerLine", FT_UINT32, BASE_DEC, NULL, 0, "Fixed number of bytes per video line", HFILL } }, /***** Colorformat Descriptor *****/ { &hf_usb_vid_color_primaries, { "bColorPrimaries", "usbvideo.color.primaries", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &color_primaries_meaning_ext, 0, NULL, HFILL } }, { &hf_usb_vid_transfer_characteristics, { "bTransferCharacteristics", "usbvideo.color.transferCharacteristics", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &color_transfer_characteristics_ext, 0, NULL, HFILL } }, { &hf_usb_vid_matrix_coefficients, { "bMatrixCoefficients", "usbvideo.color.matrixCoefficients", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &matrix_coefficients_meaning_ext, 0, NULL, HFILL } }, /***** Video Control Header Descriptor *****/ { &hf_usb_vid_control_ifdesc_bcdUVC, { "bcdUVC", "usbvideo.bcdUVC", FT_UINT16, BASE_HEX, NULL, 0, "Video Device Class Specification release number", HFILL } }, { &hf_usb_vid_control_ifdesc_bInCollection, { "bInCollection", "usbvideo.numStreamingInterfaces", FT_UINT8, BASE_DEC, NULL, 0, "Number of VideoStreaming interfaces", HFILL } }, { &hf_usb_vid_control_ifdesc_baInterfaceNr, { "baInterfaceNr", "usbvideo.streamingInterfaceNumbers", FT_BYTES, BASE_NONE, NULL, 0, "Interface numbers of VideoStreaming interfaces", HFILL }}, /***** Video Streaming Input Header Descriptor *****/ { &hf_usb_vid_streaming_ifdesc_bNumFormats, { "bNumFormats", "usbvideo.streaming.numFormats", FT_UINT8, BASE_DEC, NULL, 0, "Number of video payload format descriptors", HFILL } }, { &hf_usb_vid_streaming_bmInfo, { "bmInfo", "usbvideo.streaming.info", FT_UINT8, BASE_HEX, NULL, 0, "Capabilities", HFILL } }, { &hf_usb_vid_streaming_info_D[0], { "Dynamic Format Change", "usbvideo.streaming.info.D0", FT_BOOLEAN, 8, TFS(&tfs_yes_no), (1<<0), "Dynamic Format Change", HFILL } }, { &hf_usb_vid_streaming_control_D[0], { "wKeyFrameRate", "usbvideo.streaming.control.D0", FT_BOOLEAN, 6, TFS(&tfs_yes_no), (1<<0), "Probe and Commit support", HFILL } }, { &hf_usb_vid_streaming_control_D[1], { "wPFrameRate", "usbvideo.streaming.control.D1", FT_BOOLEAN, 6, TFS(&tfs_yes_no), (1<<1), "Probe and Commit support", HFILL } }, { &hf_usb_vid_streaming_control_D[2], { "wCompQuality", "usbvideo.streaming.control.D2", FT_BOOLEAN, 6, TFS(&tfs_yes_no), (1<<2), "Probe and Commit support", HFILL } }, { &hf_usb_vid_streaming_control_D[3], { "wCompWindowSize", "usbvideo.streaming.control.D3", FT_BOOLEAN, 6, TFS(&tfs_yes_no), (1<<3), "Probe and Commit support", HFILL } }, { &hf_usb_vid_streaming_control_D[4], { "Generate Key Frame", "usbvideo.streaming.control.D4", FT_BOOLEAN, 6, TFS(&tfs_yes_no), (1<<4), "Probe and Commit support", HFILL } }, { &hf_usb_vid_streaming_control_D[5], { "Update Frame Segment", "usbvideo.streaming.control.D5", FT_BOOLEAN, 6, TFS(&tfs_yes_no), (1<<5), "Probe and Commit support", HFILL } }, { &hf_usb_vid_streaming_terminal_link, { "bTerminalLink", "usbvideo.streaming.terminalLink", FT_UINT8, BASE_DEC, NULL, 0x0, "Output terminal ID", HFILL } }, { &hf_usb_vid_streaming_still_capture_method, { "bStillCaptureMethod", "usbvideo.streaming.stillCaptureMethod", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &vs_still_capture_methods_ext, 0, "Method of Still Image Capture", HFILL } }, { &hf_usb_vid_streaming_trigger_support, { "HW Triggering", "usbvideo.streaming.triggerSupport", FT_BOOLEAN, BASE_DEC, TFS(&tfs_supported_not_supported), 0, "Is HW triggering supported", HFILL } }, { &hf_usb_vid_streaming_trigger_usage, { "bTriggerUsage", "usbvideo.streaming.triggerUsage", FT_UINT8, BASE_DEC, VALS(vs_trigger_usage), 0, "How host SW should respond to trigger", HFILL } }, /***** Interrupt URB *****/ { &hf_usb_vid_interrupt_bStatusType, { "Status Type", "usbvideo.interrupt.statusType", FT_UINT8, BASE_HEX, VALS(interrupt_status_types), 0xF, NULL, HFILL } }, { &hf_usb_vid_interrupt_bAttribute, { "Change Type", "usbvideo.interrupt.attribute", FT_UINT8, BASE_HEX | BASE_EXT_STRING, &control_change_types_ext, 0, "Type of control change", HFILL } }, { &hf_usb_vid_interrupt_bOriginator, { "Originator", "usbvideo.interrupt.originator", FT_UINT8, BASE_DEC, NULL, 0, "ID of the entity that reports this interrupt", HFILL } }, { &hf_usb_vid_control_interrupt_bEvent, { "Event", "usbvideo.interrupt.controlEvent", FT_UINT8, BASE_HEX, VALS(control_interrupt_events), 0, "Type of event", HFILL } }, /***** Video Control Endpoint Descriptor *****/ { &hf_usb_vid_epdesc_subtype, { "Subtype", "usbvideo.ep.descriptorSubType", FT_UINT8, BASE_DEC, VALS(vc_ep_descriptor_subtypes), 0, "Descriptor Subtype", HFILL } }, { &hf_usb_vid_epdesc_max_transfer_sz, { "wMaxTransferSize", "usbvideo.ep.maxInterruptSize", FT_UINT16, BASE_DEC, NULL, 0x0, "Max interrupt structure size", HFILL } }, /***** Fields used in multiple contexts *****/ { &hf_usb_vid_ifdesc_wTotalLength, { "wTotalLength", "usbvideo.totalLength", FT_UINT16, BASE_DEC, NULL, 0, "Video interface descriptor size", HFILL } }, { &hf_usb_vid_bControlSize, { "bControlSize", "usbvideo.bmcontrolSize", FT_UINT8, BASE_DEC, NULL, 0, "Size of bmControls field", HFILL } }, { &hf_usb_vid_bmControl, { "bmControl", "usbvideo.availableControls", FT_UINT32, BASE_HEX, NULL, 0, "Available controls", HFILL } }, { &hf_usb_vid_bmControl_bytes, { "bmControl", "usbvideo.availableControls.bytes", FT_BYTES, BASE_NONE, NULL, 0, "Available controls", HFILL } }, { &hf_usb_vid_control_ifdesc_src_id, { "bSourceID", "usbvideo.sourceID", FT_UINT8, BASE_DEC, NULL, 0x0, "Entity to which this terminal/unit is connected", HFILL } }, /**********/ { &hf_usb_vid_control_ifdesc_subtype, { "Subtype", "usbvideo.control.descriptorSubType", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &vc_if_descriptor_subtypes_ext, 0, "Descriptor Subtype", HFILL } }, { &hf_usb_vid_streaming_ifdesc_subtype, { "Subtype", "usbvideo.streaming.descriptorSubType", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &vs_if_descriptor_subtypes_ext, 0, "Descriptor Subtype", HFILL } }, { &hf_usb_vid_descriptor_data, { "Descriptor data", "usbvideo.descriptor_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_usb_vid_control_data, { "Control data", "usbvideo.control_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_usb_vid_control_value, { "Control value", "usbvideo.control_value", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_usb_vid_value_data, { "Value data", "usbvideo.value_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, }; static gint *usb_vid_subtrees[] = { &ett_usb_vid, &ett_descriptor_video_endpoint, &ett_descriptor_video_control, &ett_descriptor_video_streaming, &ett_camera_controls, &ett_processing_controls, &ett_streaming_controls, &ett_streaming_info, &ett_interlace_flags, &ett_frame_capability_flags, &ett_mjpeg_flags, &ett_video_probe, &ett_probe_hint, &ett_probe_framing, &ett_video_standards, &ett_control_capabilities }; static ei_register_info ei[] = { { &ei_usb_vid_subtype_unknown, { "usbvideo.subtype.unknown", PI_UNDECODED, PI_WARN, "Unknown VC subtype", EXPFILL }}, { &ei_usb_vid_bitmask_len, { "usbvideo.bitmask_len_error", PI_UNDECODED, PI_WARN, "Only least-significant bytes decoded", EXPFILL }}, }; expert_module_t* expert_usb_vid; proto_usb_vid = proto_register_protocol("USB Video", "USBVIDEO", "usbvideo"); proto_register_field_array(proto_usb_vid, hf, array_length(hf)); proto_register_subtree_array(usb_vid_subtrees, array_length(usb_vid_subtrees)); expert_usb_vid = expert_register_protocol(proto_usb_vid); expert_register_field_array(expert_usb_vid, ei, array_length(ei)); } void proto_reg_handoff_usb_vid(void) { dissector_handle_t usb_vid_control_handle; dissector_handle_t usb_vid_descriptor_handle; dissector_handle_t usb_vid_interrupt_handle; usb_vid_control_handle = create_dissector_handle(dissect_usb_vid_control, proto_usb_vid); dissector_add_uint("usb.control", IF_CLASS_VIDEO, usb_vid_control_handle); usb_vid_descriptor_handle = create_dissector_handle(dissect_usb_vid_descriptor, proto_usb_vid); dissector_add_uint("usb.descriptor", IF_CLASS_VIDEO, usb_vid_descriptor_handle); usb_vid_interrupt_handle = create_dissector_handle(dissect_usb_vid_interrupt, proto_usb_vid); dissector_add_uint("usb.interrupt", IF_CLASS_VIDEO, usb_vid_interrupt_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5108_3
crossvul-cpp_data_good_3253_0
/* radare2 - LGPL - Copyright 2017 - wargio */ #include <stdlib.h> #include <string.h> #include <r_util.h> #include <r_types.h> #include "r_x509_internal.h" #include "r_pkcs7_internal.h" bool r_pkcs7_parse_certificaterevocationlists (RPKCS7CertificateRevocationLists *crls, RASN1Object *object) { ut32 i; if (!crls && !object) { return false; } if (object->list.length > 0) { crls->elements = (RX509CertificateRevocationList **) calloc (object->list.length, sizeof (RX509CertificateRevocationList*)); if (!crls->elements) { return false; } crls->length = object->list.length; for (i = 0; i < crls->length; ++i) { crls->elements[i] = r_x509_parse_crl (object->list.objects[i]); } } return true; } void r_pkcs7_free_certificaterevocationlists (RPKCS7CertificateRevocationLists *crls) { ut32 i; if (crls) { for (i = 0; i < crls->length; ++i) { r_x509_free_crl (crls->elements[i]); crls->elements[i] = NULL; } R_FREE (crls->elements); // Used internally pkcs #7, so it should't free crls. } } bool r_pkcs7_parse_extendedcertificatesandcertificates (RPKCS7ExtendedCertificatesAndCertificates *ecac, RASN1Object *object) { ut32 i; if (!ecac && !object) { return false; } if (object->list.length > 0) { ecac->elements = (RX509Certificate **) calloc (object->list.length, sizeof (RX509Certificate*)); if (!ecac->elements) { return false; } ecac->length = object->list.length; for (i = 0; i < ecac->length; ++i) { ecac->elements[i] = r_x509_parse_certificate (object->list.objects[i]); object->list.objects[i] = NULL; } } return true; } void r_pkcs7_free_extendedcertificatesandcertificates (RPKCS7ExtendedCertificatesAndCertificates *ecac) { ut32 i; if (ecac) { for (i = 0; i < ecac->length; ++i) { r_x509_free_certificate (ecac->elements[i]); ecac->elements[i] = NULL; } R_FREE (ecac->elements); // Used internally pkcs #7, so it should't free ecac. } } bool r_pkcs7_parse_digestalgorithmidentifier (RPKCS7DigestAlgorithmIdentifiers *dai, RASN1Object *object) { ut32 i; if (!dai && !object) { return false; } if (object->list.length > 0) { dai->elements = (RX509AlgorithmIdentifier **) calloc (object->list.length, sizeof (RX509AlgorithmIdentifier*)); if (!dai->elements) { return false; } dai->length = object->list.length; for (i = 0; i < dai->length; ++i) { // r_x509_parse_algorithmidentifier returns bool, // so i have to allocate before calling the function dai->elements[i] = (RX509AlgorithmIdentifier *) malloc (sizeof (RX509AlgorithmIdentifier)); //should i handle invalid memory? the function checks the pointer //or it should return if dai->elements[i] == NULL ? if (dai->elements[i]) { //Memset is needed to initialize to 0 the structure and avoid garbage. memset (dai->elements[i], 0, sizeof (RX509AlgorithmIdentifier)); r_x509_parse_algorithmidentifier (dai->elements[i], object->list.objects[i]); } } } return true; } void r_pkcs7_free_digestalgorithmidentifier (RPKCS7DigestAlgorithmIdentifiers *dai) { ut32 i; if (dai) { for (i = 0; i < dai->length; ++i) { if (dai->elements[i]) { r_x509_free_algorithmidentifier (dai->elements[i]); // r_x509_free_algorithmidentifier doesn't free the pointer // because on x509 the original use was internal. R_FREE (dai->elements[i]); } } R_FREE (dai->elements); // Used internally pkcs #7, so it should't free dai. } } bool r_pkcs7_parse_contentinfo (RPKCS7ContentInfo* ci, RASN1Object *object) { if (!ci || !object || object->list.length < 1 || !object->list.objects[0]) { return false; } ci->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); if (object->list.length > 1) { R_PTR_MOVE (ci->content, object->list.objects[1]); } return true; } void r_pkcs7_free_contentinfo (RPKCS7ContentInfo* ci) { if (ci) { r_asn1_free_object (ci->content); r_asn1_free_string (ci->contentType); // Used internally pkcs #7, so it should't free ci. } } bool r_pkcs7_parse_issuerandserialnumber (RPKCS7IssuerAndSerialNumber* iasu, RASN1Object *object) { if (!iasu || !object || object->list.length != 2) { return false; } r_x509_parse_name (&iasu->issuer, object->list.objects[0]); R_PTR_MOVE (iasu->serialNumber, object->list.objects[1]); return true; } void r_pkcs7_free_issuerandserialnumber (RPKCS7IssuerAndSerialNumber* iasu) { if (iasu) { r_x509_free_name (&iasu->issuer); r_asn1_free_object (iasu->serialNumber); // Used internally pkcs #7, so it should't free iasu. } } /* RX509AlgorithmIdentifier digestEncryptionAlgorithm; RASN1Object *encryptedDigest; RASN1Object *unauthenticatedAttributes; //Optional type ?? } RPKCS7SignerInfo; */ bool r_pkcs7_parse_signerinfo (RPKCS7SignerInfo* si, RASN1Object *object) { RASN1Object **elems; ut32 shift = 3; if (!si || !object || object->list.length < 5) { return false; } elems = object->list.objects; //Following RFC si->version = (ut32) elems[0]->sector[0]; r_pkcs7_parse_issuerandserialnumber (&si->issuerAndSerialNumber, elems[1]); r_x509_parse_algorithmidentifier (&si->digestAlgorithm, elems[2]); if (shift < object->list.length && elems[shift]->klass == CLASS_CONTEXT && elems[shift]->tag == 0) { r_pkcs7_parse_attributes (&si->authenticatedAttributes, elems[shift]); shift++; } if (shift < object->list.length) { r_x509_parse_algorithmidentifier (&si->digestEncryptionAlgorithm, elems[shift]); shift++; } if (shift < object->list.length) { R_PTR_MOVE (si->encryptedDigest, object->list.objects[shift]); shift++; } if (shift < object->list.length && elems[shift]->klass == CLASS_CONTEXT && elems[shift]->tag == 1) { r_pkcs7_parse_attributes (&si->unauthenticatedAttributes, elems[shift]); } return true; } void r_pkcs7_free_signerinfo (RPKCS7SignerInfo* si) { if (si) { r_pkcs7_free_issuerandserialnumber (&si->issuerAndSerialNumber); r_x509_free_algorithmidentifier (&si->digestAlgorithm); r_pkcs7_free_attributes (&si->authenticatedAttributes); r_x509_free_algorithmidentifier (&si->digestEncryptionAlgorithm); r_asn1_free_object (si->encryptedDigest); r_pkcs7_free_attributes (&si->unauthenticatedAttributes); free (si); } } bool r_pkcs7_parse_signerinfos (RPKCS7SignerInfos *ss, RASN1Object *object) { ut32 i; if (!ss && !object) { return false; } if (object->list.length > 0) { ss->elements = (RPKCS7SignerInfo **) calloc (object->list.length, sizeof (RPKCS7SignerInfo*)); if (!ss->elements) { return false; } ss->length = object->list.length; for (i = 0; i < ss->length; ++i) { // r_pkcs7_parse_signerinfo returns bool, // so i have to allocate before calling the function ss->elements[i] = R_NEW0 (RPKCS7SignerInfo); //should i handle invalid memory? the function checks the pointer //or it should return if si->elements[i] == NULL ? r_pkcs7_parse_signerinfo (ss->elements[i], object->list.objects[i]); } } return true; } void r_pkcs7_free_signerinfos (RPKCS7SignerInfos *ss) { ut32 i; if (ss) { for (i = 0; i < ss->length; i++) { r_pkcs7_free_signerinfo (ss->elements[i]); ss->elements[i] = NULL; } R_FREE (ss->elements); // Used internally pkcs #7, so it should't free ss. } } bool r_pkcs7_parse_signeddata (RPKCS7SignedData *sd, RASN1Object *object) { RASN1Object **elems; ut32 shift = 3; if (!sd || !object || object->list.length < 4) { return false; } memset (sd, 0, sizeof (RPKCS7SignedData)); elems = object->list.objects; //Following RFC sd->version = (ut32) elems[0]->sector[0]; r_pkcs7_parse_digestalgorithmidentifier (&sd->digestAlgorithms, elems[1]); r_pkcs7_parse_contentinfo (&sd->contentInfo, elems[2]); //Optional if (shift < object->list.length && elems[shift]->klass == CLASS_CONTEXT && elems[shift]->tag == 0) { r_pkcs7_parse_extendedcertificatesandcertificates (&sd->certificates, elems[shift]); shift++; } //Optional if (shift < object->list.length && elems[shift]->klass == CLASS_CONTEXT && elems[shift]->tag == 1) { r_pkcs7_parse_certificaterevocationlists (&sd->crls, elems[shift]); shift++; } if (shift < object->list.length) { r_pkcs7_parse_signerinfos (&sd->signerinfos, elems[shift]); } return true; } void r_pkcs7_free_signeddata (RPKCS7SignedData* sd) { if (sd) { r_pkcs7_free_digestalgorithmidentifier (&sd->digestAlgorithms); r_pkcs7_free_contentinfo (&sd->contentInfo); r_pkcs7_free_extendedcertificatesandcertificates (&sd->certificates); r_pkcs7_free_certificaterevocationlists (&sd->crls); r_pkcs7_free_signerinfos (&sd->signerinfos); // Used internally pkcs #7, so it should't free sd. } } RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects || !object->list.objects[0] || !object->list.objects[1] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; } void r_pkcs7_free_cms (RCMS* container) { if (container) { r_asn1_free_string (container->contentType); r_pkcs7_free_signeddata (&container->signedData); free (container); } } RPKCS7Attribute* r_pkcs7_parse_attribute (RASN1Object *object) { RPKCS7Attribute* attribute; if (!object || object->list.length < 1) { return NULL; } attribute = R_NEW0 (RPKCS7Attribute); if (!attribute) { return NULL; } if (object->list.objects[0]) { attribute->oid = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); } if (object->list.length == 2) { R_PTR_MOVE (attribute->data, object->list.objects[1]); } return attribute; } void r_pkcs7_free_attribute (RPKCS7Attribute* attribute) { if (attribute) { r_asn1_free_object (attribute->data); r_asn1_free_string (attribute->oid); free (attribute); } } bool r_pkcs7_parse_attributes (RPKCS7Attributes* attributes, RASN1Object *object) { ut32 i; if (!attributes || !object || !object->list.length) { return false; } attributes->length = object->list.length; if (attributes->length > 0) { attributes->elements = R_NEWS0 (RPKCS7Attribute*, attributes->length); if (!attributes->elements) { attributes->length = 0; return false; } for (i = 0; i < object->list.length; ++i) { attributes->elements[i] = r_pkcs7_parse_attribute (object->list.objects[i]); } } return true; } void r_pkcs7_free_attributes (RPKCS7Attributes* attributes) { ut32 i; if (attributes) { for (i = 0; i < attributes->length; ++i) { r_pkcs7_free_attribute (attributes->elements[i]); } R_FREE (attributes->elements); // Used internally pkcs #7, so it should't free attributes. } } char* r_pkcs7_signerinfos_dump (RX509CertificateRevocationList *crl, char* buffer, ut32 length, const char* pad) { RASN1String *algo = NULL, *last = NULL, *next = NULL; ut32 i, p; int r; char *tmp, *pad2, *pad3; if (!crl || !buffer || !length) { return NULL; } if (!pad) { pad = ""; } pad3 = r_str_newf ("%s ", pad); if (!pad3) return NULL; pad2 = pad3 + 2; algo = crl->signature.algorithm; last = crl->lastUpdate; next = crl->nextUpdate; r = snprintf (buffer, length, "%sCRL:\n%sSignature:\n%s%s\n%sIssuer\n", pad, pad2, pad3, algo ? algo->string : "", pad2); p = (ut32) r; if (r < 0 || !(tmp = r_x509_name_dump (&crl->issuer, buffer + p, length - p, pad3))) { free (pad3); return NULL; } p = tmp - buffer; if (length <= p) { free (pad3); return NULL; } r = snprintf (buffer + p, length - p, "%sLast Update: %s\n%sNext Update: %s\n%sRevoked Certificates:\n", pad2, last ? last->string : "Missing", pad2, next ? next->string : "Missing", pad2); p += (ut32) r; if (r < 0) { free (pad3); return NULL; } for (i = 0; i < crl->length; ++i) { if (length <= p || !(tmp = r_x509_crlentry_dump (crl->revokedCertificates[i], buffer + p, length - p, pad3))) { free (pad3); return NULL; } p = tmp - buffer; } free (pad3); return buffer + p; } char* r_x509_signedinfo_dump (RPKCS7SignerInfo *si, char* buffer, ut32 length, const char* pad) { RASN1String *s = NULL; RASN1Object *o = NULL; ut32 i, p; int r; char *tmp, *pad2, *pad3; if (!si || !buffer || !length) { return NULL; } if (!pad) { pad = ""; } pad3 = r_str_newf ("%s ", pad); if (!pad3) { return NULL; } pad2 = pad3 + 2; r = snprintf (buffer, length, "%sSignerInfo:\n%sVersion: v%u\n%sIssuer\n", pad, pad2, si->version + 1, pad2); p = (ut32) r; if (r < 0) { free (pad3); return NULL; } if (length <= p || !(tmp = r_x509_name_dump (&si->issuerAndSerialNumber.issuer, buffer + p, length - p, pad3))) { free (pad3); return NULL; } p = tmp - buffer; if ((o = si->issuerAndSerialNumber.serialNumber)) { s = r_asn1_stringify_integer (o->sector, o->length); } else { s = NULL; } if (length <= p) { free (pad3); return NULL; } r = snprintf (buffer + p, length - p, "%sSerial Number:\n%s%s\n", pad2, pad3, s ? s->string : "Missing"); p += (ut32) r; r_asn1_free_string (s); if (r < 0 || length <= p) { free (pad3); return NULL; } s = si->digestAlgorithm.algorithm; r = snprintf (buffer + p, length - p, "%sDigest Algorithm:\n%s%s\n%sAuthenticated Attributes:\n", pad2, pad3, s ? s->string : "Missing", pad2); p += (ut32) r; if (r < 0 || length <= p) { free (pad3); return NULL; } for (i = 0; i < si->authenticatedAttributes.length; ++i) { RPKCS7Attribute* attr = si->authenticatedAttributes.elements[i]; if (!attr) continue; r = snprintf (buffer + p, length - p, "%s%s: %u bytes\n", pad3, attr->oid ? attr->oid->string : "Missing", attr->data ? attr->data->length : 0); p += (ut32) r; if (r < 0 || length <= p) { free (pad3); return NULL; } } s = si->digestEncryptionAlgorithm.algorithm; if (length <= p) { free (pad3); return NULL; } r = snprintf (buffer + p, length - p, "%sDigest Encryption Algorithm\n%s%s\n", pad2, pad3, s ? s->string : "Missing"); p += (ut32) r; if (r < 0 || length <= p) { free (pad3); return NULL; } // if ((o = si->encryptedDigest)) s = r_asn1_stringify_bytes (o->sector, o->length); // else s = NULL; // r = snprintf (buffer + p, length - p, "%sEncrypted Digest: %u bytes\n%s\n", pad2, o ? o->length : 0, s ? s->string : "Missing"); // p += (ut32) r; // r_asn1_free_string (s); r = snprintf (buffer + p, length - p, "%sEncrypted Digest: %u bytes\n", pad2, o ? o->length : 0); if (r < 0 || length <= p) { free (pad3); return NULL; } r = snprintf (buffer + p, length - p, "%sUnauthenticated Attributes:\n", pad2); p += (ut32) r; if (r < 0 || length <= p) { free (pad3); return NULL; } for (i = 0; i < si->unauthenticatedAttributes.length; ++i) { RPKCS7Attribute* attr = si->unauthenticatedAttributes.elements[i]; if (!attr) { continue; } o = attr->data; r = snprintf (buffer + p, length - p, "%s%s: %u bytes\n", pad3, attr->oid ? attr->oid->string : "Missing", o ? o->length : 0); p += (ut32) r; if (r < 0 || length <= p) { free (pad3); return NULL; } } free (pad3); return buffer + p; } char *r_pkcs7_cms_dump (RCMS* container) { RPKCS7SignedData *sd; ut32 i, length, p = 0; int r; char *buffer = NULL, *tmp = NULL; if (!container) { return NULL; } sd = &container->signedData; length = 2048 + (container->signedData.certificates.length * 1024); if(!length) { return NULL; } buffer = (char*) calloc (1, length); if (!buffer) { return NULL; } r = snprintf (buffer, length, "signedData\n Version: %u\n Digest Algorithms:\n", sd->version); p += (ut32) r; if (r < 0 || length <= p) { free (buffer); return NULL; } if (container->signedData.digestAlgorithms.elements) { for (i = 0; i < container->signedData.digestAlgorithms.length; ++i) { if (container->signedData.digestAlgorithms.elements[i]) { RASN1String *s = container->signedData.digestAlgorithms.elements[i]->algorithm; r = snprintf (buffer + p, length - p, " %s\n", s ? s->string : "Missing"); p += (ut32) r; if (r < 0 || length <= p) { free (buffer); return NULL; } } } } r = snprintf (buffer + p, length - p, " Certificates: %u\n", container->signedData.certificates.length); p += (ut32) r; if (r < 0 || length <= p) { free (buffer); return NULL; } for (i = 0; i < container->signedData.certificates.length; ++i) { if (length <= p || !(tmp = r_x509_certificate_dump (container->signedData.certificates.elements[i], buffer + p, length - p, " "))) { free (buffer); return NULL; } p = tmp - buffer; } for (i = 0; i < container->signedData.crls.length; ++i) { if (length <= p || !(tmp = r_x509_crl_dump (container->signedData.crls.elements[i], buffer + p, length - p, " "))) { free (buffer); return NULL; } p = tmp - buffer; } p = tmp - buffer; if (length <= p) { free (buffer); return NULL; } r = snprintf (buffer + p, length - p, " SignerInfos:\n"); p += (ut32) r; if (r < 0 || length <= p) { free (buffer); return NULL; } if (container->signedData.signerinfos.elements) { for (i = 0; i < container->signedData.signerinfos.length; ++i) { if (length <= p || !(tmp = r_x509_signedinfo_dump (container->signedData.signerinfos.elements[i], buffer + p, length - p, " "))) { free (buffer); return NULL; } p = tmp - buffer; } } return buffer; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_3253_0
crossvul-cpp_data_good_323_0
/************************************************************ * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting * documentation, and that the name of Silicon Graphics not be * used in advertising or publicity pertaining to distribution * of the software without specific prior written permission. * Silicon Graphics makes no representation about the suitability * of this software for any purpose. It is provided "as is" * without any express or implied warranty. * * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH * THE USE OR PERFORMANCE OF THIS SOFTWARE. * ********************************************************/ #include "xkbcomp-priv.h" #include "text.h" #include "expr.h" typedef bool (*IdentLookupFunc)(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, unsigned int *val_rtrn); bool ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; } static bool SimpleLookup(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, unsigned int *val_rtrn) { const LookupEntry *entry; const char *str; if (!priv || field == XKB_ATOM_NONE || type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); for (entry = priv; entry && entry->name; entry++) { if (istreq(str, entry->name)) { *val_rtrn = entry->value; return true; } } return false; } /* Data passed in the *priv argument for LookupModMask. */ typedef struct { const struct xkb_mod_set *mods; enum mod_type mod_type; } LookupModMaskPriv; static bool LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (!str) return false; if (istreq(str, "all")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, "none")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; } bool ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr, bool *set_rtrn) { bool ok = false; const char *ident; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) { log_err(ctx, "Found constant of type %s where boolean was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *set_rtrn = expr->boolean.set; return true; case EXPR_IDENT: ident = xkb_atom_text(ctx, expr->ident.ident); if (ident) { if (istreq(ident, "true") || istreq(ident, "yes") || istreq(ident, "on")) { *set_rtrn = true; return true; } else if (istreq(ident, "false") || istreq(ident, "no") || istreq(ident, "off")) { *set_rtrn = false; return true; } } log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_INVERT: case EXPR_NOT: ok = ExprResolveBoolean(ctx, expr->unary.child, set_rtrn); if (ok) *set_rtrn = !*set_rtrn; return ok; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_UNARY_PLUS: log_err(ctx, "%s of boolean values not permitted\n", expr_op_type_to_string(expr->expr.op)); break; default: log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n", expr->expr.op); break; } return false; } bool ExprResolveKeyCode(struct xkb_context *ctx, const ExprDef *expr, xkb_keycode_t *kc) { xkb_keycode_t leftRtrn, rightRtrn; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_INT) { log_err(ctx, "Found constant of type %s where an int was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *kc = (xkb_keycode_t) expr->integer.ival; return true; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: if (!ExprResolveKeyCode(ctx, expr->binary.left, &leftRtrn) || !ExprResolveKeyCode(ctx, expr->binary.right, &rightRtrn)) return false; switch (expr->expr.op) { case EXPR_ADD: *kc = leftRtrn + rightRtrn; break; case EXPR_SUBTRACT: *kc = leftRtrn - rightRtrn; break; case EXPR_MULTIPLY: *kc = leftRtrn * rightRtrn; break; case EXPR_DIVIDE: if (rightRtrn == 0) { log_err(ctx, "Cannot divide by zero: %d / %d\n", leftRtrn, rightRtrn); return false; } *kc = leftRtrn / rightRtrn; break; default: break; } return true; case EXPR_NEGATE: if (!ExprResolveKeyCode(ctx, expr->unary.child, &leftRtrn)) return false; *kc = ~leftRtrn; return true; case EXPR_UNARY_PLUS: return ExprResolveKeyCode(ctx, expr->unary.child, kc); default: log_wsgo(ctx, "Unknown operator %d in ResolveKeyCode\n", expr->expr.op); break; } return false; } /** * This function returns ... something. It's a bit of a guess, really. * * If an integer is given in value ctx, it will be returned in ival. * If an ident or field reference is given, the lookup function (if given) * will be called. At the moment, only SimpleLookup use this, and they both * return the results in uval. And don't support field references. * * Cool. */ static bool ExprResolveIntegerLookup(struct xkb_context *ctx, const ExprDef *expr, int *val_rtrn, IdentLookupFunc lookup, const void *lookupPriv) { bool ok = false; int l, r; unsigned u; ExprDef *left, *right; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_INT) { log_err(ctx, "Found constant of type %s where an int was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *val_rtrn = expr->integer.ival; return true; case EXPR_IDENT: if (lookup) ok = lookup(ctx, lookupPriv, expr->ident.ident, EXPR_TYPE_INT, &u); if (!ok) log_err(ctx, "Identifier \"%s\" of type int is unknown\n", xkb_atom_text(ctx, expr->ident.ident)); else *val_rtrn = (int) u; return ok; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type int is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: left = expr->binary.left; right = expr->binary.right; if (!ExprResolveIntegerLookup(ctx, left, &l, lookup, lookupPriv) || !ExprResolveIntegerLookup(ctx, right, &r, lookup, lookupPriv)) return false; switch (expr->expr.op) { case EXPR_ADD: *val_rtrn = l + r; break; case EXPR_SUBTRACT: *val_rtrn = l - r; break; case EXPR_MULTIPLY: *val_rtrn = l * r; break; case EXPR_DIVIDE: if (r == 0) { log_err(ctx, "Cannot divide by zero: %d / %d\n", l, r); return false; } *val_rtrn = l / r; break; default: log_err(ctx, "%s of integers not permitted\n", expr_op_type_to_string(expr->expr.op)); return false; } return true; case EXPR_ASSIGN: log_wsgo(ctx, "Assignment operator not implemented yet\n"); break; case EXPR_NOT: log_err(ctx, "The ! operator cannot be applied to an integer\n"); return false; case EXPR_INVERT: case EXPR_NEGATE: left = expr->unary.child; if (!ExprResolveIntegerLookup(ctx, left, &l, lookup, lookupPriv)) return false; *val_rtrn = (expr->expr.op == EXPR_NEGATE ? -l : ~l); return true; case EXPR_UNARY_PLUS: left = expr->unary.child; return ExprResolveIntegerLookup(ctx, left, val_rtrn, lookup, lookupPriv); default: log_wsgo(ctx, "Unknown operator %d in ResolveInteger\n", expr->expr.op); break; } return false; } bool ExprResolveInteger(struct xkb_context *ctx, const ExprDef *expr, int *val_rtrn) { return ExprResolveIntegerLookup(ctx, expr, val_rtrn, NULL, NULL); } bool ExprResolveGroup(struct xkb_context *ctx, const ExprDef *expr, xkb_layout_index_t *group_rtrn) { bool ok; int result; ok = ExprResolveIntegerLookup(ctx, expr, &result, SimpleLookup, groupNames); if (!ok) return false; if (result <= 0 || result > XKB_MAX_GROUPS) { log_err(ctx, "Group index %u is out of range (1..%d)\n", result, XKB_MAX_GROUPS); return false; } *group_rtrn = (xkb_layout_index_t) result; return true; } bool ExprResolveLevel(struct xkb_context *ctx, const ExprDef *expr, xkb_level_index_t *level_rtrn) { bool ok; int result; ok = ExprResolveIntegerLookup(ctx, expr, &result, SimpleLookup, levelNames); if (!ok) return false; if (result < 1) { log_err(ctx, "Shift level %d is out of range\n", result); return false; } /* Level is zero-indexed from now on. */ *level_rtrn = (unsigned int) (result - 1); return true; } bool ExprResolveButton(struct xkb_context *ctx, const ExprDef *expr, int *btn_rtrn) { return ExprResolveIntegerLookup(ctx, expr, btn_rtrn, SimpleLookup, buttonNames); } bool ExprResolveString(struct xkb_context *ctx, const ExprDef *expr, xkb_atom_t *val_rtrn) { switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_STRING) { log_err(ctx, "Found constant of type %s, expected a string\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *val_rtrn = expr->string.str; return true; case EXPR_IDENT: log_err(ctx, "Identifier \"%s\" of type string not found\n", xkb_atom_text(ctx, expr->ident.ident)); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type string not found\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_INVERT: case EXPR_NOT: case EXPR_UNARY_PLUS: log_err(ctx, "%s of strings not permitted\n", expr_op_type_to_string(expr->expr.op)); return false; default: log_wsgo(ctx, "Unknown operator %d in ResolveString\n", expr->expr.op); break; } return false; } bool ExprResolveEnum(struct xkb_context *ctx, const ExprDef *expr, unsigned int *val_rtrn, const LookupEntry *values) { if (expr->expr.op != EXPR_IDENT) { log_err(ctx, "Found a %s where an enumerated value was expected\n", expr_op_type_to_string(expr->expr.op)); return false; } if (!SimpleLookup(ctx, values, expr->ident.ident, EXPR_TYPE_INT, val_rtrn)) { log_err(ctx, "Illegal identifier %s; expected one of:\n", xkb_atom_text(ctx, expr->ident.ident)); while (values && values->name) { log_err(ctx, "\t%s\n", values->name); values++; } return false; } return true; } static bool ExprResolveMaskLookup(struct xkb_context *ctx, const ExprDef *expr, unsigned int *val_rtrn, IdentLookupFunc lookup, const void *lookupPriv) { bool ok = false; unsigned int l = 0, r = 0; int v; ExprDef *left, *right; const char *bogus = NULL; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_INT) { log_err(ctx, "Found constant of type %s where a mask was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *val_rtrn = (unsigned int) expr->integer.ival; return true; case EXPR_IDENT: ok = lookup(ctx, lookupPriv, expr->ident.ident, EXPR_TYPE_INT, val_rtrn); if (!ok) log_err(ctx, "Identifier \"%s\" of type int is unknown\n", xkb_atom_text(ctx, expr->ident.ident)); return ok; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type int is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_ARRAY_REF: bogus = "array reference"; /* fallthrough */ case EXPR_ACTION_DECL: if (bogus == NULL) bogus = "function use"; log_err(ctx, "Unexpected %s in mask expression; Expression Ignored\n", bogus); return false; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: left = expr->binary.left; right = expr->binary.right; if (!ExprResolveMaskLookup(ctx, left, &l, lookup, lookupPriv) || !ExprResolveMaskLookup(ctx, right, &r, lookup, lookupPriv)) return false; switch (expr->expr.op) { case EXPR_ADD: *val_rtrn = l | r; break; case EXPR_SUBTRACT: *val_rtrn = l & (~r); break; case EXPR_MULTIPLY: case EXPR_DIVIDE: log_err(ctx, "Cannot %s masks; Illegal operation ignored\n", (expr->expr.op == EXPR_DIVIDE ? "divide" : "multiply")); return false; default: break; } return true; case EXPR_ASSIGN: log_wsgo(ctx, "Assignment operator not implemented yet\n"); break; case EXPR_INVERT: left = expr->unary.child; if (!ExprResolveIntegerLookup(ctx, left, &v, lookup, lookupPriv)) return false; *val_rtrn = ~v; return true; case EXPR_UNARY_PLUS: case EXPR_NEGATE: case EXPR_NOT: left = expr->unary.child; if (!ExprResolveIntegerLookup(ctx, left, &v, lookup, lookupPriv)) log_err(ctx, "The %s operator cannot be used with a mask\n", (expr->expr.op == EXPR_NEGATE ? "-" : "!")); return false; default: log_wsgo(ctx, "Unknown operator %d in ResolveMask\n", expr->expr.op); break; } return false; } bool ExprResolveMask(struct xkb_context *ctx, const ExprDef *expr, unsigned int *mask_rtrn, const LookupEntry *values) { return ExprResolveMaskLookup(ctx, expr, mask_rtrn, SimpleLookup, values); } bool ExprResolveModMask(struct xkb_context *ctx, const ExprDef *expr, enum mod_type mod_type, const struct xkb_mod_set *mods, xkb_mod_mask_t *mask_rtrn) { LookupModMaskPriv priv = { .mods = mods, .mod_type = mod_type }; return ExprResolveMaskLookup(ctx, expr, mask_rtrn, LookupModMask, &priv); } bool ExprResolveKeySym(struct xkb_context *ctx, const ExprDef *expr, xkb_keysym_t *sym_rtrn) { int val; if (expr->expr.op == EXPR_IDENT) { const char *str = xkb_atom_text(ctx, expr->ident.ident); *sym_rtrn = xkb_keysym_from_name(str, 0); if (*sym_rtrn != XKB_KEY_NoSymbol) return true; } if (!ExprResolveInteger(ctx, expr, &val)) return false; if (val < 0 || val >= 10) return false; *sym_rtrn = XKB_KEY_0 + (xkb_keysym_t) val; return true; } bool ExprResolveMod(struct xkb_context *ctx, const ExprDef *def, enum mod_type mod_type, const struct xkb_mod_set *mods, xkb_mod_index_t *ndx_rtrn) { xkb_mod_index_t ndx; xkb_atom_t name; if (def->expr.op != EXPR_IDENT) { log_err(ctx, "Cannot resolve virtual modifier: " "found %s where a virtual modifier name was expected\n", expr_op_type_to_string(def->expr.op)); return false; } name = def->ident.ident; ndx = XkbModNameToIndex(mods, name, mod_type); if (ndx == XKB_MOD_INVALID) { log_err(ctx, "Cannot resolve virtual modifier: " "\"%s\" was not previously declared\n", xkb_atom_text(ctx, name)); return false; } *ndx_rtrn = ndx; return true; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_323_0
crossvul-cpp_data_bad_1223_2
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2011, 2012 STRATO. All rights reserved. */ #include <linux/blkdev.h> #include <linux/ratelimit.h> #include <linux/sched/mm.h> #include "ctree.h" #include "volumes.h" #include "disk-io.h" #include "ordered-data.h" #include "transaction.h" #include "backref.h" #include "extent_io.h" #include "dev-replace.h" #include "check-integrity.h" #include "rcu-string.h" #include "raid56.h" /* * This is only the first step towards a full-features scrub. It reads all * extent and super block and verifies the checksums. In case a bad checksum * is found or the extent cannot be read, good data will be written back if * any can be found. * * Future enhancements: * - In case an unrepairable extent is encountered, track which files are * affected and report them * - track and record media errors, throw out bad devices * - add a mode to also read unallocated space */ struct scrub_block; struct scrub_ctx; /* * the following three values only influence the performance. * The last one configures the number of parallel and outstanding I/O * operations. The first two values configure an upper limit for the number * of (dynamically allocated) pages that are added to a bio. */ #define SCRUB_PAGES_PER_RD_BIO 32 /* 128k per bio */ #define SCRUB_PAGES_PER_WR_BIO 32 /* 128k per bio */ #define SCRUB_BIOS_PER_SCTX 64 /* 8MB per device in flight */ /* * the following value times PAGE_SIZE needs to be large enough to match the * largest node/leaf/sector size that shall be supported. * Values larger than BTRFS_STRIPE_LEN are not supported. */ #define SCRUB_MAX_PAGES_PER_BLOCK 16 /* 64k per node/leaf/sector */ struct scrub_recover { refcount_t refs; struct btrfs_bio *bbio; u64 map_length; }; struct scrub_page { struct scrub_block *sblock; struct page *page; struct btrfs_device *dev; struct list_head list; u64 flags; /* extent flags */ u64 generation; u64 logical; u64 physical; u64 physical_for_dev_replace; atomic_t refs; struct { unsigned int mirror_num:8; unsigned int have_csum:1; unsigned int io_error:1; }; u8 csum[BTRFS_CSUM_SIZE]; struct scrub_recover *recover; }; struct scrub_bio { int index; struct scrub_ctx *sctx; struct btrfs_device *dev; struct bio *bio; blk_status_t status; u64 logical; u64 physical; #if SCRUB_PAGES_PER_WR_BIO >= SCRUB_PAGES_PER_RD_BIO struct scrub_page *pagev[SCRUB_PAGES_PER_WR_BIO]; #else struct scrub_page *pagev[SCRUB_PAGES_PER_RD_BIO]; #endif int page_count; int next_free; struct btrfs_work work; }; struct scrub_block { struct scrub_page *pagev[SCRUB_MAX_PAGES_PER_BLOCK]; int page_count; atomic_t outstanding_pages; refcount_t refs; /* free mem on transition to zero */ struct scrub_ctx *sctx; struct scrub_parity *sparity; struct { unsigned int header_error:1; unsigned int checksum_error:1; unsigned int no_io_error_seen:1; unsigned int generation_error:1; /* also sets header_error */ /* The following is for the data used to check parity */ /* It is for the data with checksum */ unsigned int data_corrected:1; }; struct btrfs_work work; }; /* Used for the chunks with parity stripe such RAID5/6 */ struct scrub_parity { struct scrub_ctx *sctx; struct btrfs_device *scrub_dev; u64 logic_start; u64 logic_end; int nsectors; u64 stripe_len; refcount_t refs; struct list_head spages; /* Work of parity check and repair */ struct btrfs_work work; /* Mark the parity blocks which have data */ unsigned long *dbitmap; /* * Mark the parity blocks which have data, but errors happen when * read data or check data */ unsigned long *ebitmap; unsigned long bitmap[0]; }; struct scrub_ctx { struct scrub_bio *bios[SCRUB_BIOS_PER_SCTX]; struct btrfs_fs_info *fs_info; int first_free; int curr; atomic_t bios_in_flight; atomic_t workers_pending; spinlock_t list_lock; wait_queue_head_t list_wait; u16 csum_size; struct list_head csum_list; atomic_t cancel_req; int readonly; int pages_per_rd_bio; int is_dev_replace; struct scrub_bio *wr_curr_bio; struct mutex wr_lock; int pages_per_wr_bio; /* <= SCRUB_PAGES_PER_WR_BIO */ struct btrfs_device *wr_tgtdev; bool flush_all_writes; /* * statistics */ struct btrfs_scrub_progress stat; spinlock_t stat_lock; /* * Use a ref counter to avoid use-after-free issues. Scrub workers * decrement bios_in_flight and workers_pending and then do a wakeup * on the list_wait wait queue. We must ensure the main scrub task * doesn't free the scrub context before or while the workers are * doing the wakeup() call. */ refcount_t refs; }; struct scrub_warning { struct btrfs_path *path; u64 extent_item_size; const char *errstr; u64 physical; u64 logical; struct btrfs_device *dev; }; struct full_stripe_lock { struct rb_node node; u64 logical; u64 refs; struct mutex mutex; }; static void scrub_pending_bio_inc(struct scrub_ctx *sctx); static void scrub_pending_bio_dec(struct scrub_ctx *sctx); static int scrub_handle_errored_block(struct scrub_block *sblock_to_check); static int scrub_setup_recheck_block(struct scrub_block *original_sblock, struct scrub_block *sblocks_for_recheck); static void scrub_recheck_block(struct btrfs_fs_info *fs_info, struct scrub_block *sblock, int retry_failed_mirror); static void scrub_recheck_block_checksum(struct scrub_block *sblock); static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad, struct scrub_block *sblock_good); static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad, struct scrub_block *sblock_good, int page_num, int force_write); static void scrub_write_block_to_dev_replace(struct scrub_block *sblock); static int scrub_write_page_to_dev_replace(struct scrub_block *sblock, int page_num); static int scrub_checksum_data(struct scrub_block *sblock); static int scrub_checksum_tree_block(struct scrub_block *sblock); static int scrub_checksum_super(struct scrub_block *sblock); static void scrub_block_get(struct scrub_block *sblock); static void scrub_block_put(struct scrub_block *sblock); static void scrub_page_get(struct scrub_page *spage); static void scrub_page_put(struct scrub_page *spage); static void scrub_parity_get(struct scrub_parity *sparity); static void scrub_parity_put(struct scrub_parity *sparity); static int scrub_add_page_to_rd_bio(struct scrub_ctx *sctx, struct scrub_page *spage); static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len, u64 physical, struct btrfs_device *dev, u64 flags, u64 gen, int mirror_num, u8 *csum, int force, u64 physical_for_dev_replace); static void scrub_bio_end_io(struct bio *bio); static void scrub_bio_end_io_worker(struct btrfs_work *work); static void scrub_block_complete(struct scrub_block *sblock); static void scrub_remap_extent(struct btrfs_fs_info *fs_info, u64 extent_logical, u64 extent_len, u64 *extent_physical, struct btrfs_device **extent_dev, int *extent_mirror_num); static int scrub_add_page_to_wr_bio(struct scrub_ctx *sctx, struct scrub_page *spage); static void scrub_wr_submit(struct scrub_ctx *sctx); static void scrub_wr_bio_end_io(struct bio *bio); static void scrub_wr_bio_end_io_worker(struct btrfs_work *work); static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info); static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info); static void scrub_put_ctx(struct scrub_ctx *sctx); static inline int scrub_is_page_on_raid56(struct scrub_page *page) { return page->recover && (page->recover->bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK); } static void scrub_pending_bio_inc(struct scrub_ctx *sctx) { refcount_inc(&sctx->refs); atomic_inc(&sctx->bios_in_flight); } static void scrub_pending_bio_dec(struct scrub_ctx *sctx) { atomic_dec(&sctx->bios_in_flight); wake_up(&sctx->list_wait); scrub_put_ctx(sctx); } static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info) { while (atomic_read(&fs_info->scrub_pause_req)) { mutex_unlock(&fs_info->scrub_lock); wait_event(fs_info->scrub_pause_wait, atomic_read(&fs_info->scrub_pause_req) == 0); mutex_lock(&fs_info->scrub_lock); } } static void scrub_pause_on(struct btrfs_fs_info *fs_info) { atomic_inc(&fs_info->scrubs_paused); wake_up(&fs_info->scrub_pause_wait); } static void scrub_pause_off(struct btrfs_fs_info *fs_info) { mutex_lock(&fs_info->scrub_lock); __scrub_blocked_if_needed(fs_info); atomic_dec(&fs_info->scrubs_paused); mutex_unlock(&fs_info->scrub_lock); wake_up(&fs_info->scrub_pause_wait); } static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info) { scrub_pause_on(fs_info); scrub_pause_off(fs_info); } /* * Insert new full stripe lock into full stripe locks tree * * Return pointer to existing or newly inserted full_stripe_lock structure if * everything works well. * Return ERR_PTR(-ENOMEM) if we failed to allocate memory * * NOTE: caller must hold full_stripe_locks_root->lock before calling this * function */ static struct full_stripe_lock *insert_full_stripe_lock( struct btrfs_full_stripe_locks_tree *locks_root, u64 fstripe_logical) { struct rb_node **p; struct rb_node *parent = NULL; struct full_stripe_lock *entry; struct full_stripe_lock *ret; lockdep_assert_held(&locks_root->lock); p = &locks_root->root.rb_node; while (*p) { parent = *p; entry = rb_entry(parent, struct full_stripe_lock, node); if (fstripe_logical < entry->logical) { p = &(*p)->rb_left; } else if (fstripe_logical > entry->logical) { p = &(*p)->rb_right; } else { entry->refs++; return entry; } } /* * Insert new lock. */ ret = kmalloc(sizeof(*ret), GFP_KERNEL); if (!ret) return ERR_PTR(-ENOMEM); ret->logical = fstripe_logical; ret->refs = 1; mutex_init(&ret->mutex); rb_link_node(&ret->node, parent, p); rb_insert_color(&ret->node, &locks_root->root); return ret; } /* * Search for a full stripe lock of a block group * * Return pointer to existing full stripe lock if found * Return NULL if not found */ static struct full_stripe_lock *search_full_stripe_lock( struct btrfs_full_stripe_locks_tree *locks_root, u64 fstripe_logical) { struct rb_node *node; struct full_stripe_lock *entry; lockdep_assert_held(&locks_root->lock); node = locks_root->root.rb_node; while (node) { entry = rb_entry(node, struct full_stripe_lock, node); if (fstripe_logical < entry->logical) node = node->rb_left; else if (fstripe_logical > entry->logical) node = node->rb_right; else return entry; } return NULL; } /* * Helper to get full stripe logical from a normal bytenr. * * Caller must ensure @cache is a RAID56 block group. */ static u64 get_full_stripe_logical(struct btrfs_block_group_cache *cache, u64 bytenr) { u64 ret; /* * Due to chunk item size limit, full stripe length should not be * larger than U32_MAX. Just a sanity check here. */ WARN_ON_ONCE(cache->full_stripe_len >= U32_MAX); /* * round_down() can only handle power of 2, while RAID56 full * stripe length can be 64KiB * n, so we need to manually round down. */ ret = div64_u64(bytenr - cache->key.objectid, cache->full_stripe_len) * cache->full_stripe_len + cache->key.objectid; return ret; } /* * Lock a full stripe to avoid concurrency of recovery and read * * It's only used for profiles with parities (RAID5/6), for other profiles it * does nothing. * * Return 0 if we locked full stripe covering @bytenr, with a mutex held. * So caller must call unlock_full_stripe() at the same context. * * Return <0 if encounters error. */ static int lock_full_stripe(struct btrfs_fs_info *fs_info, u64 bytenr, bool *locked_ret) { struct btrfs_block_group_cache *bg_cache; struct btrfs_full_stripe_locks_tree *locks_root; struct full_stripe_lock *existing; u64 fstripe_start; int ret = 0; *locked_ret = false; bg_cache = btrfs_lookup_block_group(fs_info, bytenr); if (!bg_cache) { ASSERT(0); return -ENOENT; } /* Profiles not based on parity don't need full stripe lock */ if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) goto out; locks_root = &bg_cache->full_stripe_locks_root; fstripe_start = get_full_stripe_logical(bg_cache, bytenr); /* Now insert the full stripe lock */ mutex_lock(&locks_root->lock); existing = insert_full_stripe_lock(locks_root, fstripe_start); mutex_unlock(&locks_root->lock); if (IS_ERR(existing)) { ret = PTR_ERR(existing); goto out; } mutex_lock(&existing->mutex); *locked_ret = true; out: btrfs_put_block_group(bg_cache); return ret; } /* * Unlock a full stripe. * * NOTE: Caller must ensure it's the same context calling corresponding * lock_full_stripe(). * * Return 0 if we unlock full stripe without problem. * Return <0 for error */ static int unlock_full_stripe(struct btrfs_fs_info *fs_info, u64 bytenr, bool locked) { struct btrfs_block_group_cache *bg_cache; struct btrfs_full_stripe_locks_tree *locks_root; struct full_stripe_lock *fstripe_lock; u64 fstripe_start; bool freeit = false; int ret = 0; /* If we didn't acquire full stripe lock, no need to continue */ if (!locked) return 0; bg_cache = btrfs_lookup_block_group(fs_info, bytenr); if (!bg_cache) { ASSERT(0); return -ENOENT; } if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) goto out; locks_root = &bg_cache->full_stripe_locks_root; fstripe_start = get_full_stripe_logical(bg_cache, bytenr); mutex_lock(&locks_root->lock); fstripe_lock = search_full_stripe_lock(locks_root, fstripe_start); /* Unpaired unlock_full_stripe() detected */ if (!fstripe_lock) { WARN_ON(1); ret = -ENOENT; mutex_unlock(&locks_root->lock); goto out; } if (fstripe_lock->refs == 0) { WARN_ON(1); btrfs_warn(fs_info, "full stripe lock at %llu refcount underflow", fstripe_lock->logical); } else { fstripe_lock->refs--; } if (fstripe_lock->refs == 0) { rb_erase(&fstripe_lock->node, &locks_root->root); freeit = true; } mutex_unlock(&locks_root->lock); mutex_unlock(&fstripe_lock->mutex); if (freeit) kfree(fstripe_lock); out: btrfs_put_block_group(bg_cache); return ret; } static void scrub_free_csums(struct scrub_ctx *sctx) { while (!list_empty(&sctx->csum_list)) { struct btrfs_ordered_sum *sum; sum = list_first_entry(&sctx->csum_list, struct btrfs_ordered_sum, list); list_del(&sum->list); kfree(sum); } } static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx) { int i; if (!sctx) return; /* this can happen when scrub is cancelled */ if (sctx->curr != -1) { struct scrub_bio *sbio = sctx->bios[sctx->curr]; for (i = 0; i < sbio->page_count; i++) { WARN_ON(!sbio->pagev[i]->page); scrub_block_put(sbio->pagev[i]->sblock); } bio_put(sbio->bio); } for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) { struct scrub_bio *sbio = sctx->bios[i]; if (!sbio) break; kfree(sbio); } kfree(sctx->wr_curr_bio); scrub_free_csums(sctx); kfree(sctx); } static void scrub_put_ctx(struct scrub_ctx *sctx) { if (refcount_dec_and_test(&sctx->refs)) scrub_free_ctx(sctx); } static noinline_for_stack struct scrub_ctx *scrub_setup_ctx( struct btrfs_fs_info *fs_info, int is_dev_replace) { struct scrub_ctx *sctx; int i; sctx = kzalloc(sizeof(*sctx), GFP_KERNEL); if (!sctx) goto nomem; refcount_set(&sctx->refs, 1); sctx->is_dev_replace = is_dev_replace; sctx->pages_per_rd_bio = SCRUB_PAGES_PER_RD_BIO; sctx->curr = -1; sctx->fs_info = fs_info; for (i = 0; i < SCRUB_BIOS_PER_SCTX; ++i) { struct scrub_bio *sbio; sbio = kzalloc(sizeof(*sbio), GFP_KERNEL); if (!sbio) goto nomem; sctx->bios[i] = sbio; sbio->index = i; sbio->sctx = sctx; sbio->page_count = 0; btrfs_init_work(&sbio->work, btrfs_scrub_helper, scrub_bio_end_io_worker, NULL, NULL); if (i != SCRUB_BIOS_PER_SCTX - 1) sctx->bios[i]->next_free = i + 1; else sctx->bios[i]->next_free = -1; } sctx->first_free = 0; atomic_set(&sctx->bios_in_flight, 0); atomic_set(&sctx->workers_pending, 0); atomic_set(&sctx->cancel_req, 0); sctx->csum_size = btrfs_super_csum_size(fs_info->super_copy); INIT_LIST_HEAD(&sctx->csum_list); spin_lock_init(&sctx->list_lock); spin_lock_init(&sctx->stat_lock); init_waitqueue_head(&sctx->list_wait); WARN_ON(sctx->wr_curr_bio != NULL); mutex_init(&sctx->wr_lock); sctx->wr_curr_bio = NULL; if (is_dev_replace) { WARN_ON(!fs_info->dev_replace.tgtdev); sctx->pages_per_wr_bio = SCRUB_PAGES_PER_WR_BIO; sctx->wr_tgtdev = fs_info->dev_replace.tgtdev; sctx->flush_all_writes = false; } return sctx; nomem: scrub_free_ctx(sctx); return ERR_PTR(-ENOMEM); } static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root, void *warn_ctx) { u64 isize; u32 nlink; int ret; int i; unsigned nofs_flag; struct extent_buffer *eb; struct btrfs_inode_item *inode_item; struct scrub_warning *swarn = warn_ctx; struct btrfs_fs_info *fs_info = swarn->dev->fs_info; struct inode_fs_paths *ipath = NULL; struct btrfs_root *local_root; struct btrfs_key root_key; struct btrfs_key key; root_key.objectid = root; root_key.type = BTRFS_ROOT_ITEM_KEY; root_key.offset = (u64)-1; local_root = btrfs_read_fs_root_no_name(fs_info, &root_key); if (IS_ERR(local_root)) { ret = PTR_ERR(local_root); goto err; } /* * this makes the path point to (inum INODE_ITEM ioff) */ key.objectid = inum; key.type = BTRFS_INODE_ITEM_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, local_root, &key, swarn->path, 0, 0); if (ret) { btrfs_release_path(swarn->path); goto err; } eb = swarn->path->nodes[0]; inode_item = btrfs_item_ptr(eb, swarn->path->slots[0], struct btrfs_inode_item); isize = btrfs_inode_size(eb, inode_item); nlink = btrfs_inode_nlink(eb, inode_item); btrfs_release_path(swarn->path); /* * init_path might indirectly call vmalloc, or use GFP_KERNEL. Scrub * uses GFP_NOFS in this context, so we keep it consistent but it does * not seem to be strictly necessary. */ nofs_flag = memalloc_nofs_save(); ipath = init_ipath(4096, local_root, swarn->path); memalloc_nofs_restore(nofs_flag); if (IS_ERR(ipath)) { ret = PTR_ERR(ipath); ipath = NULL; goto err; } ret = paths_from_inode(inum, ipath); if (ret < 0) goto err; /* * we deliberately ignore the bit ipath might have been too small to * hold all of the paths here */ for (i = 0; i < ipath->fspath->elem_cnt; ++i) btrfs_warn_in_rcu(fs_info, "%s at logical %llu on dev %s, physical %llu, root %llu, inode %llu, offset %llu, length %llu, links %u (path: %s)", swarn->errstr, swarn->logical, rcu_str_deref(swarn->dev->name), swarn->physical, root, inum, offset, min(isize - offset, (u64)PAGE_SIZE), nlink, (char *)(unsigned long)ipath->fspath->val[i]); free_ipath(ipath); return 0; err: btrfs_warn_in_rcu(fs_info, "%s at logical %llu on dev %s, physical %llu, root %llu, inode %llu, offset %llu: path resolving failed with ret=%d", swarn->errstr, swarn->logical, rcu_str_deref(swarn->dev->name), swarn->physical, root, inum, offset, ret); free_ipath(ipath); return 0; } static void scrub_print_warning(const char *errstr, struct scrub_block *sblock) { struct btrfs_device *dev; struct btrfs_fs_info *fs_info; struct btrfs_path *path; struct btrfs_key found_key; struct extent_buffer *eb; struct btrfs_extent_item *ei; struct scrub_warning swarn; unsigned long ptr = 0; u64 extent_item_pos; u64 flags = 0; u64 ref_root; u32 item_size; u8 ref_level = 0; int ret; WARN_ON(sblock->page_count < 1); dev = sblock->pagev[0]->dev; fs_info = sblock->sctx->fs_info; path = btrfs_alloc_path(); if (!path) return; swarn.physical = sblock->pagev[0]->physical; swarn.logical = sblock->pagev[0]->logical; swarn.errstr = errstr; swarn.dev = NULL; ret = extent_from_logical(fs_info, swarn.logical, path, &found_key, &flags); if (ret < 0) goto out; extent_item_pos = swarn.logical - found_key.objectid; swarn.extent_item_size = found_key.offset; eb = path->nodes[0]; ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item); item_size = btrfs_item_size_nr(eb, path->slots[0]); if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) { do { ret = tree_backref_for_extent(&ptr, eb, &found_key, ei, item_size, &ref_root, &ref_level); btrfs_warn_in_rcu(fs_info, "%s at logical %llu on dev %s, physical %llu: metadata %s (level %d) in tree %llu", errstr, swarn.logical, rcu_str_deref(dev->name), swarn.physical, ref_level ? "node" : "leaf", ret < 0 ? -1 : ref_level, ret < 0 ? -1 : ref_root); } while (ret != 1); btrfs_release_path(path); } else { btrfs_release_path(path); swarn.path = path; swarn.dev = dev; iterate_extent_inodes(fs_info, found_key.objectid, extent_item_pos, 1, scrub_print_warning_inode, &swarn, false); } out: btrfs_free_path(path); } static inline void scrub_get_recover(struct scrub_recover *recover) { refcount_inc(&recover->refs); } static inline void scrub_put_recover(struct btrfs_fs_info *fs_info, struct scrub_recover *recover) { if (refcount_dec_and_test(&recover->refs)) { btrfs_bio_counter_dec(fs_info); btrfs_put_bbio(recover->bbio); kfree(recover); } } /* * scrub_handle_errored_block gets called when either verification of the * pages failed or the bio failed to read, e.g. with EIO. In the latter * case, this function handles all pages in the bio, even though only one * may be bad. * The goal of this function is to repair the errored block by using the * contents of one of the mirrors. */ static int scrub_handle_errored_block(struct scrub_block *sblock_to_check) { struct scrub_ctx *sctx = sblock_to_check->sctx; struct btrfs_device *dev; struct btrfs_fs_info *fs_info; u64 logical; unsigned int failed_mirror_index; unsigned int is_metadata; unsigned int have_csum; struct scrub_block *sblocks_for_recheck; /* holds one for each mirror */ struct scrub_block *sblock_bad; int ret; int mirror_index; int page_num; int success; bool full_stripe_locked; unsigned int nofs_flag; static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL, DEFAULT_RATELIMIT_BURST); BUG_ON(sblock_to_check->page_count < 1); fs_info = sctx->fs_info; if (sblock_to_check->pagev[0]->flags & BTRFS_EXTENT_FLAG_SUPER) { /* * if we find an error in a super block, we just report it. * They will get written with the next transaction commit * anyway */ spin_lock(&sctx->stat_lock); ++sctx->stat.super_errors; spin_unlock(&sctx->stat_lock); return 0; } logical = sblock_to_check->pagev[0]->logical; BUG_ON(sblock_to_check->pagev[0]->mirror_num < 1); failed_mirror_index = sblock_to_check->pagev[0]->mirror_num - 1; is_metadata = !(sblock_to_check->pagev[0]->flags & BTRFS_EXTENT_FLAG_DATA); have_csum = sblock_to_check->pagev[0]->have_csum; dev = sblock_to_check->pagev[0]->dev; /* * We must use GFP_NOFS because the scrub task might be waiting for a * worker task executing this function and in turn a transaction commit * might be waiting the scrub task to pause (which needs to wait for all * the worker tasks to complete before pausing). * We do allocations in the workers through insert_full_stripe_lock() * and scrub_add_page_to_wr_bio(), which happens down the call chain of * this function. */ nofs_flag = memalloc_nofs_save(); /* * For RAID5/6, race can happen for a different device scrub thread. * For data corruption, Parity and Data threads will both try * to recovery the data. * Race can lead to doubly added csum error, or even unrecoverable * error. */ ret = lock_full_stripe(fs_info, logical, &full_stripe_locked); if (ret < 0) { memalloc_nofs_restore(nofs_flag); spin_lock(&sctx->stat_lock); if (ret == -ENOMEM) sctx->stat.malloc_errors++; sctx->stat.read_errors++; sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); return ret; } /* * read all mirrors one after the other. This includes to * re-read the extent or metadata block that failed (that was * the cause that this fixup code is called) another time, * page by page this time in order to know which pages * caused I/O errors and which ones are good (for all mirrors). * It is the goal to handle the situation when more than one * mirror contains I/O errors, but the errors do not * overlap, i.e. the data can be repaired by selecting the * pages from those mirrors without I/O error on the * particular pages. One example (with blocks >= 2 * PAGE_SIZE) * would be that mirror #1 has an I/O error on the first page, * the second page is good, and mirror #2 has an I/O error on * the second page, but the first page is good. * Then the first page of the first mirror can be repaired by * taking the first page of the second mirror, and the * second page of the second mirror can be repaired by * copying the contents of the 2nd page of the 1st mirror. * One more note: if the pages of one mirror contain I/O * errors, the checksum cannot be verified. In order to get * the best data for repairing, the first attempt is to find * a mirror without I/O errors and with a validated checksum. * Only if this is not possible, the pages are picked from * mirrors with I/O errors without considering the checksum. * If the latter is the case, at the end, the checksum of the * repaired area is verified in order to correctly maintain * the statistics. */ sblocks_for_recheck = kcalloc(BTRFS_MAX_MIRRORS, sizeof(*sblocks_for_recheck), GFP_KERNEL); if (!sblocks_for_recheck) { spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; sctx->stat.read_errors++; sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS); goto out; } /* setup the context, map the logical blocks and alloc the pages */ ret = scrub_setup_recheck_block(sblock_to_check, sblocks_for_recheck); if (ret) { spin_lock(&sctx->stat_lock); sctx->stat.read_errors++; sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS); goto out; } BUG_ON(failed_mirror_index >= BTRFS_MAX_MIRRORS); sblock_bad = sblocks_for_recheck + failed_mirror_index; /* build and submit the bios for the failed mirror, check checksums */ scrub_recheck_block(fs_info, sblock_bad, 1); if (!sblock_bad->header_error && !sblock_bad->checksum_error && sblock_bad->no_io_error_seen) { /* * the error disappeared after reading page by page, or * the area was part of a huge bio and other parts of the * bio caused I/O errors, or the block layer merged several * read requests into one and the error is caused by a * different bio (usually one of the two latter cases is * the cause) */ spin_lock(&sctx->stat_lock); sctx->stat.unverified_errors++; sblock_to_check->data_corrected = 1; spin_unlock(&sctx->stat_lock); if (sctx->is_dev_replace) scrub_write_block_to_dev_replace(sblock_bad); goto out; } if (!sblock_bad->no_io_error_seen) { spin_lock(&sctx->stat_lock); sctx->stat.read_errors++; spin_unlock(&sctx->stat_lock); if (__ratelimit(&_rs)) scrub_print_warning("i/o error", sblock_to_check); btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS); } else if (sblock_bad->checksum_error) { spin_lock(&sctx->stat_lock); sctx->stat.csum_errors++; spin_unlock(&sctx->stat_lock); if (__ratelimit(&_rs)) scrub_print_warning("checksum error", sblock_to_check); btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS); } else if (sblock_bad->header_error) { spin_lock(&sctx->stat_lock); sctx->stat.verify_errors++; spin_unlock(&sctx->stat_lock); if (__ratelimit(&_rs)) scrub_print_warning("checksum/header error", sblock_to_check); if (sblock_bad->generation_error) btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_GENERATION_ERRS); else btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS); } if (sctx->readonly) { ASSERT(!sctx->is_dev_replace); goto out; } /* * now build and submit the bios for the other mirrors, check * checksums. * First try to pick the mirror which is completely without I/O * errors and also does not have a checksum error. * If one is found, and if a checksum is present, the full block * that is known to contain an error is rewritten. Afterwards * the block is known to be corrected. * If a mirror is found which is completely correct, and no * checksum is present, only those pages are rewritten that had * an I/O error in the block to be repaired, since it cannot be * determined, which copy of the other pages is better (and it * could happen otherwise that a correct page would be * overwritten by a bad one). */ for (mirror_index = 0; ;mirror_index++) { struct scrub_block *sblock_other; if (mirror_index == failed_mirror_index) continue; /* raid56's mirror can be more than BTRFS_MAX_MIRRORS */ if (!scrub_is_page_on_raid56(sblock_bad->pagev[0])) { if (mirror_index >= BTRFS_MAX_MIRRORS) break; if (!sblocks_for_recheck[mirror_index].page_count) break; sblock_other = sblocks_for_recheck + mirror_index; } else { struct scrub_recover *r = sblock_bad->pagev[0]->recover; int max_allowed = r->bbio->num_stripes - r->bbio->num_tgtdevs; if (mirror_index >= max_allowed) break; if (!sblocks_for_recheck[1].page_count) break; ASSERT(failed_mirror_index == 0); sblock_other = sblocks_for_recheck + 1; sblock_other->pagev[0]->mirror_num = 1 + mirror_index; } /* build and submit the bios, check checksums */ scrub_recheck_block(fs_info, sblock_other, 0); if (!sblock_other->header_error && !sblock_other->checksum_error && sblock_other->no_io_error_seen) { if (sctx->is_dev_replace) { scrub_write_block_to_dev_replace(sblock_other); goto corrected_error; } else { ret = scrub_repair_block_from_good_copy( sblock_bad, sblock_other); if (!ret) goto corrected_error; } } } if (sblock_bad->no_io_error_seen && !sctx->is_dev_replace) goto did_not_correct_error; /* * In case of I/O errors in the area that is supposed to be * repaired, continue by picking good copies of those pages. * Select the good pages from mirrors to rewrite bad pages from * the area to fix. Afterwards verify the checksum of the block * that is supposed to be repaired. This verification step is * only done for the purpose of statistic counting and for the * final scrub report, whether errors remain. * A perfect algorithm could make use of the checksum and try * all possible combinations of pages from the different mirrors * until the checksum verification succeeds. For example, when * the 2nd page of mirror #1 faces I/O errors, and the 2nd page * of mirror #2 is readable but the final checksum test fails, * then the 2nd page of mirror #3 could be tried, whether now * the final checksum succeeds. But this would be a rare * exception and is therefore not implemented. At least it is * avoided that the good copy is overwritten. * A more useful improvement would be to pick the sectors * without I/O error based on sector sizes (512 bytes on legacy * disks) instead of on PAGE_SIZE. Then maybe 512 byte of one * mirror could be repaired by taking 512 byte of a different * mirror, even if other 512 byte sectors in the same PAGE_SIZE * area are unreadable. */ success = 1; for (page_num = 0; page_num < sblock_bad->page_count; page_num++) { struct scrub_page *page_bad = sblock_bad->pagev[page_num]; struct scrub_block *sblock_other = NULL; /* skip no-io-error page in scrub */ if (!page_bad->io_error && !sctx->is_dev_replace) continue; if (scrub_is_page_on_raid56(sblock_bad->pagev[0])) { /* * In case of dev replace, if raid56 rebuild process * didn't work out correct data, then copy the content * in sblock_bad to make sure target device is identical * to source device, instead of writing garbage data in * sblock_for_recheck array to target device. */ sblock_other = NULL; } else if (page_bad->io_error) { /* try to find no-io-error page in mirrors */ for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS && sblocks_for_recheck[mirror_index].page_count > 0; mirror_index++) { if (!sblocks_for_recheck[mirror_index]. pagev[page_num]->io_error) { sblock_other = sblocks_for_recheck + mirror_index; break; } } if (!sblock_other) success = 0; } if (sctx->is_dev_replace) { /* * did not find a mirror to fetch the page * from. scrub_write_page_to_dev_replace() * handles this case (page->io_error), by * filling the block with zeros before * submitting the write request */ if (!sblock_other) sblock_other = sblock_bad; if (scrub_write_page_to_dev_replace(sblock_other, page_num) != 0) { atomic64_inc( &fs_info->dev_replace.num_write_errors); success = 0; } } else if (sblock_other) { ret = scrub_repair_page_from_good_copy(sblock_bad, sblock_other, page_num, 0); if (0 == ret) page_bad->io_error = 0; else success = 0; } } if (success && !sctx->is_dev_replace) { if (is_metadata || have_csum) { /* * need to verify the checksum now that all * sectors on disk are repaired (the write * request for data to be repaired is on its way). * Just be lazy and use scrub_recheck_block() * which re-reads the data before the checksum * is verified, but most likely the data comes out * of the page cache. */ scrub_recheck_block(fs_info, sblock_bad, 1); if (!sblock_bad->header_error && !sblock_bad->checksum_error && sblock_bad->no_io_error_seen) goto corrected_error; else goto did_not_correct_error; } else { corrected_error: spin_lock(&sctx->stat_lock); sctx->stat.corrected_errors++; sblock_to_check->data_corrected = 1; spin_unlock(&sctx->stat_lock); btrfs_err_rl_in_rcu(fs_info, "fixed up error at logical %llu on dev %s", logical, rcu_str_deref(dev->name)); } } else { did_not_correct_error: spin_lock(&sctx->stat_lock); sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); btrfs_err_rl_in_rcu(fs_info, "unable to fixup (regular) error at logical %llu on dev %s", logical, rcu_str_deref(dev->name)); } out: if (sblocks_for_recheck) { for (mirror_index = 0; mirror_index < BTRFS_MAX_MIRRORS; mirror_index++) { struct scrub_block *sblock = sblocks_for_recheck + mirror_index; struct scrub_recover *recover; int page_index; for (page_index = 0; page_index < sblock->page_count; page_index++) { sblock->pagev[page_index]->sblock = NULL; recover = sblock->pagev[page_index]->recover; if (recover) { scrub_put_recover(fs_info, recover); sblock->pagev[page_index]->recover = NULL; } scrub_page_put(sblock->pagev[page_index]); } } kfree(sblocks_for_recheck); } ret = unlock_full_stripe(fs_info, logical, full_stripe_locked); memalloc_nofs_restore(nofs_flag); if (ret < 0) return ret; return 0; } static inline int scrub_nr_raid_mirrors(struct btrfs_bio *bbio) { if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID5) return 2; else if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID6) return 3; else return (int)bbio->num_stripes; } static inline void scrub_stripe_index_and_offset(u64 logical, u64 map_type, u64 *raid_map, u64 mapped_length, int nstripes, int mirror, int *stripe_index, u64 *stripe_offset) { int i; if (map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) { /* RAID5/6 */ for (i = 0; i < nstripes; i++) { if (raid_map[i] == RAID6_Q_STRIPE || raid_map[i] == RAID5_P_STRIPE) continue; if (logical >= raid_map[i] && logical < raid_map[i] + mapped_length) break; } *stripe_index = i; *stripe_offset = logical - raid_map[i]; } else { /* The other RAID type */ *stripe_index = mirror; *stripe_offset = 0; } } static int scrub_setup_recheck_block(struct scrub_block *original_sblock, struct scrub_block *sblocks_for_recheck) { struct scrub_ctx *sctx = original_sblock->sctx; struct btrfs_fs_info *fs_info = sctx->fs_info; u64 length = original_sblock->page_count * PAGE_SIZE; u64 logical = original_sblock->pagev[0]->logical; u64 generation = original_sblock->pagev[0]->generation; u64 flags = original_sblock->pagev[0]->flags; u64 have_csum = original_sblock->pagev[0]->have_csum; struct scrub_recover *recover; struct btrfs_bio *bbio; u64 sublen; u64 mapped_length; u64 stripe_offset; int stripe_index; int page_index = 0; int mirror_index; int nmirrors; int ret; /* * note: the two members refs and outstanding_pages * are not used (and not set) in the blocks that are used for * the recheck procedure */ while (length > 0) { sublen = min_t(u64, length, PAGE_SIZE); mapped_length = sublen; bbio = NULL; /* * with a length of PAGE_SIZE, each returned stripe * represents one mirror */ btrfs_bio_counter_inc_blocked(fs_info); ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical, &mapped_length, &bbio); if (ret || !bbio || mapped_length < sublen) { btrfs_put_bbio(bbio); btrfs_bio_counter_dec(fs_info); return -EIO; } recover = kzalloc(sizeof(struct scrub_recover), GFP_NOFS); if (!recover) { btrfs_put_bbio(bbio); btrfs_bio_counter_dec(fs_info); return -ENOMEM; } refcount_set(&recover->refs, 1); recover->bbio = bbio; recover->map_length = mapped_length; BUG_ON(page_index >= SCRUB_MAX_PAGES_PER_BLOCK); nmirrors = min(scrub_nr_raid_mirrors(bbio), BTRFS_MAX_MIRRORS); for (mirror_index = 0; mirror_index < nmirrors; mirror_index++) { struct scrub_block *sblock; struct scrub_page *page; sblock = sblocks_for_recheck + mirror_index; sblock->sctx = sctx; page = kzalloc(sizeof(*page), GFP_NOFS); if (!page) { leave_nomem: spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); scrub_put_recover(fs_info, recover); return -ENOMEM; } scrub_page_get(page); sblock->pagev[page_index] = page; page->sblock = sblock; page->flags = flags; page->generation = generation; page->logical = logical; page->have_csum = have_csum; if (have_csum) memcpy(page->csum, original_sblock->pagev[0]->csum, sctx->csum_size); scrub_stripe_index_and_offset(logical, bbio->map_type, bbio->raid_map, mapped_length, bbio->num_stripes - bbio->num_tgtdevs, mirror_index, &stripe_index, &stripe_offset); page->physical = bbio->stripes[stripe_index].physical + stripe_offset; page->dev = bbio->stripes[stripe_index].dev; BUG_ON(page_index >= original_sblock->page_count); page->physical_for_dev_replace = original_sblock->pagev[page_index]-> physical_for_dev_replace; /* for missing devices, dev->bdev is NULL */ page->mirror_num = mirror_index + 1; sblock->page_count++; page->page = alloc_page(GFP_NOFS); if (!page->page) goto leave_nomem; scrub_get_recover(recover); page->recover = recover; } scrub_put_recover(fs_info, recover); length -= sublen; logical += sublen; page_index++; } return 0; } static void scrub_bio_wait_endio(struct bio *bio) { complete(bio->bi_private); } static int scrub_submit_raid56_bio_wait(struct btrfs_fs_info *fs_info, struct bio *bio, struct scrub_page *page) { DECLARE_COMPLETION_ONSTACK(done); int ret; int mirror_num; bio->bi_iter.bi_sector = page->logical >> 9; bio->bi_private = &done; bio->bi_end_io = scrub_bio_wait_endio; mirror_num = page->sblock->pagev[0]->mirror_num; ret = raid56_parity_recover(fs_info, bio, page->recover->bbio, page->recover->map_length, mirror_num, 0); if (ret) return ret; wait_for_completion_io(&done); return blk_status_to_errno(bio->bi_status); } static void scrub_recheck_block_on_raid56(struct btrfs_fs_info *fs_info, struct scrub_block *sblock) { struct scrub_page *first_page = sblock->pagev[0]; struct bio *bio; int page_num; /* All pages in sblock belong to the same stripe on the same device. */ ASSERT(first_page->dev); if (!first_page->dev->bdev) goto out; bio = btrfs_io_bio_alloc(BIO_MAX_PAGES); bio_set_dev(bio, first_page->dev->bdev); for (page_num = 0; page_num < sblock->page_count; page_num++) { struct scrub_page *page = sblock->pagev[page_num]; WARN_ON(!page->page); bio_add_page(bio, page->page, PAGE_SIZE, 0); } if (scrub_submit_raid56_bio_wait(fs_info, bio, first_page)) { bio_put(bio); goto out; } bio_put(bio); scrub_recheck_block_checksum(sblock); return; out: for (page_num = 0; page_num < sblock->page_count; page_num++) sblock->pagev[page_num]->io_error = 1; sblock->no_io_error_seen = 0; } /* * this function will check the on disk data for checksum errors, header * errors and read I/O errors. If any I/O errors happen, the exact pages * which are errored are marked as being bad. The goal is to enable scrub * to take those pages that are not errored from all the mirrors so that * the pages that are errored in the just handled mirror can be repaired. */ static void scrub_recheck_block(struct btrfs_fs_info *fs_info, struct scrub_block *sblock, int retry_failed_mirror) { int page_num; sblock->no_io_error_seen = 1; /* short cut for raid56 */ if (!retry_failed_mirror && scrub_is_page_on_raid56(sblock->pagev[0])) return scrub_recheck_block_on_raid56(fs_info, sblock); for (page_num = 0; page_num < sblock->page_count; page_num++) { struct bio *bio; struct scrub_page *page = sblock->pagev[page_num]; if (page->dev->bdev == NULL) { page->io_error = 1; sblock->no_io_error_seen = 0; continue; } WARN_ON(!page->page); bio = btrfs_io_bio_alloc(1); bio_set_dev(bio, page->dev->bdev); bio_add_page(bio, page->page, PAGE_SIZE, 0); bio->bi_iter.bi_sector = page->physical >> 9; bio->bi_opf = REQ_OP_READ; if (btrfsic_submit_bio_wait(bio)) { page->io_error = 1; sblock->no_io_error_seen = 0; } bio_put(bio); } if (sblock->no_io_error_seen) scrub_recheck_block_checksum(sblock); } static inline int scrub_check_fsid(u8 fsid[], struct scrub_page *spage) { struct btrfs_fs_devices *fs_devices = spage->dev->fs_devices; int ret; ret = memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE); return !ret; } static void scrub_recheck_block_checksum(struct scrub_block *sblock) { sblock->header_error = 0; sblock->checksum_error = 0; sblock->generation_error = 0; if (sblock->pagev[0]->flags & BTRFS_EXTENT_FLAG_DATA) scrub_checksum_data(sblock); else scrub_checksum_tree_block(sblock); } static int scrub_repair_block_from_good_copy(struct scrub_block *sblock_bad, struct scrub_block *sblock_good) { int page_num; int ret = 0; for (page_num = 0; page_num < sblock_bad->page_count; page_num++) { int ret_sub; ret_sub = scrub_repair_page_from_good_copy(sblock_bad, sblock_good, page_num, 1); if (ret_sub) ret = ret_sub; } return ret; } static int scrub_repair_page_from_good_copy(struct scrub_block *sblock_bad, struct scrub_block *sblock_good, int page_num, int force_write) { struct scrub_page *page_bad = sblock_bad->pagev[page_num]; struct scrub_page *page_good = sblock_good->pagev[page_num]; struct btrfs_fs_info *fs_info = sblock_bad->sctx->fs_info; BUG_ON(page_bad->page == NULL); BUG_ON(page_good->page == NULL); if (force_write || sblock_bad->header_error || sblock_bad->checksum_error || page_bad->io_error) { struct bio *bio; int ret; if (!page_bad->dev->bdev) { btrfs_warn_rl(fs_info, "scrub_repair_page_from_good_copy(bdev == NULL) is unexpected"); return -EIO; } bio = btrfs_io_bio_alloc(1); bio_set_dev(bio, page_bad->dev->bdev); bio->bi_iter.bi_sector = page_bad->physical >> 9; bio->bi_opf = REQ_OP_WRITE; ret = bio_add_page(bio, page_good->page, PAGE_SIZE, 0); if (PAGE_SIZE != ret) { bio_put(bio); return -EIO; } if (btrfsic_submit_bio_wait(bio)) { btrfs_dev_stat_inc_and_print(page_bad->dev, BTRFS_DEV_STAT_WRITE_ERRS); atomic64_inc(&fs_info->dev_replace.num_write_errors); bio_put(bio); return -EIO; } bio_put(bio); } return 0; } static void scrub_write_block_to_dev_replace(struct scrub_block *sblock) { struct btrfs_fs_info *fs_info = sblock->sctx->fs_info; int page_num; /* * This block is used for the check of the parity on the source device, * so the data needn't be written into the destination device. */ if (sblock->sparity) return; for (page_num = 0; page_num < sblock->page_count; page_num++) { int ret; ret = scrub_write_page_to_dev_replace(sblock, page_num); if (ret) atomic64_inc(&fs_info->dev_replace.num_write_errors); } } static int scrub_write_page_to_dev_replace(struct scrub_block *sblock, int page_num) { struct scrub_page *spage = sblock->pagev[page_num]; BUG_ON(spage->page == NULL); if (spage->io_error) { void *mapped_buffer = kmap_atomic(spage->page); clear_page(mapped_buffer); flush_dcache_page(spage->page); kunmap_atomic(mapped_buffer); } return scrub_add_page_to_wr_bio(sblock->sctx, spage); } static int scrub_add_page_to_wr_bio(struct scrub_ctx *sctx, struct scrub_page *spage) { struct scrub_bio *sbio; int ret; mutex_lock(&sctx->wr_lock); again: if (!sctx->wr_curr_bio) { sctx->wr_curr_bio = kzalloc(sizeof(*sctx->wr_curr_bio), GFP_KERNEL); if (!sctx->wr_curr_bio) { mutex_unlock(&sctx->wr_lock); return -ENOMEM; } sctx->wr_curr_bio->sctx = sctx; sctx->wr_curr_bio->page_count = 0; } sbio = sctx->wr_curr_bio; if (sbio->page_count == 0) { struct bio *bio; sbio->physical = spage->physical_for_dev_replace; sbio->logical = spage->logical; sbio->dev = sctx->wr_tgtdev; bio = sbio->bio; if (!bio) { bio = btrfs_io_bio_alloc(sctx->pages_per_wr_bio); sbio->bio = bio; } bio->bi_private = sbio; bio->bi_end_io = scrub_wr_bio_end_io; bio_set_dev(bio, sbio->dev->bdev); bio->bi_iter.bi_sector = sbio->physical >> 9; bio->bi_opf = REQ_OP_WRITE; sbio->status = 0; } else if (sbio->physical + sbio->page_count * PAGE_SIZE != spage->physical_for_dev_replace || sbio->logical + sbio->page_count * PAGE_SIZE != spage->logical) { scrub_wr_submit(sctx); goto again; } ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0); if (ret != PAGE_SIZE) { if (sbio->page_count < 1) { bio_put(sbio->bio); sbio->bio = NULL; mutex_unlock(&sctx->wr_lock); return -EIO; } scrub_wr_submit(sctx); goto again; } sbio->pagev[sbio->page_count] = spage; scrub_page_get(spage); sbio->page_count++; if (sbio->page_count == sctx->pages_per_wr_bio) scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); return 0; } static void scrub_wr_submit(struct scrub_ctx *sctx) { struct scrub_bio *sbio; if (!sctx->wr_curr_bio) return; sbio = sctx->wr_curr_bio; sctx->wr_curr_bio = NULL; WARN_ON(!sbio->bio->bi_disk); scrub_pending_bio_inc(sctx); /* process all writes in a single worker thread. Then the block layer * orders the requests before sending them to the driver which * doubled the write performance on spinning disks when measured * with Linux 3.5 */ btrfsic_submit_bio(sbio->bio); } static void scrub_wr_bio_end_io(struct bio *bio) { struct scrub_bio *sbio = bio->bi_private; struct btrfs_fs_info *fs_info = sbio->dev->fs_info; sbio->status = bio->bi_status; sbio->bio = bio; btrfs_init_work(&sbio->work, btrfs_scrubwrc_helper, scrub_wr_bio_end_io_worker, NULL, NULL); btrfs_queue_work(fs_info->scrub_wr_completion_workers, &sbio->work); } static void scrub_wr_bio_end_io_worker(struct btrfs_work *work) { struct scrub_bio *sbio = container_of(work, struct scrub_bio, work); struct scrub_ctx *sctx = sbio->sctx; int i; WARN_ON(sbio->page_count > SCRUB_PAGES_PER_WR_BIO); if (sbio->status) { struct btrfs_dev_replace *dev_replace = &sbio->sctx->fs_info->dev_replace; for (i = 0; i < sbio->page_count; i++) { struct scrub_page *spage = sbio->pagev[i]; spage->io_error = 1; atomic64_inc(&dev_replace->num_write_errors); } } for (i = 0; i < sbio->page_count; i++) scrub_page_put(sbio->pagev[i]); bio_put(sbio->bio); kfree(sbio); scrub_pending_bio_dec(sctx); } static int scrub_checksum(struct scrub_block *sblock) { u64 flags; int ret; /* * No need to initialize these stats currently, * because this function only use return value * instead of these stats value. * * Todo: * always use stats */ sblock->header_error = 0; sblock->generation_error = 0; sblock->checksum_error = 0; WARN_ON(sblock->page_count < 1); flags = sblock->pagev[0]->flags; ret = 0; if (flags & BTRFS_EXTENT_FLAG_DATA) ret = scrub_checksum_data(sblock); else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) ret = scrub_checksum_tree_block(sblock); else if (flags & BTRFS_EXTENT_FLAG_SUPER) (void)scrub_checksum_super(sblock); else WARN_ON(1); if (ret) scrub_handle_errored_block(sblock); return ret; } static int scrub_checksum_data(struct scrub_block *sblock) { struct scrub_ctx *sctx = sblock->sctx; u8 csum[BTRFS_CSUM_SIZE]; u8 *on_disk_csum; struct page *page; void *buffer; u32 crc = ~(u32)0; u64 len; int index; BUG_ON(sblock->page_count < 1); if (!sblock->pagev[0]->have_csum) return 0; on_disk_csum = sblock->pagev[0]->csum; page = sblock->pagev[0]->page; buffer = kmap_atomic(page); len = sctx->fs_info->sectorsize; index = 0; for (;;) { u64 l = min_t(u64, len, PAGE_SIZE); crc = btrfs_csum_data(buffer, crc, l); kunmap_atomic(buffer); len -= l; if (len == 0) break; index++; BUG_ON(index >= sblock->page_count); BUG_ON(!sblock->pagev[index]->page); page = sblock->pagev[index]->page; buffer = kmap_atomic(page); } btrfs_csum_final(crc, csum); if (memcmp(csum, on_disk_csum, sctx->csum_size)) sblock->checksum_error = 1; return sblock->checksum_error; } static int scrub_checksum_tree_block(struct scrub_block *sblock) { struct scrub_ctx *sctx = sblock->sctx; struct btrfs_header *h; struct btrfs_fs_info *fs_info = sctx->fs_info; u8 calculated_csum[BTRFS_CSUM_SIZE]; u8 on_disk_csum[BTRFS_CSUM_SIZE]; struct page *page; void *mapped_buffer; u64 mapped_size; void *p; u32 crc = ~(u32)0; u64 len; int index; BUG_ON(sblock->page_count < 1); page = sblock->pagev[0]->page; mapped_buffer = kmap_atomic(page); h = (struct btrfs_header *)mapped_buffer; memcpy(on_disk_csum, h->csum, sctx->csum_size); /* * we don't use the getter functions here, as we * a) don't have an extent buffer and * b) the page is already kmapped */ if (sblock->pagev[0]->logical != btrfs_stack_header_bytenr(h)) sblock->header_error = 1; if (sblock->pagev[0]->generation != btrfs_stack_header_generation(h)) { sblock->header_error = 1; sblock->generation_error = 1; } if (!scrub_check_fsid(h->fsid, sblock->pagev[0])) sblock->header_error = 1; if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid, BTRFS_UUID_SIZE)) sblock->header_error = 1; len = sctx->fs_info->nodesize - BTRFS_CSUM_SIZE; mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE; p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE; index = 0; for (;;) { u64 l = min_t(u64, len, mapped_size); crc = btrfs_csum_data(p, crc, l); kunmap_atomic(mapped_buffer); len -= l; if (len == 0) break; index++; BUG_ON(index >= sblock->page_count); BUG_ON(!sblock->pagev[index]->page); page = sblock->pagev[index]->page; mapped_buffer = kmap_atomic(page); mapped_size = PAGE_SIZE; p = mapped_buffer; } btrfs_csum_final(crc, calculated_csum); if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size)) sblock->checksum_error = 1; return sblock->header_error || sblock->checksum_error; } static int scrub_checksum_super(struct scrub_block *sblock) { struct btrfs_super_block *s; struct scrub_ctx *sctx = sblock->sctx; u8 calculated_csum[BTRFS_CSUM_SIZE]; u8 on_disk_csum[BTRFS_CSUM_SIZE]; struct page *page; void *mapped_buffer; u64 mapped_size; void *p; u32 crc = ~(u32)0; int fail_gen = 0; int fail_cor = 0; u64 len; int index; BUG_ON(sblock->page_count < 1); page = sblock->pagev[0]->page; mapped_buffer = kmap_atomic(page); s = (struct btrfs_super_block *)mapped_buffer; memcpy(on_disk_csum, s->csum, sctx->csum_size); if (sblock->pagev[0]->logical != btrfs_super_bytenr(s)) ++fail_cor; if (sblock->pagev[0]->generation != btrfs_super_generation(s)) ++fail_gen; if (!scrub_check_fsid(s->fsid, sblock->pagev[0])) ++fail_cor; len = BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE; mapped_size = PAGE_SIZE - BTRFS_CSUM_SIZE; p = ((u8 *)mapped_buffer) + BTRFS_CSUM_SIZE; index = 0; for (;;) { u64 l = min_t(u64, len, mapped_size); crc = btrfs_csum_data(p, crc, l); kunmap_atomic(mapped_buffer); len -= l; if (len == 0) break; index++; BUG_ON(index >= sblock->page_count); BUG_ON(!sblock->pagev[index]->page); page = sblock->pagev[index]->page; mapped_buffer = kmap_atomic(page); mapped_size = PAGE_SIZE; p = mapped_buffer; } btrfs_csum_final(crc, calculated_csum); if (memcmp(calculated_csum, on_disk_csum, sctx->csum_size)) ++fail_cor; if (fail_cor + fail_gen) { /* * if we find an error in a super block, we just report it. * They will get written with the next transaction commit * anyway */ spin_lock(&sctx->stat_lock); ++sctx->stat.super_errors; spin_unlock(&sctx->stat_lock); if (fail_cor) btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev, BTRFS_DEV_STAT_CORRUPTION_ERRS); else btrfs_dev_stat_inc_and_print(sblock->pagev[0]->dev, BTRFS_DEV_STAT_GENERATION_ERRS); } return fail_cor + fail_gen; } static void scrub_block_get(struct scrub_block *sblock) { refcount_inc(&sblock->refs); } static void scrub_block_put(struct scrub_block *sblock) { if (refcount_dec_and_test(&sblock->refs)) { int i; if (sblock->sparity) scrub_parity_put(sblock->sparity); for (i = 0; i < sblock->page_count; i++) scrub_page_put(sblock->pagev[i]); kfree(sblock); } } static void scrub_page_get(struct scrub_page *spage) { atomic_inc(&spage->refs); } static void scrub_page_put(struct scrub_page *spage) { if (atomic_dec_and_test(&spage->refs)) { if (spage->page) __free_page(spage->page); kfree(spage); } } static void scrub_submit(struct scrub_ctx *sctx) { struct scrub_bio *sbio; if (sctx->curr == -1) return; sbio = sctx->bios[sctx->curr]; sctx->curr = -1; scrub_pending_bio_inc(sctx); btrfsic_submit_bio(sbio->bio); } static int scrub_add_page_to_rd_bio(struct scrub_ctx *sctx, struct scrub_page *spage) { struct scrub_block *sblock = spage->sblock; struct scrub_bio *sbio; int ret; again: /* * grab a fresh bio or wait for one to become available */ while (sctx->curr == -1) { spin_lock(&sctx->list_lock); sctx->curr = sctx->first_free; if (sctx->curr != -1) { sctx->first_free = sctx->bios[sctx->curr]->next_free; sctx->bios[sctx->curr]->next_free = -1; sctx->bios[sctx->curr]->page_count = 0; spin_unlock(&sctx->list_lock); } else { spin_unlock(&sctx->list_lock); wait_event(sctx->list_wait, sctx->first_free != -1); } } sbio = sctx->bios[sctx->curr]; if (sbio->page_count == 0) { struct bio *bio; sbio->physical = spage->physical; sbio->logical = spage->logical; sbio->dev = spage->dev; bio = sbio->bio; if (!bio) { bio = btrfs_io_bio_alloc(sctx->pages_per_rd_bio); sbio->bio = bio; } bio->bi_private = sbio; bio->bi_end_io = scrub_bio_end_io; bio_set_dev(bio, sbio->dev->bdev); bio->bi_iter.bi_sector = sbio->physical >> 9; bio->bi_opf = REQ_OP_READ; sbio->status = 0; } else if (sbio->physical + sbio->page_count * PAGE_SIZE != spage->physical || sbio->logical + sbio->page_count * PAGE_SIZE != spage->logical || sbio->dev != spage->dev) { scrub_submit(sctx); goto again; } sbio->pagev[sbio->page_count] = spage; ret = bio_add_page(sbio->bio, spage->page, PAGE_SIZE, 0); if (ret != PAGE_SIZE) { if (sbio->page_count < 1) { bio_put(sbio->bio); sbio->bio = NULL; return -EIO; } scrub_submit(sctx); goto again; } scrub_block_get(sblock); /* one for the page added to the bio */ atomic_inc(&sblock->outstanding_pages); sbio->page_count++; if (sbio->page_count == sctx->pages_per_rd_bio) scrub_submit(sctx); return 0; } static void scrub_missing_raid56_end_io(struct bio *bio) { struct scrub_block *sblock = bio->bi_private; struct btrfs_fs_info *fs_info = sblock->sctx->fs_info; if (bio->bi_status) sblock->no_io_error_seen = 0; bio_put(bio); btrfs_queue_work(fs_info->scrub_workers, &sblock->work); } static void scrub_missing_raid56_worker(struct btrfs_work *work) { struct scrub_block *sblock = container_of(work, struct scrub_block, work); struct scrub_ctx *sctx = sblock->sctx; struct btrfs_fs_info *fs_info = sctx->fs_info; u64 logical; struct btrfs_device *dev; logical = sblock->pagev[0]->logical; dev = sblock->pagev[0]->dev; if (sblock->no_io_error_seen) scrub_recheck_block_checksum(sblock); if (!sblock->no_io_error_seen) { spin_lock(&sctx->stat_lock); sctx->stat.read_errors++; spin_unlock(&sctx->stat_lock); btrfs_err_rl_in_rcu(fs_info, "IO error rebuilding logical %llu for dev %s", logical, rcu_str_deref(dev->name)); } else if (sblock->header_error || sblock->checksum_error) { spin_lock(&sctx->stat_lock); sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); btrfs_err_rl_in_rcu(fs_info, "failed to rebuild valid logical %llu for dev %s", logical, rcu_str_deref(dev->name)); } else { scrub_write_block_to_dev_replace(sblock); } scrub_block_put(sblock); if (sctx->is_dev_replace && sctx->flush_all_writes) { mutex_lock(&sctx->wr_lock); scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); } scrub_pending_bio_dec(sctx); } static void scrub_missing_raid56_pages(struct scrub_block *sblock) { struct scrub_ctx *sctx = sblock->sctx; struct btrfs_fs_info *fs_info = sctx->fs_info; u64 length = sblock->page_count * PAGE_SIZE; u64 logical = sblock->pagev[0]->logical; struct btrfs_bio *bbio = NULL; struct bio *bio; struct btrfs_raid_bio *rbio; int ret; int i; btrfs_bio_counter_inc_blocked(fs_info); ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical, &length, &bbio); if (ret || !bbio || !bbio->raid_map) goto bbio_out; if (WARN_ON(!sctx->is_dev_replace || !(bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK))) { /* * We shouldn't be scrubbing a missing device. Even for dev * replace, we should only get here for RAID 5/6. We either * managed to mount something with no mirrors remaining or * there's a bug in scrub_remap_extent()/btrfs_map_block(). */ goto bbio_out; } bio = btrfs_io_bio_alloc(0); bio->bi_iter.bi_sector = logical >> 9; bio->bi_private = sblock; bio->bi_end_io = scrub_missing_raid56_end_io; rbio = raid56_alloc_missing_rbio(fs_info, bio, bbio, length); if (!rbio) goto rbio_out; for (i = 0; i < sblock->page_count; i++) { struct scrub_page *spage = sblock->pagev[i]; raid56_add_scrub_pages(rbio, spage->page, spage->logical); } btrfs_init_work(&sblock->work, btrfs_scrub_helper, scrub_missing_raid56_worker, NULL, NULL); scrub_block_get(sblock); scrub_pending_bio_inc(sctx); raid56_submit_missing_rbio(rbio); return; rbio_out: bio_put(bio); bbio_out: btrfs_bio_counter_dec(fs_info); btrfs_put_bbio(bbio); spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); } static int scrub_pages(struct scrub_ctx *sctx, u64 logical, u64 len, u64 physical, struct btrfs_device *dev, u64 flags, u64 gen, int mirror_num, u8 *csum, int force, u64 physical_for_dev_replace) { struct scrub_block *sblock; int index; sblock = kzalloc(sizeof(*sblock), GFP_KERNEL); if (!sblock) { spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); return -ENOMEM; } /* one ref inside this function, plus one for each page added to * a bio later on */ refcount_set(&sblock->refs, 1); sblock->sctx = sctx; sblock->no_io_error_seen = 1; for (index = 0; len > 0; index++) { struct scrub_page *spage; u64 l = min_t(u64, len, PAGE_SIZE); spage = kzalloc(sizeof(*spage), GFP_KERNEL); if (!spage) { leave_nomem: spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); scrub_block_put(sblock); return -ENOMEM; } BUG_ON(index >= SCRUB_MAX_PAGES_PER_BLOCK); scrub_page_get(spage); sblock->pagev[index] = spage; spage->sblock = sblock; spage->dev = dev; spage->flags = flags; spage->generation = gen; spage->logical = logical; spage->physical = physical; spage->physical_for_dev_replace = physical_for_dev_replace; spage->mirror_num = mirror_num; if (csum) { spage->have_csum = 1; memcpy(spage->csum, csum, sctx->csum_size); } else { spage->have_csum = 0; } sblock->page_count++; spage->page = alloc_page(GFP_KERNEL); if (!spage->page) goto leave_nomem; len -= l; logical += l; physical += l; physical_for_dev_replace += l; } WARN_ON(sblock->page_count == 0); if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) { /* * This case should only be hit for RAID 5/6 device replace. See * the comment in scrub_missing_raid56_pages() for details. */ scrub_missing_raid56_pages(sblock); } else { for (index = 0; index < sblock->page_count; index++) { struct scrub_page *spage = sblock->pagev[index]; int ret; ret = scrub_add_page_to_rd_bio(sctx, spage); if (ret) { scrub_block_put(sblock); return ret; } } if (force) scrub_submit(sctx); } /* last one frees, either here or in bio completion for last page */ scrub_block_put(sblock); return 0; } static void scrub_bio_end_io(struct bio *bio) { struct scrub_bio *sbio = bio->bi_private; struct btrfs_fs_info *fs_info = sbio->dev->fs_info; sbio->status = bio->bi_status; sbio->bio = bio; btrfs_queue_work(fs_info->scrub_workers, &sbio->work); } static void scrub_bio_end_io_worker(struct btrfs_work *work) { struct scrub_bio *sbio = container_of(work, struct scrub_bio, work); struct scrub_ctx *sctx = sbio->sctx; int i; BUG_ON(sbio->page_count > SCRUB_PAGES_PER_RD_BIO); if (sbio->status) { for (i = 0; i < sbio->page_count; i++) { struct scrub_page *spage = sbio->pagev[i]; spage->io_error = 1; spage->sblock->no_io_error_seen = 0; } } /* now complete the scrub_block items that have all pages completed */ for (i = 0; i < sbio->page_count; i++) { struct scrub_page *spage = sbio->pagev[i]; struct scrub_block *sblock = spage->sblock; if (atomic_dec_and_test(&sblock->outstanding_pages)) scrub_block_complete(sblock); scrub_block_put(sblock); } bio_put(sbio->bio); sbio->bio = NULL; spin_lock(&sctx->list_lock); sbio->next_free = sctx->first_free; sctx->first_free = sbio->index; spin_unlock(&sctx->list_lock); if (sctx->is_dev_replace && sctx->flush_all_writes) { mutex_lock(&sctx->wr_lock); scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); } scrub_pending_bio_dec(sctx); } static inline void __scrub_mark_bitmap(struct scrub_parity *sparity, unsigned long *bitmap, u64 start, u64 len) { u64 offset; u64 nsectors64; u32 nsectors; int sectorsize = sparity->sctx->fs_info->sectorsize; if (len >= sparity->stripe_len) { bitmap_set(bitmap, 0, sparity->nsectors); return; } start -= sparity->logic_start; start = div64_u64_rem(start, sparity->stripe_len, &offset); offset = div_u64(offset, sectorsize); nsectors64 = div_u64(len, sectorsize); ASSERT(nsectors64 < UINT_MAX); nsectors = (u32)nsectors64; if (offset + nsectors <= sparity->nsectors) { bitmap_set(bitmap, offset, nsectors); return; } bitmap_set(bitmap, offset, sparity->nsectors - offset); bitmap_set(bitmap, 0, nsectors - (sparity->nsectors - offset)); } static inline void scrub_parity_mark_sectors_error(struct scrub_parity *sparity, u64 start, u64 len) { __scrub_mark_bitmap(sparity, sparity->ebitmap, start, len); } static inline void scrub_parity_mark_sectors_data(struct scrub_parity *sparity, u64 start, u64 len) { __scrub_mark_bitmap(sparity, sparity->dbitmap, start, len); } static void scrub_block_complete(struct scrub_block *sblock) { int corrupted = 0; if (!sblock->no_io_error_seen) { corrupted = 1; scrub_handle_errored_block(sblock); } else { /* * if has checksum error, write via repair mechanism in * dev replace case, otherwise write here in dev replace * case. */ corrupted = scrub_checksum(sblock); if (!corrupted && sblock->sctx->is_dev_replace) scrub_write_block_to_dev_replace(sblock); } if (sblock->sparity && corrupted && !sblock->data_corrected) { u64 start = sblock->pagev[0]->logical; u64 end = sblock->pagev[sblock->page_count - 1]->logical + PAGE_SIZE; scrub_parity_mark_sectors_error(sblock->sparity, start, end - start); } } static int scrub_find_csum(struct scrub_ctx *sctx, u64 logical, u8 *csum) { struct btrfs_ordered_sum *sum = NULL; unsigned long index; unsigned long num_sectors; while (!list_empty(&sctx->csum_list)) { sum = list_first_entry(&sctx->csum_list, struct btrfs_ordered_sum, list); if (sum->bytenr > logical) return 0; if (sum->bytenr + sum->len > logical) break; ++sctx->stat.csum_discards; list_del(&sum->list); kfree(sum); sum = NULL; } if (!sum) return 0; index = div_u64(logical - sum->bytenr, sctx->fs_info->sectorsize); ASSERT(index < UINT_MAX); num_sectors = sum->len / sctx->fs_info->sectorsize; memcpy(csum, sum->sums + index, sctx->csum_size); if (index == num_sectors - 1) { list_del(&sum->list); kfree(sum); } return 1; } /* scrub extent tries to collect up to 64 kB for each bio */ static int scrub_extent(struct scrub_ctx *sctx, struct map_lookup *map, u64 logical, u64 len, u64 physical, struct btrfs_device *dev, u64 flags, u64 gen, int mirror_num, u64 physical_for_dev_replace) { int ret; u8 csum[BTRFS_CSUM_SIZE]; u32 blocksize; if (flags & BTRFS_EXTENT_FLAG_DATA) { if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) blocksize = map->stripe_len; else blocksize = sctx->fs_info->sectorsize; spin_lock(&sctx->stat_lock); sctx->stat.data_extents_scrubbed++; sctx->stat.data_bytes_scrubbed += len; spin_unlock(&sctx->stat_lock); } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) { if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) blocksize = map->stripe_len; else blocksize = sctx->fs_info->nodesize; spin_lock(&sctx->stat_lock); sctx->stat.tree_extents_scrubbed++; sctx->stat.tree_bytes_scrubbed += len; spin_unlock(&sctx->stat_lock); } else { blocksize = sctx->fs_info->sectorsize; WARN_ON(1); } while (len) { u64 l = min_t(u64, len, blocksize); int have_csum = 0; if (flags & BTRFS_EXTENT_FLAG_DATA) { /* push csums to sbio */ have_csum = scrub_find_csum(sctx, logical, csum); if (have_csum == 0) ++sctx->stat.no_csum; } ret = scrub_pages(sctx, logical, l, physical, dev, flags, gen, mirror_num, have_csum ? csum : NULL, 0, physical_for_dev_replace); if (ret) return ret; len -= l; logical += l; physical += l; physical_for_dev_replace += l; } return 0; } static int scrub_pages_for_parity(struct scrub_parity *sparity, u64 logical, u64 len, u64 physical, struct btrfs_device *dev, u64 flags, u64 gen, int mirror_num, u8 *csum) { struct scrub_ctx *sctx = sparity->sctx; struct scrub_block *sblock; int index; sblock = kzalloc(sizeof(*sblock), GFP_KERNEL); if (!sblock) { spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); return -ENOMEM; } /* one ref inside this function, plus one for each page added to * a bio later on */ refcount_set(&sblock->refs, 1); sblock->sctx = sctx; sblock->no_io_error_seen = 1; sblock->sparity = sparity; scrub_parity_get(sparity); for (index = 0; len > 0; index++) { struct scrub_page *spage; u64 l = min_t(u64, len, PAGE_SIZE); spage = kzalloc(sizeof(*spage), GFP_KERNEL); if (!spage) { leave_nomem: spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); scrub_block_put(sblock); return -ENOMEM; } BUG_ON(index >= SCRUB_MAX_PAGES_PER_BLOCK); /* For scrub block */ scrub_page_get(spage); sblock->pagev[index] = spage; /* For scrub parity */ scrub_page_get(spage); list_add_tail(&spage->list, &sparity->spages); spage->sblock = sblock; spage->dev = dev; spage->flags = flags; spage->generation = gen; spage->logical = logical; spage->physical = physical; spage->mirror_num = mirror_num; if (csum) { spage->have_csum = 1; memcpy(spage->csum, csum, sctx->csum_size); } else { spage->have_csum = 0; } sblock->page_count++; spage->page = alloc_page(GFP_KERNEL); if (!spage->page) goto leave_nomem; len -= l; logical += l; physical += l; } WARN_ON(sblock->page_count == 0); for (index = 0; index < sblock->page_count; index++) { struct scrub_page *spage = sblock->pagev[index]; int ret; ret = scrub_add_page_to_rd_bio(sctx, spage); if (ret) { scrub_block_put(sblock); return ret; } } /* last one frees, either here or in bio completion for last page */ scrub_block_put(sblock); return 0; } static int scrub_extent_for_parity(struct scrub_parity *sparity, u64 logical, u64 len, u64 physical, struct btrfs_device *dev, u64 flags, u64 gen, int mirror_num) { struct scrub_ctx *sctx = sparity->sctx; int ret; u8 csum[BTRFS_CSUM_SIZE]; u32 blocksize; if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) { scrub_parity_mark_sectors_error(sparity, logical, len); return 0; } if (flags & BTRFS_EXTENT_FLAG_DATA) { blocksize = sparity->stripe_len; } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) { blocksize = sparity->stripe_len; } else { blocksize = sctx->fs_info->sectorsize; WARN_ON(1); } while (len) { u64 l = min_t(u64, len, blocksize); int have_csum = 0; if (flags & BTRFS_EXTENT_FLAG_DATA) { /* push csums to sbio */ have_csum = scrub_find_csum(sctx, logical, csum); if (have_csum == 0) goto skip; } ret = scrub_pages_for_parity(sparity, logical, l, physical, dev, flags, gen, mirror_num, have_csum ? csum : NULL); if (ret) return ret; skip: len -= l; logical += l; physical += l; } return 0; } /* * Given a physical address, this will calculate it's * logical offset. if this is a parity stripe, it will return * the most left data stripe's logical offset. * * return 0 if it is a data stripe, 1 means parity stripe. */ static int get_raid56_logic_offset(u64 physical, int num, struct map_lookup *map, u64 *offset, u64 *stripe_start) { int i; int j = 0; u64 stripe_nr; u64 last_offset; u32 stripe_index; u32 rot; last_offset = (physical - map->stripes[num].physical) * nr_data_stripes(map); if (stripe_start) *stripe_start = last_offset; *offset = last_offset; for (i = 0; i < nr_data_stripes(map); i++) { *offset = last_offset + i * map->stripe_len; stripe_nr = div64_u64(*offset, map->stripe_len); stripe_nr = div_u64(stripe_nr, nr_data_stripes(map)); /* Work out the disk rotation on this stripe-set */ stripe_nr = div_u64_rem(stripe_nr, map->num_stripes, &rot); /* calculate which stripe this data locates */ rot += i; stripe_index = rot % map->num_stripes; if (stripe_index == num) return 0; if (stripe_index < num) j++; } *offset = last_offset + j * map->stripe_len; return 1; } static void scrub_free_parity(struct scrub_parity *sparity) { struct scrub_ctx *sctx = sparity->sctx; struct scrub_page *curr, *next; int nbits; nbits = bitmap_weight(sparity->ebitmap, sparity->nsectors); if (nbits) { spin_lock(&sctx->stat_lock); sctx->stat.read_errors += nbits; sctx->stat.uncorrectable_errors += nbits; spin_unlock(&sctx->stat_lock); } list_for_each_entry_safe(curr, next, &sparity->spages, list) { list_del_init(&curr->list); scrub_page_put(curr); } kfree(sparity); } static void scrub_parity_bio_endio_worker(struct btrfs_work *work) { struct scrub_parity *sparity = container_of(work, struct scrub_parity, work); struct scrub_ctx *sctx = sparity->sctx; scrub_free_parity(sparity); scrub_pending_bio_dec(sctx); } static void scrub_parity_bio_endio(struct bio *bio) { struct scrub_parity *sparity = (struct scrub_parity *)bio->bi_private; struct btrfs_fs_info *fs_info = sparity->sctx->fs_info; if (bio->bi_status) bitmap_or(sparity->ebitmap, sparity->ebitmap, sparity->dbitmap, sparity->nsectors); bio_put(bio); btrfs_init_work(&sparity->work, btrfs_scrubparity_helper, scrub_parity_bio_endio_worker, NULL, NULL); btrfs_queue_work(fs_info->scrub_parity_workers, &sparity->work); } static void scrub_parity_check_and_repair(struct scrub_parity *sparity) { struct scrub_ctx *sctx = sparity->sctx; struct btrfs_fs_info *fs_info = sctx->fs_info; struct bio *bio; struct btrfs_raid_bio *rbio; struct btrfs_bio *bbio = NULL; u64 length; int ret; if (!bitmap_andnot(sparity->dbitmap, sparity->dbitmap, sparity->ebitmap, sparity->nsectors)) goto out; length = sparity->logic_end - sparity->logic_start; btrfs_bio_counter_inc_blocked(fs_info); ret = btrfs_map_sblock(fs_info, BTRFS_MAP_WRITE, sparity->logic_start, &length, &bbio); if (ret || !bbio || !bbio->raid_map) goto bbio_out; bio = btrfs_io_bio_alloc(0); bio->bi_iter.bi_sector = sparity->logic_start >> 9; bio->bi_private = sparity; bio->bi_end_io = scrub_parity_bio_endio; rbio = raid56_parity_alloc_scrub_rbio(fs_info, bio, bbio, length, sparity->scrub_dev, sparity->dbitmap, sparity->nsectors); if (!rbio) goto rbio_out; scrub_pending_bio_inc(sctx); raid56_parity_submit_scrub_rbio(rbio); return; rbio_out: bio_put(bio); bbio_out: btrfs_bio_counter_dec(fs_info); btrfs_put_bbio(bbio); bitmap_or(sparity->ebitmap, sparity->ebitmap, sparity->dbitmap, sparity->nsectors); spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); out: scrub_free_parity(sparity); } static inline int scrub_calc_parity_bitmap_len(int nsectors) { return DIV_ROUND_UP(nsectors, BITS_PER_LONG) * sizeof(long); } static void scrub_parity_get(struct scrub_parity *sparity) { refcount_inc(&sparity->refs); } static void scrub_parity_put(struct scrub_parity *sparity) { if (!refcount_dec_and_test(&sparity->refs)) return; scrub_parity_check_and_repair(sparity); } static noinline_for_stack int scrub_raid56_parity(struct scrub_ctx *sctx, struct map_lookup *map, struct btrfs_device *sdev, struct btrfs_path *path, u64 logic_start, u64 logic_end) { struct btrfs_fs_info *fs_info = sctx->fs_info; struct btrfs_root *root = fs_info->extent_root; struct btrfs_root *csum_root = fs_info->csum_root; struct btrfs_extent_item *extent; struct btrfs_bio *bbio = NULL; u64 flags; int ret; int slot; struct extent_buffer *l; struct btrfs_key key; u64 generation; u64 extent_logical; u64 extent_physical; u64 extent_len; u64 mapped_length; struct btrfs_device *extent_dev; struct scrub_parity *sparity; int nsectors; int bitmap_len; int extent_mirror_num; int stop_loop = 0; nsectors = div_u64(map->stripe_len, fs_info->sectorsize); bitmap_len = scrub_calc_parity_bitmap_len(nsectors); sparity = kzalloc(sizeof(struct scrub_parity) + 2 * bitmap_len, GFP_NOFS); if (!sparity) { spin_lock(&sctx->stat_lock); sctx->stat.malloc_errors++; spin_unlock(&sctx->stat_lock); return -ENOMEM; } sparity->stripe_len = map->stripe_len; sparity->nsectors = nsectors; sparity->sctx = sctx; sparity->scrub_dev = sdev; sparity->logic_start = logic_start; sparity->logic_end = logic_end; refcount_set(&sparity->refs, 1); INIT_LIST_HEAD(&sparity->spages); sparity->dbitmap = sparity->bitmap; sparity->ebitmap = (void *)sparity->bitmap + bitmap_len; ret = 0; while (logic_start < logic_end) { if (btrfs_fs_incompat(fs_info, SKINNY_METADATA)) key.type = BTRFS_METADATA_ITEM_KEY; else key.type = BTRFS_EXTENT_ITEM_KEY; key.objectid = logic_start; key.offset = (u64)-1; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; if (ret > 0) { ret = btrfs_previous_extent_item(root, path, 0); if (ret < 0) goto out; if (ret > 0) { btrfs_release_path(path); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; } } stop_loop = 0; while (1) { u64 bytes; l = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(l)) { ret = btrfs_next_leaf(root, path); if (ret == 0) continue; if (ret < 0) goto out; stop_loop = 1; break; } btrfs_item_key_to_cpu(l, &key, slot); if (key.type != BTRFS_EXTENT_ITEM_KEY && key.type != BTRFS_METADATA_ITEM_KEY) goto next; if (key.type == BTRFS_METADATA_ITEM_KEY) bytes = fs_info->nodesize; else bytes = key.offset; if (key.objectid + bytes <= logic_start) goto next; if (key.objectid >= logic_end) { stop_loop = 1; break; } while (key.objectid >= logic_start + map->stripe_len) logic_start += map->stripe_len; extent = btrfs_item_ptr(l, slot, struct btrfs_extent_item); flags = btrfs_extent_flags(l, extent); generation = btrfs_extent_generation(l, extent); if ((flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) && (key.objectid < logic_start || key.objectid + bytes > logic_start + map->stripe_len)) { btrfs_err(fs_info, "scrub: tree block %llu spanning stripes, ignored. logical=%llu", key.objectid, logic_start); spin_lock(&sctx->stat_lock); sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); goto next; } again: extent_logical = key.objectid; extent_len = bytes; if (extent_logical < logic_start) { extent_len -= logic_start - extent_logical; extent_logical = logic_start; } if (extent_logical + extent_len > logic_start + map->stripe_len) extent_len = logic_start + map->stripe_len - extent_logical; scrub_parity_mark_sectors_data(sparity, extent_logical, extent_len); mapped_length = extent_len; bbio = NULL; ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, extent_logical, &mapped_length, &bbio, 0); if (!ret) { if (!bbio || mapped_length < extent_len) ret = -EIO; } if (ret) { btrfs_put_bbio(bbio); goto out; } extent_physical = bbio->stripes[0].physical; extent_mirror_num = bbio->mirror_num; extent_dev = bbio->stripes[0].dev; btrfs_put_bbio(bbio); ret = btrfs_lookup_csums_range(csum_root, extent_logical, extent_logical + extent_len - 1, &sctx->csum_list, 1); if (ret) goto out; ret = scrub_extent_for_parity(sparity, extent_logical, extent_len, extent_physical, extent_dev, flags, generation, extent_mirror_num); scrub_free_csums(sctx); if (ret) goto out; if (extent_logical + extent_len < key.objectid + bytes) { logic_start += map->stripe_len; if (logic_start >= logic_end) { stop_loop = 1; break; } if (logic_start < key.objectid + bytes) { cond_resched(); goto again; } } next: path->slots[0]++; } btrfs_release_path(path); if (stop_loop) break; logic_start += map->stripe_len; } out: if (ret < 0) scrub_parity_mark_sectors_error(sparity, logic_start, logic_end - logic_start); scrub_parity_put(sparity); scrub_submit(sctx); mutex_lock(&sctx->wr_lock); scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); btrfs_release_path(path); return ret < 0 ? ret : 0; } static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx, struct map_lookup *map, struct btrfs_device *scrub_dev, int num, u64 base, u64 length) { struct btrfs_path *path, *ppath; struct btrfs_fs_info *fs_info = sctx->fs_info; struct btrfs_root *root = fs_info->extent_root; struct btrfs_root *csum_root = fs_info->csum_root; struct btrfs_extent_item *extent; struct blk_plug plug; u64 flags; int ret; int slot; u64 nstripes; struct extent_buffer *l; u64 physical; u64 logical; u64 logic_end; u64 physical_end; u64 generation; int mirror_num; struct reada_control *reada1; struct reada_control *reada2; struct btrfs_key key; struct btrfs_key key_end; u64 increment = map->stripe_len; u64 offset; u64 extent_logical; u64 extent_physical; u64 extent_len; u64 stripe_logical; u64 stripe_end; struct btrfs_device *extent_dev; int extent_mirror_num; int stop_loop = 0; physical = map->stripes[num].physical; offset = 0; nstripes = div64_u64(length, map->stripe_len); if (map->type & BTRFS_BLOCK_GROUP_RAID0) { offset = map->stripe_len * num; increment = map->stripe_len * map->num_stripes; mirror_num = 1; } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) { int factor = map->num_stripes / map->sub_stripes; offset = map->stripe_len * (num / map->sub_stripes); increment = map->stripe_len * factor; mirror_num = num % map->sub_stripes + 1; } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) { increment = map->stripe_len; mirror_num = num % map->num_stripes + 1; } else if (map->type & BTRFS_BLOCK_GROUP_DUP) { increment = map->stripe_len; mirror_num = num % map->num_stripes + 1; } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { get_raid56_logic_offset(physical, num, map, &offset, NULL); increment = map->stripe_len * nr_data_stripes(map); mirror_num = 1; } else { increment = map->stripe_len; mirror_num = 1; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; ppath = btrfs_alloc_path(); if (!ppath) { btrfs_free_path(path); return -ENOMEM; } /* * work on commit root. The related disk blocks are static as * long as COW is applied. This means, it is save to rewrite * them to repair disk errors without any race conditions */ path->search_commit_root = 1; path->skip_locking = 1; ppath->search_commit_root = 1; ppath->skip_locking = 1; /* * trigger the readahead for extent tree csum tree and wait for * completion. During readahead, the scrub is officially paused * to not hold off transaction commits */ logical = base + offset; physical_end = physical + nstripes * map->stripe_len; if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { get_raid56_logic_offset(physical_end, num, map, &logic_end, NULL); logic_end += base; } else { logic_end = logical + increment * nstripes; } wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0); scrub_blocked_if_needed(fs_info); /* FIXME it might be better to start readahead at commit root */ key.objectid = logical; key.type = BTRFS_EXTENT_ITEM_KEY; key.offset = (u64)0; key_end.objectid = logic_end; key_end.type = BTRFS_METADATA_ITEM_KEY; key_end.offset = (u64)-1; reada1 = btrfs_reada_add(root, &key, &key_end); key.objectid = BTRFS_EXTENT_CSUM_OBJECTID; key.type = BTRFS_EXTENT_CSUM_KEY; key.offset = logical; key_end.objectid = BTRFS_EXTENT_CSUM_OBJECTID; key_end.type = BTRFS_EXTENT_CSUM_KEY; key_end.offset = logic_end; reada2 = btrfs_reada_add(csum_root, &key, &key_end); if (!IS_ERR(reada1)) btrfs_reada_wait(reada1); if (!IS_ERR(reada2)) btrfs_reada_wait(reada2); /* * collect all data csums for the stripe to avoid seeking during * the scrub. This might currently (crc32) end up to be about 1MB */ blk_start_plug(&plug); /* * now find all extents for each stripe and scrub them */ ret = 0; while (physical < physical_end) { /* * canceled? */ if (atomic_read(&fs_info->scrub_cancel_req) || atomic_read(&sctx->cancel_req)) { ret = -ECANCELED; goto out; } /* * check to see if we have to pause */ if (atomic_read(&fs_info->scrub_pause_req)) { /* push queued extents */ sctx->flush_all_writes = true; scrub_submit(sctx); mutex_lock(&sctx->wr_lock); scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0); sctx->flush_all_writes = false; scrub_blocked_if_needed(fs_info); } if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { ret = get_raid56_logic_offset(physical, num, map, &logical, &stripe_logical); logical += base; if (ret) { /* it is parity strip */ stripe_logical += base; stripe_end = stripe_logical + increment; ret = scrub_raid56_parity(sctx, map, scrub_dev, ppath, stripe_logical, stripe_end); if (ret) goto out; goto skip; } } if (btrfs_fs_incompat(fs_info, SKINNY_METADATA)) key.type = BTRFS_METADATA_ITEM_KEY; else key.type = BTRFS_EXTENT_ITEM_KEY; key.objectid = logical; key.offset = (u64)-1; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; if (ret > 0) { ret = btrfs_previous_extent_item(root, path, 0); if (ret < 0) goto out; if (ret > 0) { /* there's no smaller item, so stick with the * larger one */ btrfs_release_path(path); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; } } stop_loop = 0; while (1) { u64 bytes; l = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(l)) { ret = btrfs_next_leaf(root, path); if (ret == 0) continue; if (ret < 0) goto out; stop_loop = 1; break; } btrfs_item_key_to_cpu(l, &key, slot); if (key.type != BTRFS_EXTENT_ITEM_KEY && key.type != BTRFS_METADATA_ITEM_KEY) goto next; if (key.type == BTRFS_METADATA_ITEM_KEY) bytes = fs_info->nodesize; else bytes = key.offset; if (key.objectid + bytes <= logical) goto next; if (key.objectid >= logical + map->stripe_len) { /* out of this device extent */ if (key.objectid >= logic_end) stop_loop = 1; break; } extent = btrfs_item_ptr(l, slot, struct btrfs_extent_item); flags = btrfs_extent_flags(l, extent); generation = btrfs_extent_generation(l, extent); if ((flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) && (key.objectid < logical || key.objectid + bytes > logical + map->stripe_len)) { btrfs_err(fs_info, "scrub: tree block %llu spanning stripes, ignored. logical=%llu", key.objectid, logical); spin_lock(&sctx->stat_lock); sctx->stat.uncorrectable_errors++; spin_unlock(&sctx->stat_lock); goto next; } again: extent_logical = key.objectid; extent_len = bytes; /* * trim extent to this stripe */ if (extent_logical < logical) { extent_len -= logical - extent_logical; extent_logical = logical; } if (extent_logical + extent_len > logical + map->stripe_len) { extent_len = logical + map->stripe_len - extent_logical; } extent_physical = extent_logical - logical + physical; extent_dev = scrub_dev; extent_mirror_num = mirror_num; if (sctx->is_dev_replace) scrub_remap_extent(fs_info, extent_logical, extent_len, &extent_physical, &extent_dev, &extent_mirror_num); ret = btrfs_lookup_csums_range(csum_root, extent_logical, extent_logical + extent_len - 1, &sctx->csum_list, 1); if (ret) goto out; ret = scrub_extent(sctx, map, extent_logical, extent_len, extent_physical, extent_dev, flags, generation, extent_mirror_num, extent_logical - logical + physical); scrub_free_csums(sctx); if (ret) goto out; if (extent_logical + extent_len < key.objectid + bytes) { if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { /* * loop until we find next data stripe * or we have finished all stripes. */ loop: physical += map->stripe_len; ret = get_raid56_logic_offset(physical, num, map, &logical, &stripe_logical); logical += base; if (ret && physical < physical_end) { stripe_logical += base; stripe_end = stripe_logical + increment; ret = scrub_raid56_parity(sctx, map, scrub_dev, ppath, stripe_logical, stripe_end); if (ret) goto out; goto loop; } } else { physical += map->stripe_len; logical += increment; } if (logical < key.objectid + bytes) { cond_resched(); goto again; } if (physical >= physical_end) { stop_loop = 1; break; } } next: path->slots[0]++; } btrfs_release_path(path); skip: logical += increment; physical += map->stripe_len; spin_lock(&sctx->stat_lock); if (stop_loop) sctx->stat.last_physical = map->stripes[num].physical + length; else sctx->stat.last_physical = physical; spin_unlock(&sctx->stat_lock); if (stop_loop) break; } out: /* push queued extents */ scrub_submit(sctx); mutex_lock(&sctx->wr_lock); scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); blk_finish_plug(&plug); btrfs_free_path(path); btrfs_free_path(ppath); return ret < 0 ? ret : 0; } static noinline_for_stack int scrub_chunk(struct scrub_ctx *sctx, struct btrfs_device *scrub_dev, u64 chunk_offset, u64 length, u64 dev_offset, struct btrfs_block_group_cache *cache) { struct btrfs_fs_info *fs_info = sctx->fs_info; struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree; struct map_lookup *map; struct extent_map *em; int i; int ret = 0; read_lock(&map_tree->map_tree.lock); em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1); read_unlock(&map_tree->map_tree.lock); if (!em) { /* * Might have been an unused block group deleted by the cleaner * kthread or relocation. */ spin_lock(&cache->lock); if (!cache->removed) ret = -EINVAL; spin_unlock(&cache->lock); return ret; } map = em->map_lookup; if (em->start != chunk_offset) goto out; if (em->len < length) goto out; for (i = 0; i < map->num_stripes; ++i) { if (map->stripes[i].dev->bdev == scrub_dev->bdev && map->stripes[i].physical == dev_offset) { ret = scrub_stripe(sctx, map, scrub_dev, i, chunk_offset, length); if (ret) goto out; } } out: free_extent_map(em); return ret; } static noinline_for_stack int scrub_enumerate_chunks(struct scrub_ctx *sctx, struct btrfs_device *scrub_dev, u64 start, u64 end) { struct btrfs_dev_extent *dev_extent = NULL; struct btrfs_path *path; struct btrfs_fs_info *fs_info = sctx->fs_info; struct btrfs_root *root = fs_info->dev_root; u64 length; u64 chunk_offset; int ret = 0; int ro_set; int slot; struct extent_buffer *l; struct btrfs_key key; struct btrfs_key found_key; struct btrfs_block_group_cache *cache; struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = READA_FORWARD; path->search_commit_root = 1; path->skip_locking = 1; key.objectid = scrub_dev->devid; key.offset = 0ull; key.type = BTRFS_DEV_EXTENT_KEY; while (1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) break; if (ret > 0) { if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) { ret = btrfs_next_leaf(root, path); if (ret < 0) break; if (ret > 0) { ret = 0; break; } } else { ret = 0; } } l = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(l, &found_key, slot); if (found_key.objectid != scrub_dev->devid) break; if (found_key.type != BTRFS_DEV_EXTENT_KEY) break; if (found_key.offset >= end) break; if (found_key.offset < key.offset) break; dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent); length = btrfs_dev_extent_length(l, dev_extent); if (found_key.offset + length <= start) goto skip; chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent); /* * get a reference on the corresponding block group to prevent * the chunk from going away while we scrub it */ cache = btrfs_lookup_block_group(fs_info, chunk_offset); /* some chunks are removed but not committed to disk yet, * continue scrubbing */ if (!cache) goto skip; /* * we need call btrfs_inc_block_group_ro() with scrubs_paused, * to avoid deadlock caused by: * btrfs_inc_block_group_ro() * -> btrfs_wait_for_commit() * -> btrfs_commit_transaction() * -> btrfs_scrub_pause() */ scrub_pause_on(fs_info); ret = btrfs_inc_block_group_ro(cache); if (!ret && sctx->is_dev_replace) { /* * If we are doing a device replace wait for any tasks * that started delalloc right before we set the block * group to RO mode, as they might have just allocated * an extent from it or decided they could do a nocow * write. And if any such tasks did that, wait for their * ordered extents to complete and then commit the * current transaction, so that we can later see the new * extent items in the extent tree - the ordered extents * create delayed data references (for cow writes) when * they complete, which will be run and insert the * corresponding extent items into the extent tree when * we commit the transaction they used when running * inode.c:btrfs_finish_ordered_io(). We later use * the commit root of the extent tree to find extents * to copy from the srcdev into the tgtdev, and we don't * want to miss any new extents. */ btrfs_wait_block_group_reservations(cache); btrfs_wait_nocow_writers(cache); ret = btrfs_wait_ordered_roots(fs_info, U64_MAX, cache->key.objectid, cache->key.offset); if (ret > 0) { struct btrfs_trans_handle *trans; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) ret = PTR_ERR(trans); else ret = btrfs_commit_transaction(trans); if (ret) { scrub_pause_off(fs_info); btrfs_put_block_group(cache); break; } } } scrub_pause_off(fs_info); if (ret == 0) { ro_set = 1; } else if (ret == -ENOSPC) { /* * btrfs_inc_block_group_ro return -ENOSPC when it * failed in creating new chunk for metadata. * It is not a problem for scrub/replace, because * metadata are always cowed, and our scrub paused * commit_transactions. */ ro_set = 0; } else { btrfs_warn(fs_info, "failed setting block group ro: %d", ret); btrfs_put_block_group(cache); break; } down_write(&fs_info->dev_replace.rwsem); dev_replace->cursor_right = found_key.offset + length; dev_replace->cursor_left = found_key.offset; dev_replace->item_needs_writeback = 1; up_write(&dev_replace->rwsem); ret = scrub_chunk(sctx, scrub_dev, chunk_offset, length, found_key.offset, cache); /* * flush, submit all pending read and write bios, afterwards * wait for them. * Note that in the dev replace case, a read request causes * write requests that are submitted in the read completion * worker. Therefore in the current situation, it is required * that all write requests are flushed, so that all read and * write requests are really completed when bios_in_flight * changes to 0. */ sctx->flush_all_writes = true; scrub_submit(sctx); mutex_lock(&sctx->wr_lock); scrub_wr_submit(sctx); mutex_unlock(&sctx->wr_lock); wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0); scrub_pause_on(fs_info); /* * must be called before we decrease @scrub_paused. * make sure we don't block transaction commit while * we are waiting pending workers finished. */ wait_event(sctx->list_wait, atomic_read(&sctx->workers_pending) == 0); sctx->flush_all_writes = false; scrub_pause_off(fs_info); down_write(&fs_info->dev_replace.rwsem); dev_replace->cursor_left = dev_replace->cursor_right; dev_replace->item_needs_writeback = 1; up_write(&fs_info->dev_replace.rwsem); if (ro_set) btrfs_dec_block_group_ro(cache); /* * We might have prevented the cleaner kthread from deleting * this block group if it was already unused because we raced * and set it to RO mode first. So add it back to the unused * list, otherwise it might not ever be deleted unless a manual * balance is triggered or it becomes used and unused again. */ spin_lock(&cache->lock); if (!cache->removed && !cache->ro && cache->reserved == 0 && btrfs_block_group_used(&cache->item) == 0) { spin_unlock(&cache->lock); btrfs_mark_bg_unused(cache); } else { spin_unlock(&cache->lock); } btrfs_put_block_group(cache); if (ret) break; if (sctx->is_dev_replace && atomic64_read(&dev_replace->num_write_errors) > 0) { ret = -EIO; break; } if (sctx->stat.malloc_errors > 0) { ret = -ENOMEM; break; } skip: key.offset = found_key.offset + length; btrfs_release_path(path); } btrfs_free_path(path); return ret; } static noinline_for_stack int scrub_supers(struct scrub_ctx *sctx, struct btrfs_device *scrub_dev) { int i; u64 bytenr; u64 gen; int ret; struct btrfs_fs_info *fs_info = sctx->fs_info; if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) return -EIO; /* Seed devices of a new filesystem has their own generation. */ if (scrub_dev->fs_devices != fs_info->fs_devices) gen = scrub_dev->generation; else gen = fs_info->last_trans_committed; for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) { bytenr = btrfs_sb_offset(i); if (bytenr + BTRFS_SUPER_INFO_SIZE > scrub_dev->commit_total_bytes) break; ret = scrub_pages(sctx, bytenr, BTRFS_SUPER_INFO_SIZE, bytenr, scrub_dev, BTRFS_EXTENT_FLAG_SUPER, gen, i, NULL, 1, bytenr); if (ret) return ret; } wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0); return 0; } /* * get a reference count on fs_info->scrub_workers. start worker if necessary */ static noinline_for_stack int scrub_workers_get(struct btrfs_fs_info *fs_info, int is_dev_replace) { unsigned int flags = WQ_FREEZABLE | WQ_UNBOUND; int max_active = fs_info->thread_pool_size; if (fs_info->scrub_workers_refcnt == 0) { fs_info->scrub_workers = btrfs_alloc_workqueue(fs_info, "scrub", flags, is_dev_replace ? 1 : max_active, 4); if (!fs_info->scrub_workers) goto fail_scrub_workers; fs_info->scrub_wr_completion_workers = btrfs_alloc_workqueue(fs_info, "scrubwrc", flags, max_active, 2); if (!fs_info->scrub_wr_completion_workers) goto fail_scrub_wr_completion_workers; fs_info->scrub_parity_workers = btrfs_alloc_workqueue(fs_info, "scrubparity", flags, max_active, 2); if (!fs_info->scrub_parity_workers) goto fail_scrub_parity_workers; } ++fs_info->scrub_workers_refcnt; return 0; fail_scrub_parity_workers: btrfs_destroy_workqueue(fs_info->scrub_wr_completion_workers); fail_scrub_wr_completion_workers: btrfs_destroy_workqueue(fs_info->scrub_workers); fail_scrub_workers: return -ENOMEM; } static noinline_for_stack void scrub_workers_put(struct btrfs_fs_info *fs_info) { if (--fs_info->scrub_workers_refcnt == 0) { btrfs_destroy_workqueue(fs_info->scrub_workers); btrfs_destroy_workqueue(fs_info->scrub_wr_completion_workers); btrfs_destroy_workqueue(fs_info->scrub_parity_workers); } WARN_ON(fs_info->scrub_workers_refcnt < 0); } int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start, u64 end, struct btrfs_scrub_progress *progress, int readonly, int is_dev_replace) { struct scrub_ctx *sctx; int ret; struct btrfs_device *dev; unsigned int nofs_flag; if (btrfs_fs_closing(fs_info)) return -EINVAL; if (fs_info->nodesize > BTRFS_STRIPE_LEN) { /* * in this case scrub is unable to calculate the checksum * the way scrub is implemented. Do not handle this * situation at all because it won't ever happen. */ btrfs_err(fs_info, "scrub: size assumption nodesize <= BTRFS_STRIPE_LEN (%d <= %d) fails", fs_info->nodesize, BTRFS_STRIPE_LEN); return -EINVAL; } if (fs_info->sectorsize != PAGE_SIZE) { /* not supported for data w/o checksums */ btrfs_err_rl(fs_info, "scrub: size assumption sectorsize != PAGE_SIZE (%d != %lu) fails", fs_info->sectorsize, PAGE_SIZE); return -EINVAL; } if (fs_info->nodesize > PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK || fs_info->sectorsize > PAGE_SIZE * SCRUB_MAX_PAGES_PER_BLOCK) { /* * would exhaust the array bounds of pagev member in * struct scrub_block */ btrfs_err(fs_info, "scrub: size assumption nodesize and sectorsize <= SCRUB_MAX_PAGES_PER_BLOCK (%d <= %d && %d <= %d) fails", fs_info->nodesize, SCRUB_MAX_PAGES_PER_BLOCK, fs_info->sectorsize, SCRUB_MAX_PAGES_PER_BLOCK); return -EINVAL; } /* Allocate outside of device_list_mutex */ sctx = scrub_setup_ctx(fs_info, is_dev_replace); if (IS_ERR(sctx)) return PTR_ERR(sctx); mutex_lock(&fs_info->fs_devices->device_list_mutex); dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (!dev || (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) && !is_dev_replace)) { mutex_unlock(&fs_info->fs_devices->device_list_mutex); ret = -ENODEV; goto out_free_ctx; } if (!is_dev_replace && !readonly && !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) { mutex_unlock(&fs_info->fs_devices->device_list_mutex); btrfs_err_in_rcu(fs_info, "scrub: device %s is not writable", rcu_str_deref(dev->name)); ret = -EROFS; goto out_free_ctx; } mutex_lock(&fs_info->scrub_lock); if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) || test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &dev->dev_state)) { mutex_unlock(&fs_info->scrub_lock); mutex_unlock(&fs_info->fs_devices->device_list_mutex); ret = -EIO; goto out_free_ctx; } down_read(&fs_info->dev_replace.rwsem); if (dev->scrub_ctx || (!is_dev_replace && btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))) { up_read(&fs_info->dev_replace.rwsem); mutex_unlock(&fs_info->scrub_lock); mutex_unlock(&fs_info->fs_devices->device_list_mutex); ret = -EINPROGRESS; goto out_free_ctx; } up_read(&fs_info->dev_replace.rwsem); ret = scrub_workers_get(fs_info, is_dev_replace); if (ret) { mutex_unlock(&fs_info->scrub_lock); mutex_unlock(&fs_info->fs_devices->device_list_mutex); goto out_free_ctx; } sctx->readonly = readonly; dev->scrub_ctx = sctx; mutex_unlock(&fs_info->fs_devices->device_list_mutex); /* * checking @scrub_pause_req here, we can avoid * race between committing transaction and scrubbing. */ __scrub_blocked_if_needed(fs_info); atomic_inc(&fs_info->scrubs_running); mutex_unlock(&fs_info->scrub_lock); /* * In order to avoid deadlock with reclaim when there is a transaction * trying to pause scrub, make sure we use GFP_NOFS for all the * allocations done at btrfs_scrub_pages() and scrub_pages_for_parity() * invoked by our callees. The pausing request is done when the * transaction commit starts, and it blocks the transaction until scrub * is paused (done at specific points at scrub_stripe() or right above * before incrementing fs_info->scrubs_running). */ nofs_flag = memalloc_nofs_save(); if (!is_dev_replace) { /* * by holding device list mutex, we can * kick off writing super in log tree sync. */ mutex_lock(&fs_info->fs_devices->device_list_mutex); ret = scrub_supers(sctx, dev); mutex_unlock(&fs_info->fs_devices->device_list_mutex); } if (!ret) ret = scrub_enumerate_chunks(sctx, dev, start, end); memalloc_nofs_restore(nofs_flag); wait_event(sctx->list_wait, atomic_read(&sctx->bios_in_flight) == 0); atomic_dec(&fs_info->scrubs_running); wake_up(&fs_info->scrub_pause_wait); wait_event(sctx->list_wait, atomic_read(&sctx->workers_pending) == 0); if (progress) memcpy(progress, &sctx->stat, sizeof(*progress)); mutex_lock(&fs_info->scrub_lock); dev->scrub_ctx = NULL; scrub_workers_put(fs_info); mutex_unlock(&fs_info->scrub_lock); scrub_put_ctx(sctx); return ret; out_free_ctx: scrub_free_ctx(sctx); return ret; } void btrfs_scrub_pause(struct btrfs_fs_info *fs_info) { mutex_lock(&fs_info->scrub_lock); atomic_inc(&fs_info->scrub_pause_req); while (atomic_read(&fs_info->scrubs_paused) != atomic_read(&fs_info->scrubs_running)) { mutex_unlock(&fs_info->scrub_lock); wait_event(fs_info->scrub_pause_wait, atomic_read(&fs_info->scrubs_paused) == atomic_read(&fs_info->scrubs_running)); mutex_lock(&fs_info->scrub_lock); } mutex_unlock(&fs_info->scrub_lock); } void btrfs_scrub_continue(struct btrfs_fs_info *fs_info) { atomic_dec(&fs_info->scrub_pause_req); wake_up(&fs_info->scrub_pause_wait); } int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info) { mutex_lock(&fs_info->scrub_lock); if (!atomic_read(&fs_info->scrubs_running)) { mutex_unlock(&fs_info->scrub_lock); return -ENOTCONN; } atomic_inc(&fs_info->scrub_cancel_req); while (atomic_read(&fs_info->scrubs_running)) { mutex_unlock(&fs_info->scrub_lock); wait_event(fs_info->scrub_pause_wait, atomic_read(&fs_info->scrubs_running) == 0); mutex_lock(&fs_info->scrub_lock); } atomic_dec(&fs_info->scrub_cancel_req); mutex_unlock(&fs_info->scrub_lock); return 0; } int btrfs_scrub_cancel_dev(struct btrfs_fs_info *fs_info, struct btrfs_device *dev) { struct scrub_ctx *sctx; mutex_lock(&fs_info->scrub_lock); sctx = dev->scrub_ctx; if (!sctx) { mutex_unlock(&fs_info->scrub_lock); return -ENOTCONN; } atomic_inc(&sctx->cancel_req); while (dev->scrub_ctx) { mutex_unlock(&fs_info->scrub_lock); wait_event(fs_info->scrub_pause_wait, dev->scrub_ctx == NULL); mutex_lock(&fs_info->scrub_lock); } mutex_unlock(&fs_info->scrub_lock); return 0; } int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid, struct btrfs_scrub_progress *progress) { struct btrfs_device *dev; struct scrub_ctx *sctx = NULL; mutex_lock(&fs_info->fs_devices->device_list_mutex); dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (dev) sctx = dev->scrub_ctx; if (sctx) memcpy(progress, &sctx->stat, sizeof(*progress)); mutex_unlock(&fs_info->fs_devices->device_list_mutex); return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV; } static void scrub_remap_extent(struct btrfs_fs_info *fs_info, u64 extent_logical, u64 extent_len, u64 *extent_physical, struct btrfs_device **extent_dev, int *extent_mirror_num) { u64 mapped_length; struct btrfs_bio *bbio = NULL; int ret; mapped_length = extent_len; ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, extent_logical, &mapped_length, &bbio, 0); if (ret || !bbio || mapped_length < extent_len || !bbio->stripes[0].dev->bdev) { btrfs_put_bbio(bbio); return; } *extent_physical = bbio->stripes[0].physical; *extent_mirror_num = bbio->mirror_num; *extent_dev = bbio->stripes[0].dev; btrfs_put_bbio(bbio); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_1223_2
crossvul-cpp_data_bad_4986_0
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); if (unlikely(isolated_balloon_page(page))) balloon_page_putback(page); else putback_lru_page(page); } } /* * Restore a potential migration pte to a working pte entry */ static int remove_migration_pte(struct page *new, struct vm_area_struct *vma, unsigned long addr, void *old) { struct mm_struct *mm = vma->vm_mm; swp_entry_t entry; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; if (unlikely(PageHuge(new))) { ptep = huge_pte_offset(mm, addr); if (!ptep) goto out; ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep); } else { pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; ptep = pte_offset_map(pmd, addr); /* * Peek to check is_swap_pte() before taking ptlock? No, we * can race mremap's move_ptes(), which skips anon_vma lock. */ ptl = pte_lockptr(mm, pmd); } spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto unlock; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry) || migration_entry_to_page(entry) != old) goto unlock; get_page(new); pte = pte_mkold(mk_pte(new, vma->vm_page_prot)); if (pte_swp_soft_dirty(*ptep)) pte = pte_mksoft_dirty(pte); /* Recheck VMA as permissions can change since migration started */ if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); } #endif flush_dcache_page(new); set_pte_at(mm, addr, ptep, pte); if (PageHuge(new)) { if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, addr); else page_dup_rmap(new); } else if (PageAnon(new)) page_add_anon_rmap(new, vma, addr); else page_add_file_rmap(new); if (vma->vm_flags & VM_LOCKED) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, addr, ptep); unlock: pte_unmap_unlock(ptep, ptl); out: return SWAP_AGAIN; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ static void remove_migration_ptes(struct page *old, struct page *new) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ __dec_zone_page_state(page, NR_FILE_PAGES); __inc_zone_page_state(newpage, NR_FILE_PAGES); if (!PageSwapCache(page) && PageSwapBacked(page)) { __dec_zone_page_state(page, NR_SHMEM); __inc_zone_page_state(newpage, NR_SHMEM); } spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(pslot, newpage); page_unfreeze_refs(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems provide a * migratepage callback. Anonymous pages are part of swap * space which also has its own migratepage callback. This * is the most common path for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { set_page_memcg(page, NULL); if (!PageAnon(page)) page->mapping = NULL; } return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(isolated_balloon_page(page))) { /* * A ballooned page does not need any special attention from * physical to virtual reverse mapping procedures. * Skip any attempt to unmap PTEs or to remap swap cache, * in order to avoid burning cycles at rmap level, and perform * the page migration right away (proteced by page lock). */ rc = balloon_page_migrate(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ goto out; } if (unlikely(PageTransHuge(page))) if (unlikely(split_huge_page(page))) goto out; rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) put_new_page = NULL; out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); /* Soft-offlined page shouldn't go through lru cache list */ if (reason == MR_MEMORY_FAILURE) { put_page(page); if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } else putback_lru_page(page); } /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, putback_lru_page() will drop the reference grabbed * during isolation. */ if (put_new_page) put_new_page(newpage, private); else if (unlikely(__is_movable_balloon_page(newpage))) { /* drop our reference, page already in the balloon */ put_page(newpage); } else putback_lru_page(newpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; if (!zone_reclaimable(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~GFP_IOFS, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; pmd_t orig_entry; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER); if (!new_page) goto out_fail; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } if (mm_tlb_flush_pending(mm)) flush_tlb_range(vma, mmun_start, mmun_end); /* Prepare a page as a migration target */ __set_page_locked(new_page); SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) { fail_putback: spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } orig_entry = *pmd; entry = mk_pmd(new_page, vma->vm_page_prot); entry = pmd_mkhuge(entry); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); flush_tlb_range(vma, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); if (page_count(page) != 2) { set_pmd_at(mm, mmun_start, pmd, orig_entry); flush_tlb_range(vma, mmun_start, mmun_end); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); page_remove_rmap(new_page); goto fail_putback; } mlock_migrate_page(new_page, page); set_page_memcg(new_page, page_memcg(page)); set_page_memcg(page, NULL); page_remove_rmap(page); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
./CrossVul/dataset_final_sorted/CWE-476/c/bad_4986_0
crossvul-cpp_data_good_4826_1
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | 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 "zend_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(Z_STRVAL_P(a), Z_STRLEN_P(a), (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), PHP_WDDX_VERSION, 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 (Z_TYPE(((st_entry *)stack->elements[i])->data) != IS_UNDEF && ((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_resource *rsrc) { 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; zend_string *str; 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); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); smart_str_0(packet); str = zend_string_copy(packet->s); php_wddx_destructor(packet); return str; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval retval; zval *ent; zend_string *key; zend_ulong idx; int ret; if (vallen == 0) { return SUCCESS; } ZVAL_UNDEF(&retval); if ((ret = php_wddx_deserialize_ex(val, vallen, &retval)) == SUCCESS) { if (Z_TYPE(retval) != IS_ARRAY) { zval_dtor(&retval); return FAILURE; } ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(retval), idx, key, ent) { if (key == NULL) { key = zend_long_to_str(idx); } else { zend_string_addref(key); } if (php_set_session_var(key, ent, NULL)) { if (Z_REFCOUNTED_P(ent)) Z_ADDREF_P(ent); } PS_ADD_VAR(key); zend_string_release(key); } ZEND_HASH_FOREACH_END(); } 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, size_t comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { zend_string *escaped = php_escape_html_entities( comment, comment_len, 0, ENT_QUOTES, NULL); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, ZSTR_VAL(escaped), ZSTR_LEN(escaped)); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); zend_string_release(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) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { zend_string *buf = php_escape_html_entities( (unsigned char *) Z_STRVAL_P(var), Z_STRLEN_P(var), 0, ENT_QUOTES, NULL); php_wddx_add_chunk_ex(packet, ZSTR_VAL(buf), ZSTR_LEN(buf)); zend_string_release(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]; zend_string *str = zval_get_string(var); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, ZSTR_VAL(str)); zend_string_release(str); 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_TYPE_P(var) == IS_TRUE ? 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; zend_string *key; zend_ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; zend_class_entry *ce; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); ce = Z_OBJCE_P(obj); if (!ce || ce->serialize || ce->unserialize) { php_error_docref(NULL, E_WARNING, "Class %s can not be serialized", ZSTR_VAL(class_name)); PHP_CLEANUP_CLASS_ATTRIBUTES(); return; } ZVAL_STRING(&fname, "__sleep"); /* * 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) == SUCCESS) { if (!Z_ISUNDEF(retval) && (sleephash = HASH_OF(&retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); 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, ZSTR_VAL(class_name), ZSTR_LEN(class_name)); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = Z_OBJPROP_P(obj); ZEND_HASH_FOREACH_VAL(sleephash, varname) { if (Z_TYPE_P(varname) != IS_STRING) { php_error_docref(NULL, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if ((ent = zend_hash_find(objhash, Z_STR_P(varname))) != NULL) { php_wddx_serialize_var(packet, ent, Z_STR_P(varname)); } } ZEND_HASH_FOREACH_END(); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { 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, ZSTR_VAL(class_name), ZSTR_LEN(class_name)); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = Z_OBJPROP_P(obj); ZEND_HASH_FOREACH_KEY_VAL(objhash, idx, key, ent) { if (ent == obj) { continue; } if (key) { const char *class_name, *prop_name; size_t prop_name_len; zend_string *tmp; zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len); tmp = zend_string_init(prop_name, prop_name_len, 0); php_wddx_serialize_var(packet, ent, tmp); zend_string_release(tmp); } else { key = zend_long_to_str(idx); php_wddx_serialize_var(packet, ent, key); zend_string_release(key); } } ZEND_HASH_FOREACH_END(); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } PHP_CLEANUP_CLASS_ATTRIBUTES(); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval *ent; zend_string *key; int is_struct = 0; zend_ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; zend_ulong ind = 0; target_hash = Z_ARRVAL_P(arr); ZEND_HASH_FOREACH_KEY(target_hash, idx, key) { if (key) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } ZEND_HASH_FOREACH_END(); 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); } ZEND_HASH_FOREACH_KEY_VAL(target_hash, idx, key, ent) { if (ent == arr) { continue; } if (is_struct) { if (key) { php_wddx_serialize_var(packet, ent, key); } else { key = zend_long_to_str(idx); php_wddx_serialize_var(packet, ent, key); zend_string_release(key); } } else { php_wddx_serialize_var(packet, ent, NULL); } } ZEND_HASH_FOREACH_END(); 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, zend_string *name) { HashTable *ht; if (name) { char *tmp_buf; zend_string *name_esc = php_escape_html_entities((unsigned char *) ZSTR_VAL(name), ZSTR_LEN(name), 0, ENT_QUOTES, NULL); tmp_buf = emalloc(ZSTR_LEN(name_esc) + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, ZSTR_LEN(name_esc) + sizeof(WDDX_VAR_S), WDDX_VAR_S, ZSTR_VAL(name_esc)); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); zend_string_release(name_esc); } if (Z_TYPE_P(var) == IS_INDIRECT) { var = Z_INDIRECT_P(var); } ZVAL_DEREF(var); switch (Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_TRUE: case IS_FALSE: 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->u.v.nApplyCount > 1) { php_error_docref(NULL, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } if (ZEND_HASH_APPLY_PROTECTION(ht)) { ht->u.v.nApplyCount++; } php_wddx_serialize_array(packet, var); if (ZEND_HASH_APPLY_PROTECTION(ht)) { ht->u.v.nApplyCount--; } break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->u.v.nApplyCount > 1) { php_error_docref(NULL, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->u.v.nApplyCount++; php_wddx_serialize_object(packet, var); ht->u.v.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; if (Z_TYPE_P(name_var) == IS_STRING) { zend_array *symbol_table = zend_rebuild_symbol_table(); if ((val = zend_hash_find(symbol_table, Z_STR_P(name_var))) != NULL) { if (Z_TYPE_P(val) == IS_INDIRECT) { val = Z_INDIRECT_P(val); } php_wddx_serialize_var(packet, val, Z_STR_P(name_var)); } } 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->u.v.nApplyCount > 1) { php_error_docref(NULL, E_WARNING, "recursion detected"); return; } if (Z_IMMUTABLE_P(name_var)) { ZEND_HASH_FOREACH_VAL(target_hash, val) { php_wddx_add_var(packet, val); } ZEND_HASH_FOREACH_END(); } else { ZEND_HASH_FOREACH_VAL(target_hash, val) { if (is_array) { target_hash->u.v.nApplyCount++; } ZVAL_DEREF(val); php_wddx_add_var(packet, val); if (is_array) { target_hash->u.v.nApplyCount--; } } ZEND_HASH_FOREACH_END(); } } } /* }}} */ /* {{{ 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((char *)name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp((char *)atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp((char *)name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ZVAL_STR(&ent.data, ZSTR_EMPTY_ALLOC()); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ZVAL_STR(&ent.data, ZSTR_EMPTY_ALLOC()); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)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((char *)atts[i+1], NULL, 16)); php_wddx_process_data(user_data, (XML_Char *) tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp((char *)name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ZVAL_LONG(&ent.data, 0); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_TRUE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen((char *)atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp((char *)name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ZVAL_NULL(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; array_init(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; array_init(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup((char *)atts[i+1]); break; } } } else if (!strcmp((char *)name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; array_init(&ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval tmp; char *key; const char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen((char *)atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); array_init(&tmp); add_assoc_zval_ex(&ent.data, key, p2 - p1, &tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { array_init(&tmp); add_assoc_zval_ex(&ent.data, p1, endp - p1, &tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ZVAL_UNDEF(&ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)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 && (field = zend_hash_str_find(Z_ARRVAL(recordset->data), (char*)atts[i+1], strlen((char *)atts[i+1]))) != NULL) { ZVAL_COPY_VALUE(&ent.data, field); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ZVAL_LONG(&ent.data, 0); 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; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ if (object_init_ex(&obj, pce) != SUCCESS || EG(exception)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be instantiated", Z_STRVAL(ent1->data)); } else { /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)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; if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_BINARY: case ST_STRING: if (Z_STRLEN(ent->data) == 0) { zval_ptr_dtor(&ent->data); ZVAL_STRINGL(&ent->data, (char *)s, len); } else { Z_STR(ent->data) = zend_string_extend(Z_STR(ent->data), Z_STRLEN(ent->data) + len, 0); memcpy(Z_STRVAL(ent->data) + Z_STRLEN(ent->data) - len, (char *)s, len); Z_STRVAL(ent->data)[Z_STRLEN(ent->data)] = '\0'; } break; case ST_NUMBER: ZVAL_STRINGL(&ent->data, (char *)s, len); convert_scalar_to_number(&ent->data); break; case ST_BOOLEAN: if (!strcmp((char *)s, "true")) { ZVAL_TRUE(&ent->data); } else if (!strcmp((char *)s, "false")) { ZVAL_FALSE(&ent->data); } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ZVAL_UNDEF(&ent->data); } break; case ST_DATETIME: { zend_string *str; if (Z_TYPE(ent->data) == IS_STRING) { str = zend_string_safe_alloc(Z_STRLEN(ent->data), 1, len, 0); memcpy(ZSTR_VAL(str), Z_STRVAL(ent->data), Z_STRLEN(ent->data)); memcpy(ZSTR_VAL(str) + Z_STRLEN(ent->data), s, len); ZSTR_VAL(str)[ZSTR_LEN(str)] = '\0'; zval_dtor(&ent->data); } else { str = zend_string_init((char *)s, len, 0); } ZVAL_LONG(&ent->data, php_parse_date(ZSTR_VAL(str), NULL)); /* date out of range < 1969 or > 2038 */ if (Z_LVAL(ent->data) == -1) { ZVAL_STR_COPY(&ent->data, str); } zend_string_release(str); } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(const char *value, size_t vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate((XML_Char *) "UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); /* XXX value should be parsed in the loop to exhaust size_t */ XML_Parse(parser, (const XML_Char *) value, (int)vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if (Z_ISUNDEF(ent->data)) { retval = FAILURE; } else { ZVAL_COPY(return_value, &ent->data); 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; size_t comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS(), "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); php_wddx_packet_end(packet); smart_str_0(packet); RETVAL_STR_COPY(packet->s); php_wddx_destructor(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(), "+", &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++) { zval *arg; if (!Z_ISREF(args[i])) { arg = &args[i]; } else { arg = Z_REFVAL(args[i]); } if (Z_TYPE_P(arg) != IS_ARRAY && Z_TYPE_P(arg) != IS_OBJECT) { convert_to_string_ex(arg); } php_wddx_add_var(packet, arg); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); smart_str_0(packet); RETVAL_STR_COPY(packet->s); php_wddx_destructor(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = ecalloc(1, sizeof(smart_str)); 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; size_t comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|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); RETURN_RES(zend_register_resource(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(), "r", &packet_id) == FAILURE) { return; } if ((packet = (wddx_packet *)zend_fetch_resource(Z_RES_P(packet_id), "WDDX packet ID", le_wddx)) == NULL) { RETURN_FALSE; } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); smart_str_0(packet); RETVAL_STR_COPY(packet->s); zend_list_close(Z_RES_P(packet_id)); } /* }}} */ /* {{{ proto bool 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(), "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if ((packet = (wddx_packet *)zend_fetch_resource(Z_RES_P(packet_id), "WDDX packet ID", le_wddx)) == NULL) { RETURN_FALSE; } for (i=0; i<num_args; i++) { zval *arg; if (!Z_ISREF(args[i])) { arg = &args[i]; } else { arg = Z_REFVAL(args[i]); } if (Z_TYPE_P(arg) != IS_ARRAY && Z_TYPE_P(arg) != IS_OBJECT) { convert_to_string_ex(arg); } php_wddx_add_var(packet, arg); } RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; php_stream *stream = NULL; zend_string *payload = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STR_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, packet); if (stream) { payload = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload == NULL) { return; } php_wddx_deserialize_ex(ZSTR_VAL(payload), ZSTR_LEN(payload), return_value); if (stream) { efree(payload); } } /* }}} */ #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_4826_1
crossvul-cpp_data_bad_318_0
/* * Copyright © 2009 Dan Nicholson * Copyright © 2012 Intel Corporation * Copyright © 2012 Ran Benita <ran234@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * 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. * * Author: Dan Nicholson <dbn.lists@gmail.com> * Daniel Stone <daniel@fooishbar.org> * Ran Benita <ran234@gmail.com> */ #include "xkbcomp-priv.h" static void ComputeEffectiveMask(struct xkb_keymap *keymap, struct xkb_mods *mods) { mods->mask = mod_mask_get_effective(keymap, mods->mods); } static void UpdateActionMods(struct xkb_keymap *keymap, union xkb_action *act, xkb_mod_mask_t modmap) { switch (act->type) { case ACTION_TYPE_MOD_SET: case ACTION_TYPE_MOD_LATCH: case ACTION_TYPE_MOD_LOCK: if (act->mods.flags & ACTION_MODS_LOOKUP_MODMAP) act->mods.mods.mods = modmap; ComputeEffectiveMask(keymap, &act->mods.mods); break; default: break; } } static const struct xkb_sym_interpret default_interpret = { .sym = XKB_KEY_NoSymbol, .repeat = true, .match = MATCH_ANY_OR_NONE, .mods = 0, .virtual_mod = XKB_MOD_INVALID, .action = { .type = ACTION_TYPE_NONE }, }; /** * Find an interpretation which applies to this particular level, either by * finding an exact match for the symbol and modifier combination, or a * generic XKB_KEY_NoSymbol match. */ static const struct xkb_sym_interpret * FindInterpForKey(struct xkb_keymap *keymap, const struct xkb_key *key, xkb_layout_index_t group, xkb_level_index_t level) { const xkb_keysym_t *syms; int num_syms; num_syms = xkb_keymap_key_get_syms_by_level(keymap, key->keycode, group, level, &syms); if (num_syms == 0) return NULL; /* * There may be multiple matchings interprets; we should always return * the most specific. Here we rely on compat.c to set up the * sym_interprets array from the most specific to the least specific, * such that when we find a match we return immediately. */ for (unsigned i = 0; i < keymap->num_sym_interprets; i++) { const struct xkb_sym_interpret *interp = &keymap->sym_interprets[i]; xkb_mod_mask_t mods; bool found = false; if ((num_syms > 1 || interp->sym != syms[0]) && interp->sym != XKB_KEY_NoSymbol) continue; if (interp->level_one_only && level != 0) mods = 0; else mods = key->modmap; switch (interp->match) { case MATCH_NONE: found = !(interp->mods & mods); break; case MATCH_ANY_OR_NONE: found = (!mods || (interp->mods & mods)); break; case MATCH_ANY: found = (interp->mods & mods); break; case MATCH_ALL: found = ((interp->mods & mods) == interp->mods); break; case MATCH_EXACTLY: found = (interp->mods == mods); break; } if (found) return interp; } return &default_interpret; } static bool ApplyInterpsToKey(struct xkb_keymap *keymap, struct xkb_key *key) { xkb_mod_mask_t vmodmap = 0; xkb_layout_index_t group; xkb_level_index_t level; /* If we've been told not to bind interps to this key, then don't. */ if (key->explicit & EXPLICIT_INTERP) return true; for (group = 0; group < key->num_groups; group++) { for (level = 0; level < XkbKeyNumLevels(key, group); level++) { const struct xkb_sym_interpret *interp; interp = FindInterpForKey(keymap, key, group, level); if (!interp) continue; /* Infer default key behaviours from the base level. */ if (group == 0 && level == 0) if (!(key->explicit & EXPLICIT_REPEAT) && interp->repeat) key->repeats = true; if ((group == 0 && level == 0) || !interp->level_one_only) if (interp->virtual_mod != XKB_MOD_INVALID) vmodmap |= (1u << interp->virtual_mod); if (interp->action.type != ACTION_TYPE_NONE) key->groups[group].levels[level].action = interp->action; } } if (!(key->explicit & EXPLICIT_VMODMAP)) key->vmodmap = vmodmap; return true; } /** * This collects a bunch of disparate functions which was done in the server * at various points that really should've been done within xkbcomp. Turns out * your actions and types are a lot more useful when any of your modifiers * other than Shift actually do something ... */ static bool UpdateDerivedKeymapFields(struct xkb_keymap *keymap) { struct xkb_key *key; struct xkb_mod *mod; struct xkb_led *led; unsigned int i, j; /* Find all the interprets for the key and bind them to actions, * which will also update the vmodmap. */ xkb_keys_foreach(key, keymap) if (!ApplyInterpsToKey(keymap, key)) return false; /* Update keymap->mods, the virtual -> real mod mapping. */ xkb_keys_foreach(key, keymap) xkb_mods_enumerate(i, mod, &keymap->mods) if (key->vmodmap & (1u << i)) mod->mapping |= key->modmap; /* Now update the level masks for all the types to reflect the vmods. */ for (i = 0; i < keymap->num_types; i++) { ComputeEffectiveMask(keymap, &keymap->types[i].mods); for (j = 0; j < keymap->types[i].num_entries; j++) { ComputeEffectiveMask(keymap, &keymap->types[i].entries[j].mods); ComputeEffectiveMask(keymap, &keymap->types[i].entries[j].preserve); } } /* Update action modifiers. */ xkb_keys_foreach(key, keymap) for (i = 0; i < key->num_groups; i++) for (j = 0; j < XkbKeyNumLevels(key, i); j++) UpdateActionMods(keymap, &key->groups[i].levels[j].action, key->modmap); /* Update vmod -> led maps. */ xkb_leds_foreach(led, keymap) ComputeEffectiveMask(keymap, &led->mods); /* Find maximum number of groups out of all keys in the keymap. */ xkb_keys_foreach(key, keymap) keymap->num_groups = MAX(keymap->num_groups, key->num_groups); return true; } typedef bool (*compile_file_fn)(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge); static const compile_file_fn compile_file_fns[LAST_KEYMAP_FILE_TYPE + 1] = { [FILE_TYPE_KEYCODES] = CompileKeycodes, [FILE_TYPE_TYPES] = CompileKeyTypes, [FILE_TYPE_COMPAT] = CompileCompatMap, [FILE_TYPE_SYMBOLS] = CompileSymbols, }; bool CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { log_err(ctx, "Cannot define %s in a keymap file\n", xkb_file_type_to_string(file->file_type)); continue; } if (files[file->file_type]) { log_err(ctx, "More than one %s section in keymap file; " "All sections after the first ignored\n", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, "Required section %s missing from keymap\n", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, "Compiling %s \"%s\"\n", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, "Failed to compile %s\n", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_318_0
crossvul-cpp_data_good_623_0
/* * TUN - Universal TUN/TAP device driver. * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.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. * * 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. * * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $ */ /* * Changes: * * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14 * Add TUNSETLINK ioctl to set the link encapsulation * * Mark Smith <markzzzsmith@yahoo.com.au> * Use eth_random_addr() for tap MAC address. * * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20 * Fixes in packet dropping, queue length setting and queue wakeup. * Increased default tx queue length. * Added ethtool API. * Minor cleanups * * Daniel Podlejski <underley@underley.eu.org> * Modifications for 2.3.99-pre5 kernel. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "tun" #define DRV_VERSION "1.6" #define DRV_DESCRIPTION "Universal TUN/TAP device driver" #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>" #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched/signal.h> #include <linux/major.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/miscdevice.h> #include <linux/ethtool.h> #include <linux/rtnetlink.h> #include <linux/compat.h> #include <linux/if.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/if_vlan.h> #include <linux/crc32.h> #include <linux/nsproxy.h> #include <linux/virtio_net.h> #include <linux/rcupdate.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/rtnetlink.h> #include <net/sock.h> #include <linux/seq_file.h> #include <linux/uio.h> #include <linux/skb_array.h> #include <linux/bpf.h> #include <linux/bpf_trace.h> #include <linux/uaccess.h> /* Uncomment to enable debugging */ /* #define TUN_DEBUG 1 */ #ifdef TUN_DEBUG static int debug; #define tun_debug(level, tun, fmt, args...) \ do { \ if (tun->debug) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (debug == 2) \ printk(level fmt, ##args); \ } while (0) #else #define tun_debug(level, tun, fmt, args...) \ do { \ if (0) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (0) \ printk(level fmt, ##args); \ } while (0) #endif #define TUN_HEADROOM 256 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD) /* TUN device flags */ /* IFF_ATTACH_QUEUE is never stored in device flags, * overload it to mean fasync when stored there. */ #define TUN_FASYNC IFF_ATTACH_QUEUE /* High bits in flags field are unused. */ #define TUN_VNET_LE 0x80000000 #define TUN_VNET_BE 0x40000000 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \ IFF_MULTI_QUEUE) #define GOODCOPY_LEN 128 #define FLT_EXACT_COUNT 8 struct tap_filter { unsigned int count; /* Number of addrs. Zero means disabled */ u32 mask[2]; /* Mask of the hashed addrs */ unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN]; }; /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal * to max number of VCPUs in guest. */ #define MAX_TAP_QUEUES 256 #define MAX_TAP_FLOWS 4096 #define TUN_FLOW_EXPIRE (3 * HZ) struct tun_pcpu_stats { u64 rx_packets; u64 rx_bytes; u64 tx_packets; u64 tx_bytes; struct u64_stats_sync syncp; u32 rx_dropped; u32 tx_dropped; u32 rx_frame_errors; }; /* A tun_file connects an open character device to a tuntap netdevice. It * also contains all socket related structures (except sock_fprog and tap_filter) * to serve as one transmit queue for tuntap device. The sock_fprog and * tap_filter were kept in tun_struct since they were used for filtering for the * netdevice not for a specific queue (at least I didn't see the requirement for * this). * * RCU usage: * The tun_file and tun_struct are loosely coupled, the pointer from one to the * other can only be read while rcu_read_lock or rtnl_lock is held. */ struct tun_file { struct sock sk; struct socket socket; struct socket_wq wq; struct tun_struct __rcu *tun; struct fasync_struct *fasync; /* only used for fasnyc */ unsigned int flags; union { u16 queue_index; unsigned int ifindex; }; struct list_head next; struct tun_struct *detached; struct skb_array tx_array; }; struct tun_flow_entry { struct hlist_node hash_link; struct rcu_head rcu; struct tun_struct *tun; u32 rxhash; u32 rps_rxhash; int queue_index; unsigned long updated; }; #define TUN_NUM_FLOW_ENTRIES 1024 /* Since the socket were moved to tun_file, to preserve the behavior of persist * device, socket filter, sndbuf and vnet header size were restore when the * file were attached to a persist device. */ struct tun_struct { struct tun_file __rcu *tfiles[MAX_TAP_QUEUES]; unsigned int numqueues; unsigned int flags; kuid_t owner; kgid_t group; struct net_device *dev; netdev_features_t set_features; #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \ NETIF_F_TSO6) int align; int vnet_hdr_sz; int sndbuf; struct tap_filter txflt; struct sock_fprog fprog; /* protected by rtnl lock */ bool filter_attached; #ifdef TUN_DEBUG int debug; #endif spinlock_t lock; struct hlist_head flows[TUN_NUM_FLOW_ENTRIES]; struct timer_list flow_gc_timer; unsigned long ageing_time; unsigned int numdisabled; struct list_head disabled; void *security; u32 flow_count; u32 rx_batched; struct tun_pcpu_stats __percpu *pcpu_stats; struct bpf_prog __rcu *xdp_prog; }; #ifdef CONFIG_TUN_VNET_CROSS_LE static inline bool tun_legacy_is_little_endian(struct tun_struct *tun) { return tun->flags & TUN_VNET_BE ? false : virtio_legacy_is_little_endian(); } static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp) { int be = !!(tun->flags & TUN_VNET_BE); if (put_user(be, argp)) return -EFAULT; return 0; } static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp) { int be; if (get_user(be, argp)) return -EFAULT; if (be) tun->flags |= TUN_VNET_BE; else tun->flags &= ~TUN_VNET_BE; return 0; } #else static inline bool tun_legacy_is_little_endian(struct tun_struct *tun) { return virtio_legacy_is_little_endian(); } static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp) { return -EINVAL; } static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp) { return -EINVAL; } #endif /* CONFIG_TUN_VNET_CROSS_LE */ static inline bool tun_is_little_endian(struct tun_struct *tun) { return tun->flags & TUN_VNET_LE || tun_legacy_is_little_endian(tun); } static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val) { return __virtio16_to_cpu(tun_is_little_endian(tun), val); } static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val) { return __cpu_to_virtio16(tun_is_little_endian(tun), val); } static inline u32 tun_hashfn(u32 rxhash) { return rxhash & 0x3ff; } static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash) { struct tun_flow_entry *e; hlist_for_each_entry_rcu(e, head, hash_link) { if (e->rxhash == rxhash) return e; } return NULL; } static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun, struct hlist_head *head, u32 rxhash, u16 queue_index) { struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC); if (e) { tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n", rxhash, queue_index); e->updated = jiffies; e->rxhash = rxhash; e->rps_rxhash = 0; e->queue_index = queue_index; e->tun = tun; hlist_add_head_rcu(&e->hash_link, head); ++tun->flow_count; } return e; } static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e) { tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n", e->rxhash, e->queue_index); hlist_del_rcu(&e->hash_link); kfree_rcu(e, rcu); --tun->flow_count; } static void tun_flow_flush(struct tun_struct *tun) { int i; spin_lock_bh(&tun->lock); for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) { struct tun_flow_entry *e; struct hlist_node *n; hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) tun_flow_delete(tun, e); } spin_unlock_bh(&tun->lock); } static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index) { int i; spin_lock_bh(&tun->lock); for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) { struct tun_flow_entry *e; struct hlist_node *n; hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) { if (e->queue_index == queue_index) tun_flow_delete(tun, e); } } spin_unlock_bh(&tun->lock); } static void tun_flow_cleanup(unsigned long data) { struct tun_struct *tun = (struct tun_struct *)data; unsigned long delay = tun->ageing_time; unsigned long next_timer = jiffies + delay; unsigned long count = 0; int i; tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n"); spin_lock_bh(&tun->lock); for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) { struct tun_flow_entry *e; struct hlist_node *n; hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) { unsigned long this_timer; count++; this_timer = e->updated + delay; if (time_before_eq(this_timer, jiffies)) tun_flow_delete(tun, e); else if (time_before(this_timer, next_timer)) next_timer = this_timer; } } if (count) mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer)); spin_unlock_bh(&tun->lock); } static void tun_flow_update(struct tun_struct *tun, u32 rxhash, struct tun_file *tfile) { struct hlist_head *head; struct tun_flow_entry *e; unsigned long delay = tun->ageing_time; u16 queue_index = tfile->queue_index; if (!rxhash) return; else head = &tun->flows[tun_hashfn(rxhash)]; rcu_read_lock(); /* We may get a very small possibility of OOO during switching, not * worth to optimize.*/ if (tun->numqueues == 1 || tfile->detached) goto unlock; e = tun_flow_find(head, rxhash); if (likely(e)) { /* TODO: keep queueing to old queue until it's empty? */ e->queue_index = queue_index; e->updated = jiffies; sock_rps_record_flow_hash(e->rps_rxhash); } else { spin_lock_bh(&tun->lock); if (!tun_flow_find(head, rxhash) && tun->flow_count < MAX_TAP_FLOWS) tun_flow_create(tun, head, rxhash, queue_index); if (!timer_pending(&tun->flow_gc_timer)) mod_timer(&tun->flow_gc_timer, round_jiffies_up(jiffies + delay)); spin_unlock_bh(&tun->lock); } unlock: rcu_read_unlock(); } /** * Save the hash received in the stack receive path and update the * flow_hash table accordingly. */ static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash) { if (unlikely(e->rps_rxhash != hash)) e->rps_rxhash = hash; } /* We try to identify a flow through its rxhash first. The reason that * we do not check rxq no. is because some cards(e.g 82599), chooses * the rxq based on the txq where the last packet of the flow comes. As * the userspace application move between processors, we may get a * different rxq no. here. If we could not get rxhash, then we would * hope the rxq no. may help here. */ static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { struct tun_struct *tun = netdev_priv(dev); struct tun_flow_entry *e; u32 txq = 0; u32 numqueues = 0; rcu_read_lock(); numqueues = ACCESS_ONCE(tun->numqueues); txq = __skb_get_hash_symmetric(skb); if (txq) { e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq); if (e) { tun_flow_save_rps_rxhash(e, txq); txq = e->queue_index; } else /* use multiply and shift instead of expensive divide */ txq = ((u64)txq * numqueues) >> 32; } else if (likely(skb_rx_queue_recorded(skb))) { txq = skb_get_rx_queue(skb); while (unlikely(txq >= numqueues)) txq -= numqueues; } rcu_read_unlock(); return txq; } static inline bool tun_not_capable(struct tun_struct *tun) { const struct cred *cred = current_cred(); struct net *net = dev_net(tun->dev); return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) || (gid_valid(tun->group) && !in_egroup_p(tun->group))) && !ns_capable(net->user_ns, CAP_NET_ADMIN); } static void tun_set_real_num_queues(struct tun_struct *tun) { netif_set_real_num_tx_queues(tun->dev, tun->numqueues); netif_set_real_num_rx_queues(tun->dev, tun->numqueues); } static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile) { tfile->detached = tun; list_add_tail(&tfile->next, &tun->disabled); ++tun->numdisabled; } static struct tun_struct *tun_enable_queue(struct tun_file *tfile) { struct tun_struct *tun = tfile->detached; tfile->detached = NULL; list_del_init(&tfile->next); --tun->numdisabled; return tun; } static void tun_queue_purge(struct tun_file *tfile) { struct sk_buff *skb; while ((skb = skb_array_consume(&tfile->tx_array)) != NULL) kfree_skb(skb); skb_queue_purge(&tfile->sk.sk_write_queue); skb_queue_purge(&tfile->sk.sk_error_queue); } static void __tun_detach(struct tun_file *tfile, bool clean) { struct tun_file *ntfile; struct tun_struct *tun; tun = rtnl_dereference(tfile->tun); if (tun && !tfile->detached) { u16 index = tfile->queue_index; BUG_ON(index >= tun->numqueues); rcu_assign_pointer(tun->tfiles[index], tun->tfiles[tun->numqueues - 1]); ntfile = rtnl_dereference(tun->tfiles[index]); ntfile->queue_index = index; --tun->numqueues; if (clean) { RCU_INIT_POINTER(tfile->tun, NULL); sock_put(&tfile->sk); } else tun_disable_queue(tun, tfile); synchronize_net(); tun_flow_delete_by_queue(tun, tun->numqueues + 1); /* Drop read queue */ tun_queue_purge(tfile); tun_set_real_num_queues(tun); } else if (tfile->detached && clean) { tun = tun_enable_queue(tfile); sock_put(&tfile->sk); } if (clean) { if (tun && tun->numqueues == 0 && tun->numdisabled == 0) { netif_carrier_off(tun->dev); if (!(tun->flags & IFF_PERSIST) && tun->dev->reg_state == NETREG_REGISTERED) unregister_netdevice(tun->dev); } if (tun) skb_array_cleanup(&tfile->tx_array); sock_put(&tfile->sk); } } static void tun_detach(struct tun_file *tfile, bool clean) { rtnl_lock(); __tun_detach(tfile, clean); rtnl_unlock(); } static void tun_detach_all(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); struct bpf_prog *xdp_prog = rtnl_dereference(tun->xdp_prog); struct tun_file *tfile, *tmp; int i, n = tun->numqueues; for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); BUG_ON(!tfile); tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN; tfile->socket.sk->sk_data_ready(tfile->socket.sk); RCU_INIT_POINTER(tfile->tun, NULL); --tun->numqueues; } list_for_each_entry(tfile, &tun->disabled, next) { tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN; tfile->socket.sk->sk_data_ready(tfile->socket.sk); RCU_INIT_POINTER(tfile->tun, NULL); } BUG_ON(tun->numqueues != 0); synchronize_net(); for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); /* Drop read queue */ tun_queue_purge(tfile); sock_put(&tfile->sk); } list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) { tun_enable_queue(tfile); tun_queue_purge(tfile); sock_put(&tfile->sk); } BUG_ON(tun->numdisabled != 0); if (xdp_prog) bpf_prog_put(xdp_prog); if (tun->flags & IFF_PERSIST) module_put(THIS_MODULE); } static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter) { struct tun_file *tfile = file->private_data; struct net_device *dev = tun->dev; int err; err = security_tun_dev_attach(tfile->socket.sk, tun->security); if (err < 0) goto out; err = -EINVAL; if (rtnl_dereference(tfile->tun) && !tfile->detached) goto out; err = -EBUSY; if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1) goto out; err = -E2BIG; if (!tfile->detached && tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES) goto out; err = 0; /* Re-attach the filter to persist device */ if (!skip_filter && (tun->filter_attached == true)) { lock_sock(tfile->socket.sk); err = sk_attach_filter(&tun->fprog, tfile->socket.sk); release_sock(tfile->socket.sk); if (!err) goto out; } if (!tfile->detached && skb_array_init(&tfile->tx_array, dev->tx_queue_len, GFP_KERNEL)) { err = -ENOMEM; goto out; } tfile->queue_index = tun->numqueues; tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN; rcu_assign_pointer(tfile->tun, tun); rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile); tun->numqueues++; if (tfile->detached) tun_enable_queue(tfile); else sock_hold(&tfile->sk); tun_set_real_num_queues(tun); /* device is allowed to go away first, so no need to hold extra * refcnt. */ out: return err; } static struct tun_struct *__tun_get(struct tun_file *tfile) { struct tun_struct *tun; rcu_read_lock(); tun = rcu_dereference(tfile->tun); if (tun) dev_hold(tun->dev); rcu_read_unlock(); return tun; } static struct tun_struct *tun_get(struct file *file) { return __tun_get(file->private_data); } static void tun_put(struct tun_struct *tun) { dev_put(tun->dev); } /* TAP filtering */ static void addr_hash_set(u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; mask[n >> 5] |= (1 << (n & 31)); } static unsigned int addr_hash_test(const u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; return mask[n >> 5] & (1 << (n & 31)); } static int update_filter(struct tap_filter *filter, void __user *arg) { struct { u8 u[ETH_ALEN]; } *addr; struct tun_filter uf; int err, alen, n, nexact; if (copy_from_user(&uf, arg, sizeof(uf))) return -EFAULT; if (!uf.count) { /* Disabled */ filter->count = 0; return 0; } alen = ETH_ALEN * uf.count; addr = memdup_user(arg + sizeof(uf), alen); if (IS_ERR(addr)) return PTR_ERR(addr); /* The filter is updated without holding any locks. Which is * perfectly safe. We disable it first and in the worst * case we'll accept a few undesired packets. */ filter->count = 0; wmb(); /* Use first set of addresses as an exact filter */ for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++) memcpy(filter->addr[n], addr[n].u, ETH_ALEN); nexact = n; /* Remaining multicast addresses are hashed, * unicast will leave the filter disabled. */ memset(filter->mask, 0, sizeof(filter->mask)); for (; n < uf.count; n++) { if (!is_multicast_ether_addr(addr[n].u)) { err = 0; /* no filter */ goto free_addr; } addr_hash_set(filter->mask, addr[n].u); } /* For ALLMULTI just set the mask to all ones. * This overrides the mask populated above. */ if ((uf.flags & TUN_FLT_ALLMULTI)) memset(filter->mask, ~0, sizeof(filter->mask)); /* Now enable the filter */ wmb(); filter->count = nexact; /* Return the number of exact filters */ err = nexact; free_addr: kfree(addr); return err; } /* Returns: 0 - drop, !=0 - accept */ static int run_filter(struct tap_filter *filter, const struct sk_buff *skb) { /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect * at this point. */ struct ethhdr *eh = (struct ethhdr *) skb->data; int i; /* Exact match */ for (i = 0; i < filter->count; i++) if (ether_addr_equal(eh->h_dest, filter->addr[i])) return 1; /* Inexact match (multicast only) */ if (is_multicast_ether_addr(eh->h_dest)) return addr_hash_test(filter->mask, eh->h_dest); return 0; } /* * Checks whether the packet is accepted or not. * Returns: 0 - drop, !=0 - accept */ static int check_filter(struct tap_filter *filter, const struct sk_buff *skb) { if (!filter->count) return 1; return run_filter(filter, skb); } /* Network device part of the driver */ static const struct ethtool_ops tun_ethtool_ops; /* Net device detach from fd. */ static void tun_net_uninit(struct net_device *dev) { tun_detach_all(dev); } /* Net device open. */ static int tun_net_open(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); int i; netif_tx_start_all_queues(dev); for (i = 0; i < tun->numqueues; i++) { struct tun_file *tfile; tfile = rtnl_dereference(tun->tfiles[i]); tfile->socket.sk->sk_write_space(tfile->socket.sk); } return 0; } /* Net device close. */ static int tun_net_close(struct net_device *dev) { netif_tx_stop_all_queues(dev); return 0; } /* Net device start xmit */ static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); int txq = skb->queue_mapping; struct tun_file *tfile; u32 numqueues = 0; rcu_read_lock(); tfile = rcu_dereference(tun->tfiles[txq]); numqueues = ACCESS_ONCE(tun->numqueues); /* Drop packet if interface is not attached */ if (txq >= numqueues) goto drop; #ifdef CONFIG_RPS if (numqueues == 1 && static_key_false(&rps_needed)) { /* Select queue was not called for the skbuff, so we extract the * RPS hash and save it into the flow_table here. */ __u32 rxhash; rxhash = __skb_get_hash_symmetric(skb); if (rxhash) { struct tun_flow_entry *e; e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash); if (e) tun_flow_save_rps_rxhash(e, rxhash); } } #endif tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len); BUG_ON(!tfile); /* Drop if the filter does not like it. * This is a noop if the filter is disabled. * Filter can be enabled only for the TAP devices. */ if (!check_filter(&tun->txflt, skb)) goto drop; if (tfile->socket.sk->sk_filter && sk_filter(tfile->socket.sk, skb)) goto drop; if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) goto drop; skb_tx_timestamp(skb); /* Orphan the skb - required as we might hang on to it * for indefinite time. */ skb_orphan(skb); nf_reset(skb); if (skb_array_produce(&tfile->tx_array, skb)) goto drop; /* Notify and wake up reader process */ if (tfile->flags & TUN_FASYNC) kill_fasync(&tfile->fasync, SIGIO, POLL_IN); tfile->socket.sk->sk_data_ready(tfile->socket.sk); rcu_read_unlock(); return NETDEV_TX_OK; drop: this_cpu_inc(tun->pcpu_stats->tx_dropped); skb_tx_error(skb); kfree_skb(skb); rcu_read_unlock(); return NET_XMIT_DROP; } static void tun_net_mclist(struct net_device *dev) { /* * This callback is supposed to deal with mc filter in * _rx_ path and has nothing to do with the _tx_ path. * In rx path we always accept everything userspace gives us. */ } static netdev_features_t tun_net_fix_features(struct net_device *dev, netdev_features_t features) { struct tun_struct *tun = netdev_priv(dev); return (features & tun->set_features) | (features & ~TUN_USER_FEATURES); } #ifdef CONFIG_NET_POLL_CONTROLLER static void tun_poll_controller(struct net_device *dev) { /* * Tun only receives frames when: * 1) the char device endpoint gets data from user space * 2) the tun socket gets a sendmsg call from user space * Since both of those are synchronous operations, we are guaranteed * never to have pending data when we poll for it * so there is nothing to do here but return. * We need this though so netpoll recognizes us as an interface that * supports polling, which enables bridge devices in virt setups to * still use netconsole */ return; } #endif static void tun_set_headroom(struct net_device *dev, int new_hr) { struct tun_struct *tun = netdev_priv(dev); if (new_hr < NET_SKB_PAD) new_hr = NET_SKB_PAD; tun->align = new_hr; } static void tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0; struct tun_struct *tun = netdev_priv(dev); struct tun_pcpu_stats *p; int i; for_each_possible_cpu(i) { u64 rxpackets, rxbytes, txpackets, txbytes; unsigned int start; p = per_cpu_ptr(tun->pcpu_stats, i); do { start = u64_stats_fetch_begin(&p->syncp); rxpackets = p->rx_packets; rxbytes = p->rx_bytes; txpackets = p->tx_packets; txbytes = p->tx_bytes; } while (u64_stats_fetch_retry(&p->syncp, start)); stats->rx_packets += rxpackets; stats->rx_bytes += rxbytes; stats->tx_packets += txpackets; stats->tx_bytes += txbytes; /* u32 counters */ rx_dropped += p->rx_dropped; rx_frame_errors += p->rx_frame_errors; tx_dropped += p->tx_dropped; } stats->rx_dropped = rx_dropped; stats->rx_frame_errors = rx_frame_errors; stats->tx_dropped = tx_dropped; } static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog, struct netlink_ext_ack *extack) { struct tun_struct *tun = netdev_priv(dev); struct bpf_prog *old_prog; old_prog = rtnl_dereference(tun->xdp_prog); rcu_assign_pointer(tun->xdp_prog, prog); if (old_prog) bpf_prog_put(old_prog); return 0; } static u32 tun_xdp_query(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); const struct bpf_prog *xdp_prog; xdp_prog = rtnl_dereference(tun->xdp_prog); if (xdp_prog) return xdp_prog->aux->id; return 0; } static int tun_xdp(struct net_device *dev, struct netdev_xdp *xdp) { switch (xdp->command) { case XDP_SETUP_PROG: return tun_xdp_set(dev, xdp->prog, xdp->extack); case XDP_QUERY_PROG: xdp->prog_id = tun_xdp_query(dev); xdp->prog_attached = !!xdp->prog_id; return 0; default: return -EINVAL; } } static const struct net_device_ops tun_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_fix_features = tun_net_fix_features, .ndo_select_queue = tun_select_queue, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif .ndo_set_rx_headroom = tun_set_headroom, .ndo_get_stats64 = tun_net_get_stats64, }; static const struct net_device_ops tap_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_fix_features = tun_net_fix_features, .ndo_set_rx_mode = tun_net_mclist, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, .ndo_select_queue = tun_select_queue, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif .ndo_features_check = passthru_features_check, .ndo_set_rx_headroom = tun_set_headroom, .ndo_get_stats64 = tun_net_get_stats64, .ndo_xdp = tun_xdp, }; static void tun_flow_init(struct tun_struct *tun) { int i; for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) INIT_HLIST_HEAD(&tun->flows[i]); tun->ageing_time = TUN_FLOW_EXPIRE; setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun); mod_timer(&tun->flow_gc_timer, round_jiffies_up(jiffies + tun->ageing_time)); } static void tun_flow_uninit(struct tun_struct *tun) { del_timer_sync(&tun->flow_gc_timer); tun_flow_flush(tun); } #define MIN_MTU 68 #define MAX_MTU 65535 /* Initialize net device. */ static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; break; case IFF_TAP: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; dev->priv_flags |= IFF_LIVE_ADDR_CHANGE; eth_hw_addr_random(dev); break; } dev->min_mtu = MIN_MTU; dev->max_mtu = MAX_MTU - dev->hard_header_len; } /* Character device part */ /* Poll */ static unsigned int tun_chr_poll(struct file *file, poll_table *wait) { struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); struct sock *sk; unsigned int mask = 0; if (!tun) return POLLERR; sk = tfile->socket.sk; tun_debug(KERN_INFO, tun, "tun_chr_poll\n"); poll_wait(file, sk_sleep(sk), wait); if (!skb_array_empty(&tfile->tx_array)) mask |= POLLIN | POLLRDNORM; if (tun->dev->flags & IFF_UP && (sock_writeable(sk) || (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) && sock_writeable(sk)))) mask |= POLLOUT | POLLWRNORM; if (tun->dev->reg_state != NETREG_REGISTERED) mask = POLLERR; tun_put(tun); return mask; } /* prepad is the amount to reserve at front. len is length after that. * linear is a hint as to how much to copy (usually headers). */ static struct sk_buff *tun_alloc_skb(struct tun_file *tfile, size_t prepad, size_t len, size_t linear, int noblock) { struct sock *sk = tfile->socket.sk; struct sk_buff *skb; int err; /* Under a page? Don't bother with paged skb. */ if (prepad + len < PAGE_SIZE || !linear) linear = len; skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock, &err, 0); if (!skb) return ERR_PTR(err); skb_reserve(skb, prepad); skb_put(skb, linear); skb->data_len = len - linear; skb->len += len - linear; return skb; } static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile, struct sk_buff *skb, int more) { struct sk_buff_head *queue = &tfile->sk.sk_write_queue; struct sk_buff_head process_queue; u32 rx_batched = tun->rx_batched; bool rcv = false; if (!rx_batched || (!more && skb_queue_empty(queue))) { local_bh_disable(); netif_receive_skb(skb); local_bh_enable(); return; } spin_lock(&queue->lock); if (!more || skb_queue_len(queue) == rx_batched) { __skb_queue_head_init(&process_queue); skb_queue_splice_tail_init(queue, &process_queue); rcv = true; } else { __skb_queue_tail(queue, skb); } spin_unlock(&queue->lock); if (rcv) { struct sk_buff *nskb; local_bh_disable(); while ((nskb = __skb_dequeue(&process_queue))) netif_receive_skb(nskb); netif_receive_skb(skb); local_bh_enable(); } } static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile, int len, int noblock, bool zerocopy) { if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) return false; if (tfile->socket.sk->sk_sndbuf != INT_MAX) return false; if (!noblock) return false; if (zerocopy) return false; if (SKB_DATA_ALIGN(len + TUN_RX_PAD) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE) return false; return true; } static struct sk_buff *tun_build_skb(struct tun_struct *tun, struct tun_file *tfile, struct iov_iter *from, struct virtio_net_hdr *hdr, int len, int *skb_xdp) { struct page_frag *alloc_frag = &current->task_frag; struct sk_buff *skb; struct bpf_prog *xdp_prog; int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); unsigned int delta = 0; char *buf; size_t copied; bool xdp_xmit = false; int err, pad = TUN_RX_PAD; rcu_read_lock(); xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog) pad += TUN_HEADROOM; buflen += SKB_DATA_ALIGN(len + pad); rcu_read_unlock(); if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL))) return ERR_PTR(-ENOMEM); buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset; copied = copy_page_from_iter(alloc_frag->page, alloc_frag->offset + pad, len, from); if (copied != len) return ERR_PTR(-EFAULT); /* There's a small window that XDP may be set after the check * of xdp_prog above, this should be rare and for simplicity * we do XDP on skb in case the headroom is not enough. */ if (hdr->gso_type || !xdp_prog) *skb_xdp = 1; else *skb_xdp = 0; rcu_read_lock(); xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog && !*skb_xdp) { struct xdp_buff xdp; void *orig_data; u32 act; xdp.data_hard_start = buf; xdp.data = buf + pad; xdp.data_end = xdp.data + len; orig_data = xdp.data; act = bpf_prog_run_xdp(xdp_prog, &xdp); switch (act) { case XDP_REDIRECT: get_page(alloc_frag->page); alloc_frag->offset += buflen; err = xdp_do_redirect(tun->dev, &xdp, xdp_prog); if (err) goto err_redirect; return NULL; case XDP_TX: xdp_xmit = true; /* fall through */ case XDP_PASS: delta = orig_data - xdp.data; break; default: bpf_warn_invalid_xdp_action(act); /* fall through */ case XDP_ABORTED: trace_xdp_exception(tun->dev, xdp_prog, act); /* fall through */ case XDP_DROP: goto err_xdp; } } skb = build_skb(buf, buflen); if (!skb) { rcu_read_unlock(); return ERR_PTR(-ENOMEM); } skb_reserve(skb, pad - delta); skb_put(skb, len + delta); get_page(alloc_frag->page); alloc_frag->offset += buflen; if (xdp_xmit) { skb->dev = tun->dev; generic_xdp_tx(skb, xdp_prog); rcu_read_lock(); return NULL; } rcu_read_unlock(); return skb; err_redirect: put_page(alloc_frag->page); err_xdp: rcu_read_unlock(); this_cpu_inc(tun->pcpu_stats->rx_dropped); return NULL; } /* Get packet from user space buffer */ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, void *msg_control, struct iov_iter *from, int noblock, bool more) { struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) }; struct sk_buff *skb; size_t total_len = iov_iter_count(from); size_t len = total_len, align = tun->align, linear; struct virtio_net_hdr gso = { 0 }; struct tun_pcpu_stats *stats; int good_linear; int copylen; bool zerocopy = false; int err; u32 rxhash; int skb_xdp = 1; if (!(tun->dev->flags & IFF_UP)) return -EIO; if (!(tun->flags & IFF_NO_PI)) { if (len < sizeof(pi)) return -EINVAL; len -= sizeof(pi); if (!copy_from_iter_full(&pi, sizeof(pi), from)) return -EFAULT; } if (tun->flags & IFF_VNET_HDR) { int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz); if (len < vnet_hdr_sz) return -EINVAL; len -= vnet_hdr_sz; if (!copy_from_iter_full(&gso, sizeof(gso), from)) return -EFAULT; if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len)) gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2); if (tun16_to_cpu(tun, gso.hdr_len) > len) return -EINVAL; iov_iter_advance(from, vnet_hdr_sz - sizeof(gso)); } if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) { align += NET_IP_ALIGN; if (unlikely(len < ETH_HLEN || (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN))) return -EINVAL; } good_linear = SKB_MAX_HEAD(align); if (msg_control) { struct iov_iter i = *from; /* There are 256 bytes to be copied in skb, so there is * enough room for skb expand head in case it is used. * The rest of the buffer is mapped from userspace. */ copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN; if (copylen > good_linear) copylen = good_linear; linear = copylen; iov_iter_advance(&i, copylen); if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS) zerocopy = true; } if (tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) { /* For the packet that is not easy to be processed * (e.g gso or jumbo packet), we will do it at after * skb was created with generic XDP routine. */ skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp); if (IS_ERR(skb)) { this_cpu_inc(tun->pcpu_stats->rx_dropped); return PTR_ERR(skb); } if (!skb) return total_len; } else { if (!zerocopy) { copylen = len; if (tun16_to_cpu(tun, gso.hdr_len) > good_linear) linear = good_linear; else linear = tun16_to_cpu(tun, gso.hdr_len); } skb = tun_alloc_skb(tfile, align, copylen, linear, noblock); if (IS_ERR(skb)) { if (PTR_ERR(skb) != -EAGAIN) this_cpu_inc(tun->pcpu_stats->rx_dropped); return PTR_ERR(skb); } if (zerocopy) err = zerocopy_sg_from_iter(skb, from); else err = skb_copy_datagram_from_iter(skb, 0, from, len); if (err) { this_cpu_inc(tun->pcpu_stats->rx_dropped); kfree_skb(skb); return -EFAULT; } } if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) { this_cpu_inc(tun->pcpu_stats->rx_frame_errors); kfree_skb(skb); return -EINVAL; } switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: if (tun->flags & IFF_NO_PI) { u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0; switch (ip_version) { case 4: pi.proto = htons(ETH_P_IP); break; case 6: pi.proto = htons(ETH_P_IPV6); break; default: this_cpu_inc(tun->pcpu_stats->rx_dropped); kfree_skb(skb); return -EINVAL; } } skb_reset_mac_header(skb); skb->protocol = pi.proto; skb->dev = tun->dev; break; case IFF_TAP: skb->protocol = eth_type_trans(skb, tun->dev); break; } /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; } else if (msg_control) { struct ubuf_info *uarg = msg_control; uarg->callback(uarg, false); } skb_reset_network_header(skb); skb_probe_transport_header(skb, 0); if (skb_xdp) { struct bpf_prog *xdp_prog; int ret; rcu_read_lock(); xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog) { ret = do_xdp_generic(xdp_prog, skb); if (ret != XDP_PASS) { rcu_read_unlock(); return total_len; } } rcu_read_unlock(); } rxhash = __skb_get_hash_symmetric(skb); #ifndef CONFIG_4KSTACKS tun_rx_batched(tun, tfile, skb, more); #else netif_rx_ni(skb); #endif stats = get_cpu_ptr(tun->pcpu_stats); u64_stats_update_begin(&stats->syncp); stats->rx_packets++; stats->rx_bytes += len; u64_stats_update_end(&stats->syncp); put_cpu_ptr(stats); tun_flow_update(tun, rxhash, tfile); return total_len; } static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct tun_struct *tun = tun_get(file); struct tun_file *tfile = file->private_data; ssize_t result; if (!tun) return -EBADFD; result = tun_get_user(tun, tfile, NULL, from, file->f_flags & O_NONBLOCK, false); tun_put(tun); return result; } /* Put packet to the user space buffer */ static ssize_t tun_put_user(struct tun_struct *tun, struct tun_file *tfile, struct sk_buff *skb, struct iov_iter *iter) { struct tun_pi pi = { 0, skb->protocol }; struct tun_pcpu_stats *stats; ssize_t total; int vlan_offset = 0; int vlan_hlen = 0; int vnet_hdr_sz = 0; if (skb_vlan_tag_present(skb)) vlan_hlen = VLAN_HLEN; if (tun->flags & IFF_VNET_HDR) vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz); total = skb->len + vlan_hlen + vnet_hdr_sz; if (!(tun->flags & IFF_NO_PI)) { if (iov_iter_count(iter) < sizeof(pi)) return -EINVAL; total += sizeof(pi); if (iov_iter_count(iter) < total) { /* Packet will be striped */ pi.flags |= TUN_PKT_STRIP; } if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi)) return -EFAULT; } if (vnet_hdr_sz) { struct virtio_net_hdr gso; if (iov_iter_count(iter) < vnet_hdr_sz) return -EINVAL; if (virtio_net_hdr_from_skb(skb, &gso, tun_is_little_endian(tun), true)) { struct skb_shared_info *sinfo = skb_shinfo(skb); pr_err("unexpected GSO type: " "0x%x, gso_size %d, hdr_len %d\n", sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size), tun16_to_cpu(tun, gso.hdr_len)); print_hex_dump(KERN_ERR, "tun: ", DUMP_PREFIX_NONE, 16, 1, skb->head, min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true); WARN_ON_ONCE(1); return -EINVAL; } if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso)) return -EFAULT; iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso)); } if (vlan_hlen) { int ret; struct { __be16 h_vlan_proto; __be16 h_vlan_TCI; } veth; veth.h_vlan_proto = skb->vlan_proto; veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb)); vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto); ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset); if (ret || !iov_iter_count(iter)) goto done; ret = copy_to_iter(&veth, sizeof(veth), iter); if (ret != sizeof(veth) || !iov_iter_count(iter)) goto done; } skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset); done: /* caller is in process context, */ stats = get_cpu_ptr(tun->pcpu_stats); u64_stats_update_begin(&stats->syncp); stats->tx_packets++; stats->tx_bytes += skb->len + vlan_hlen; u64_stats_update_end(&stats->syncp); put_cpu_ptr(tun->pcpu_stats); return total; } static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock, int *err) { DECLARE_WAITQUEUE(wait, current); struct sk_buff *skb = NULL; int error = 0; skb = skb_array_consume(&tfile->tx_array); if (skb) goto out; if (noblock) { error = -EAGAIN; goto out; } add_wait_queue(&tfile->wq.wait, &wait); current->state = TASK_INTERRUPTIBLE; while (1) { skb = skb_array_consume(&tfile->tx_array); if (skb) break; if (signal_pending(current)) { error = -ERESTARTSYS; break; } if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) { error = -EFAULT; break; } schedule(); } current->state = TASK_RUNNING; remove_wait_queue(&tfile->wq.wait, &wait); out: *err = error; return skb; } static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile, struct iov_iter *to, int noblock, struct sk_buff *skb) { ssize_t ret; int err; tun_debug(KERN_INFO, tun, "tun_do_read\n"); if (!iov_iter_count(to)) return 0; if (!skb) { /* Read frames from ring */ skb = tun_ring_recv(tfile, noblock, &err); if (!skb) return err; } ret = tun_put_user(tun, tfile, skb, to); if (unlikely(ret < 0)) kfree_skb(skb); else consume_skb(skb); return ret; } static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); ssize_t len = iov_iter_count(to), ret; if (!tun) return -EBADFD; ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL); ret = min_t(ssize_t, ret, len); if (ret > 0) iocb->ki_pos = ret; tun_put(tun); return ret; } static void tun_free_netdev(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); BUG_ON(!(list_empty(&tun->disabled))); free_percpu(tun->pcpu_stats); tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); } static void tun_setup(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); tun->owner = INVALID_UID; tun->group = INVALID_GID; dev->ethtool_ops = &tun_ethtool_ops; dev->needs_free_netdev = true; dev->priv_destructor = tun_free_netdev; /* We prefer our own queue length */ dev->tx_queue_len = TUN_READQ_SIZE; } /* Trivial set of netlink ops to allow deleting tun or tap * device with netlink. */ static int tun_validate(struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { return -EINVAL; } static struct rtnl_link_ops tun_link_ops __read_mostly = { .kind = DRV_NAME, .priv_size = sizeof(struct tun_struct), .setup = tun_setup, .validate = tun_validate, }; static void tun_sock_write_space(struct sock *sk) { struct tun_file *tfile; wait_queue_head_t *wqueue; if (!sock_writeable(sk)) return; if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags)) return; wqueue = sk_sleep(sk); if (wqueue && waitqueue_active(wqueue)) wake_up_interruptible_sync_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND); tfile = container_of(sk, struct tun_file, sk); kill_fasync(&tfile->fasync, SIGIO, POLL_OUT); } static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len) { int ret; struct tun_file *tfile = container_of(sock, struct tun_file, socket); struct tun_struct *tun = __tun_get(tfile); if (!tun) return -EBADFD; ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter, m->msg_flags & MSG_DONTWAIT, m->msg_flags & MSG_MORE); tun_put(tun); return ret; } static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len, int flags) { struct tun_file *tfile = container_of(sock, struct tun_file, socket); struct tun_struct *tun = __tun_get(tfile); int ret; if (!tun) return -EBADFD; if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) { ret = -EINVAL; goto out; } if (flags & MSG_ERRQUEUE) { ret = sock_recv_errqueue(sock->sk, m, total_len, SOL_PACKET, TUN_TX_TIMESTAMP); goto out; } ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, m->msg_control); if (ret > (ssize_t)total_len) { m->msg_flags |= MSG_TRUNC; ret = flags & MSG_TRUNC ? ret : total_len; } out: tun_put(tun); return ret; } static int tun_peek_len(struct socket *sock) { struct tun_file *tfile = container_of(sock, struct tun_file, socket); struct tun_struct *tun; int ret = 0; tun = __tun_get(tfile); if (!tun) return 0; ret = skb_array_peek_len(&tfile->tx_array); tun_put(tun); return ret; } /* Ops structure to mimic raw sockets with tun */ static const struct proto_ops tun_socket_ops = { .peek_len = tun_peek_len, .sendmsg = tun_sendmsg, .recvmsg = tun_recvmsg, }; static struct proto tun_proto = { .name = "tun", .owner = THIS_MODULE, .obj_size = sizeof(struct tun_file), }; static int tun_flags(struct tun_struct *tun) { return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP); } static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "0x%x\n", tun_flags(tun)); } static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return uid_valid(tun->owner)? sprintf(buf, "%u\n", from_kuid_munged(current_user_ns(), tun->owner)): sprintf(buf, "-1\n"); } static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return gid_valid(tun->group) ? sprintf(buf, "%u\n", from_kgid_munged(current_user_ns(), tun->group)): sprintf(buf, "-1\n"); } static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL); static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL); static DEVICE_ATTR(group, 0444, tun_show_group, NULL); static struct attribute *tun_dev_attrs[] = { &dev_attr_tun_flags.attr, &dev_attr_owner.attr, &dev_attr_group.attr, NULL }; static const struct attribute_group tun_attr_group = { .attrs = tun_dev_attrs }; static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } static void tun_get_iff(struct net *net, struct tun_struct *tun, struct ifreq *ifr) { tun_debug(KERN_INFO, tun, "tun_get_iff\n"); strcpy(ifr->ifr_name, tun->dev->name); ifr->ifr_flags = tun_flags(tun); } /* This is like a cut-down ethtool ops, except done via tun fd so no * privs required. */ static int set_offload(struct tun_struct *tun, unsigned long arg) { netdev_features_t features = 0; if (arg & TUN_F_CSUM) { features |= NETIF_F_HW_CSUM; arg &= ~TUN_F_CSUM; if (arg & (TUN_F_TSO4|TUN_F_TSO6)) { if (arg & TUN_F_TSO_ECN) { features |= NETIF_F_TSO_ECN; arg &= ~TUN_F_TSO_ECN; } if (arg & TUN_F_TSO4) features |= NETIF_F_TSO; if (arg & TUN_F_TSO6) features |= NETIF_F_TSO6; arg &= ~(TUN_F_TSO4|TUN_F_TSO6); } } /* This gives the user a way to test for new features in future by * trying to set them. */ if (arg) return -EINVAL; tun->set_features = features; tun->dev->wanted_features &= ~TUN_USER_FEATURES; tun->dev->wanted_features |= features; netdev_update_features(tun->dev); return 0; } static void tun_detach_filter(struct tun_struct *tun, int n) { int i; struct tun_file *tfile; for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); lock_sock(tfile->socket.sk); sk_detach_filter(tfile->socket.sk); release_sock(tfile->socket.sk); } tun->filter_attached = false; } static int tun_attach_filter(struct tun_struct *tun) { int i, ret = 0; struct tun_file *tfile; for (i = 0; i < tun->numqueues; i++) { tfile = rtnl_dereference(tun->tfiles[i]); lock_sock(tfile->socket.sk); ret = sk_attach_filter(&tun->fprog, tfile->socket.sk); release_sock(tfile->socket.sk); if (ret) { tun_detach_filter(tun, i); return ret; } } tun->filter_attached = true; return ret; } static void tun_set_sndbuf(struct tun_struct *tun) { struct tun_file *tfile; int i; for (i = 0; i < tun->numqueues; i++) { tfile = rtnl_dereference(tun->tfiles[i]); tfile->socket.sk->sk_sndbuf = tun->sndbuf; } } static int tun_set_queue(struct file *file, struct ifreq *ifr) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; int ret = 0; rtnl_lock(); if (ifr->ifr_flags & IFF_ATTACH_QUEUE) { tun = tfile->detached; if (!tun) { ret = -EINVAL; goto unlock; } ret = security_tun_dev_attach_queue(tun->security); if (ret < 0) goto unlock; ret = tun_attach(tun, file, false); } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) { tun = rtnl_dereference(tfile->tun); if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached) ret = -EINVAL; else __tun_detach(tfile, false); } else ret = -EINVAL; unlock: rtnl_unlock(); return ret; } static long __tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg, int ifreq_len) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; void __user* argp = (void __user*)arg; struct ifreq ifr; kuid_t owner; kgid_t group; int sndbuf; int vnet_hdr_sz; unsigned int ifindex; int le; int ret; if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) { if (copy_from_user(&ifr, argp, ifreq_len)) return -EFAULT; } else { memset(&ifr, 0, sizeof(ifr)); } if (cmd == TUNGETFEATURES) { /* Currently this just means: "what IFF flags are valid?". * This is needed because we never checked for invalid flags on * TUNSETIFF. */ return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES, (unsigned int __user*)argp); } else if (cmd == TUNSETQUEUE) return tun_set_queue(file, &ifr); ret = 0; rtnl_lock(); tun = __tun_get(tfile); if (cmd == TUNSETIFF) { ret = -EEXIST; if (tun) goto unlock; ifr.ifr_name[IFNAMSIZ-1] = '\0'; ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr); if (ret) goto unlock; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; goto unlock; } if (cmd == TUNSETIFINDEX) { ret = -EPERM; if (tun) goto unlock; ret = -EFAULT; if (copy_from_user(&ifindex, argp, sizeof(ifindex))) goto unlock; ret = 0; tfile->ifindex = ifindex; goto unlock; } ret = -EBADFD; if (!tun) goto unlock; tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd); ret = 0; switch (cmd) { case TUNGETIFF: tun_get_iff(current->nsproxy->net_ns, tun, &ifr); if (tfile->detached) ifr.ifr_flags |= IFF_DETACH_QUEUE; if (!tfile->socket.sk->sk_filter) ifr.ifr_flags |= IFF_NOFILTER; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case TUNSETNOCSUM: /* Disable/Enable checksum */ /* [unimplemented] */ tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n", arg ? "disabled" : "enabled"); break; case TUNSETPERSIST: /* Disable/Enable persist mode. Keep an extra reference to the * module to prevent the module being unprobed. */ if (arg && !(tun->flags & IFF_PERSIST)) { tun->flags |= IFF_PERSIST; __module_get(THIS_MODULE); } if (!arg && (tun->flags & IFF_PERSIST)) { tun->flags &= ~IFF_PERSIST; module_put(THIS_MODULE); } tun_debug(KERN_INFO, tun, "persist %s\n", arg ? "enabled" : "disabled"); break; case TUNSETOWNER: /* Set owner of the device */ owner = make_kuid(current_user_ns(), arg); if (!uid_valid(owner)) { ret = -EINVAL; break; } tun->owner = owner; tun_debug(KERN_INFO, tun, "owner set to %u\n", from_kuid(&init_user_ns, tun->owner)); break; case TUNSETGROUP: /* Set group of the device */ group = make_kgid(current_user_ns(), arg); if (!gid_valid(group)) { ret = -EINVAL; break; } tun->group = group; tun_debug(KERN_INFO, tun, "group set to %u\n", from_kgid(&init_user_ns, tun->group)); break; case TUNSETLINK: /* Only allow setting the type when the interface is down */ if (tun->dev->flags & IFF_UP) { tun_debug(KERN_INFO, tun, "Linktype set failed because interface is up\n"); ret = -EBUSY; } else { tun->dev->type = (int) arg; tun_debug(KERN_INFO, tun, "linktype set to %d\n", tun->dev->type); ret = 0; } break; #ifdef TUN_DEBUG case TUNSETDEBUG: tun->debug = arg; break; #endif case TUNSETOFFLOAD: ret = set_offload(tun, arg); break; case TUNSETTXFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = update_filter(&tun->txflt, (void __user *)arg); break; case SIOCGIFHWADDR: /* Get hw address */ memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN); ifr.ifr_hwaddr.sa_family = tun->dev->type; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case SIOCSIFHWADDR: /* Set hw address */ tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n", ifr.ifr_hwaddr.sa_data); ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr); break; case TUNGETSNDBUF: sndbuf = tfile->socket.sk->sk_sndbuf; if (copy_to_user(argp, &sndbuf, sizeof(sndbuf))) ret = -EFAULT; break; case TUNSETSNDBUF: if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) { ret = -EFAULT; break; } tun->sndbuf = sndbuf; tun_set_sndbuf(tun); break; case TUNGETVNETHDRSZ: vnet_hdr_sz = tun->vnet_hdr_sz; if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz))) ret = -EFAULT; break; case TUNSETVNETHDRSZ: if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) { ret = -EFAULT; break; } if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) { ret = -EINVAL; break; } tun->vnet_hdr_sz = vnet_hdr_sz; break; case TUNGETVNETLE: le = !!(tun->flags & TUN_VNET_LE); if (put_user(le, (int __user *)argp)) ret = -EFAULT; break; case TUNSETVNETLE: if (get_user(le, (int __user *)argp)) { ret = -EFAULT; break; } if (le) tun->flags |= TUN_VNET_LE; else tun->flags &= ~TUN_VNET_LE; break; case TUNGETVNETBE: ret = tun_get_vnet_be(tun, argp); break; case TUNSETVNETBE: ret = tun_set_vnet_be(tun, argp); break; case TUNATTACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = -EFAULT; if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog))) break; ret = tun_attach_filter(tun); break; case TUNDETACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = 0; tun_detach_filter(tun, tun->numqueues); break; case TUNGETFILTER: ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = -EFAULT; if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog))) break; ret = 0; break; default: ret = -EINVAL; break; } unlock: rtnl_unlock(); if (tun) tun_put(tun); return ret; } static long tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq)); } #ifdef CONFIG_COMPAT static long tun_chr_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case TUNSETIFF: case TUNGETIFF: case TUNSETTXFILTER: case TUNGETSNDBUF: case TUNSETSNDBUF: case SIOCGIFHWADDR: case SIOCSIFHWADDR: arg = (unsigned long)compat_ptr(arg); break; default: arg = (compat_ulong_t)arg; break; } /* * compat_ifreq is shorter than ifreq, so we must not access beyond * the end of that structure. All fields that are used in this * driver are compatible though, we don't need to convert the * contents. */ return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq)); } #endif /* CONFIG_COMPAT */ static int tun_chr_fasync(int fd, struct file *file, int on) { struct tun_file *tfile = file->private_data; int ret; if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0) goto out; if (on) { __f_setown(file, task_pid(current), PIDTYPE_PID, 0); tfile->flags |= TUN_FASYNC; } else tfile->flags &= ~TUN_FASYNC; ret = 0; out: return ret; } static int tun_chr_open(struct inode *inode, struct file * file) { struct net *net = current->nsproxy->net_ns; struct tun_file *tfile; DBG1(KERN_INFO, "tunX: tun_chr_open\n"); tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL, &tun_proto, 0); if (!tfile) return -ENOMEM; RCU_INIT_POINTER(tfile->tun, NULL); tfile->flags = 0; tfile->ifindex = 0; init_waitqueue_head(&tfile->wq.wait); RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq); tfile->socket.file = file; tfile->socket.ops = &tun_socket_ops; sock_init_data(&tfile->socket, &tfile->sk); tfile->sk.sk_write_space = tun_sock_write_space; tfile->sk.sk_sndbuf = INT_MAX; file->private_data = tfile; INIT_LIST_HEAD(&tfile->next); sock_set_flag(&tfile->sk, SOCK_ZEROCOPY); return 0; } static int tun_chr_close(struct inode *inode, struct file *file) { struct tun_file *tfile = file->private_data; tun_detach(tfile, true); return 0; } #ifdef CONFIG_PROC_FS static void tun_chr_show_fdinfo(struct seq_file *m, struct file *f) { struct tun_struct *tun; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); rtnl_lock(); tun = tun_get(f); if (tun) tun_get_iff(current->nsproxy->net_ns, tun, &ifr); rtnl_unlock(); if (tun) tun_put(tun); seq_printf(m, "iff:\t%s\n", ifr.ifr_name); } #endif static const struct file_operations tun_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read_iter = tun_chr_read_iter, .write_iter = tun_chr_write_iter, .poll = tun_chr_poll, .unlocked_ioctl = tun_chr_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = tun_chr_compat_ioctl, #endif .open = tun_chr_open, .release = tun_chr_close, .fasync = tun_chr_fasync, #ifdef CONFIG_PROC_FS .show_fdinfo = tun_chr_show_fdinfo, #endif }; static struct miscdevice tun_miscdev = { .minor = TUN_MINOR, .name = "tun", .nodename = "net/tun", .fops = &tun_fops, }; /* ethtool interface */ static int tun_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { ethtool_link_ksettings_zero_link_mode(cmd, supported); ethtool_link_ksettings_zero_link_mode(cmd, advertising); cmd->base.speed = SPEED_10; cmd->base.duplex = DUPLEX_FULL; cmd->base.port = PORT_TP; cmd->base.phy_address = 0; cmd->base.autoneg = AUTONEG_DISABLE; return 0; } static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct tun_struct *tun = netdev_priv(dev); strlcpy(info->driver, DRV_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_VERSION, sizeof(info->version)); switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: strlcpy(info->bus_info, "tun", sizeof(info->bus_info)); break; case IFF_TAP: strlcpy(info->bus_info, "tap", sizeof(info->bus_info)); break; } } static u32 tun_get_msglevel(struct net_device *dev) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); return tun->debug; #else return -EOPNOTSUPP; #endif } static void tun_set_msglevel(struct net_device *dev, u32 value) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); tun->debug = value; #endif } static int tun_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tun_struct *tun = netdev_priv(dev); ec->rx_max_coalesced_frames = tun->rx_batched; return 0; } static int tun_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tun_struct *tun = netdev_priv(dev); if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT) tun->rx_batched = NAPI_POLL_WEIGHT; else tun->rx_batched = ec->rx_max_coalesced_frames; return 0; } static const struct ethtool_ops tun_ethtool_ops = { .get_drvinfo = tun_get_drvinfo, .get_msglevel = tun_get_msglevel, .set_msglevel = tun_set_msglevel, .get_link = ethtool_op_get_link, .get_ts_info = ethtool_op_get_ts_info, .get_coalesce = tun_get_coalesce, .set_coalesce = tun_set_coalesce, .get_link_ksettings = tun_get_link_ksettings, }; static int tun_queue_resize(struct tun_struct *tun) { struct net_device *dev = tun->dev; struct tun_file *tfile; struct skb_array **arrays; int n = tun->numqueues + tun->numdisabled; int ret, i; arrays = kmalloc_array(n, sizeof(*arrays), GFP_KERNEL); if (!arrays) return -ENOMEM; for (i = 0; i < tun->numqueues; i++) { tfile = rtnl_dereference(tun->tfiles[i]); arrays[i] = &tfile->tx_array; } list_for_each_entry(tfile, &tun->disabled, next) arrays[i++] = &tfile->tx_array; ret = skb_array_resize_multiple(arrays, n, dev->tx_queue_len, GFP_KERNEL); kfree(arrays); return ret; } static int tun_device_event(struct notifier_block *unused, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct tun_struct *tun = netdev_priv(dev); if (dev->rtnl_link_ops != &tun_link_ops) return NOTIFY_DONE; switch (event) { case NETDEV_CHANGE_TX_QUEUE_LEN: if (tun_queue_resize(tun)) return NOTIFY_BAD; break; default: break; } return NOTIFY_DONE; } static struct notifier_block tun_notifier_block __read_mostly = { .notifier_call = tun_device_event, }; static int __init tun_init(void) { int ret = 0; pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION); ret = rtnl_link_register(&tun_link_ops); if (ret) { pr_err("Can't register link_ops\n"); goto err_linkops; } ret = misc_register(&tun_miscdev); if (ret) { pr_err("Can't register misc device %d\n", TUN_MINOR); goto err_misc; } ret = register_netdevice_notifier(&tun_notifier_block); if (ret) { pr_err("Can't register netdevice notifier\n"); goto err_notifier; } return 0; err_notifier: misc_deregister(&tun_miscdev); err_misc: rtnl_link_unregister(&tun_link_ops); err_linkops: return ret; } static void tun_cleanup(void) { misc_deregister(&tun_miscdev); rtnl_link_unregister(&tun_link_ops); unregister_netdevice_notifier(&tun_notifier_block); } /* Get an underlying socket object from tun file. Returns error unless file is * attached to a device. The returned object works like a packet socket, it * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for * holding a reference to the file for as long as the socket is in use. */ struct socket *tun_get_socket(struct file *file) { struct tun_file *tfile; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tfile = file->private_data; if (!tfile) return ERR_PTR(-EBADFD); return &tfile->socket; } EXPORT_SYMBOL_GPL(tun_get_socket); struct skb_array *tun_get_skb_array(struct file *file) { struct tun_file *tfile; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tfile = file->private_data; if (!tfile) return ERR_PTR(-EBADFD); return &tfile->tx_array; } EXPORT_SYMBOL_GPL(tun_get_skb_array); module_init(tun_init); module_exit(tun_cleanup); MODULE_DESCRIPTION(DRV_DESCRIPTION); MODULE_AUTHOR(DRV_COPYRIGHT); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(TUN_MINOR); MODULE_ALIAS("devname:net/tun");
./CrossVul/dataset_final_sorted/CWE-476/c/good_623_0
crossvul-cpp_data_good_101_0
/* * fs/cifs/sess.c * * SMB/CIFS session setup handling routines * * Copyright (c) International Business Machines Corp., 2006, 2009 * Author(s): Steve French (sfrench@us.ibm.com) * * 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 "cifspdu.h" #include "cifsglob.h" #include "cifsproto.h" #include "cifs_unicode.h" #include "cifs_debug.h" #include "ntlmssp.h" #include "nterr.h" #include <linux/utsname.h> #include <linux/slab.h> #include "cifs_spnego.h" static __u32 cifs_ssetup_hdr(struct cifs_ses *ses, SESSION_SETUP_ANDX *pSMB) { __u32 capabilities = 0; /* init fields common to all four types of SessSetup */ /* Note that offsets for first seven fields in req struct are same */ /* in CIFS Specs so does not matter which of 3 forms of struct */ /* that we use in next few lines */ /* Note that header is initialized to zero in header_assemble */ pSMB->req.AndXCommand = 0xFF; pSMB->req.MaxBufferSize = cpu_to_le16(min_t(u32, CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4, USHRT_MAX)); pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq); pSMB->req.VcNumber = cpu_to_le16(1); /* Now no need to set SMBFLG_CASELESS or obsolete CANONICAL PATH */ /* BB verify whether signing required on neg or just on auth frame (and NTLM case) */ capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS | CAP_LARGE_WRITE_X | CAP_LARGE_READ_X; if (ses->server->sign) pSMB->req.hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE; if (ses->capabilities & CAP_UNICODE) { pSMB->req.hdr.Flags2 |= SMBFLG2_UNICODE; capabilities |= CAP_UNICODE; } if (ses->capabilities & CAP_STATUS32) { pSMB->req.hdr.Flags2 |= SMBFLG2_ERR_STATUS; capabilities |= CAP_STATUS32; } if (ses->capabilities & CAP_DFS) { pSMB->req.hdr.Flags2 |= SMBFLG2_DFS; capabilities |= CAP_DFS; } if (ses->capabilities & CAP_UNIX) capabilities |= CAP_UNIX; return capabilities; } static void unicode_oslm_strings(char **pbcc_area, const struct nls_table *nls_cp) { char *bcc_ptr = *pbcc_area; int bytes_ret = 0; /* Copy OS version */ bytes_ret = cifs_strtoUTF16((__le16 *)bcc_ptr, "Linux version ", 32, nls_cp); bcc_ptr += 2 * bytes_ret; bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, init_utsname()->release, 32, nls_cp); bcc_ptr += 2 * bytes_ret; bcc_ptr += 2; /* trailing null */ bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS, 32, nls_cp); bcc_ptr += 2 * bytes_ret; bcc_ptr += 2; /* trailing null */ *pbcc_area = bcc_ptr; } static void unicode_domain_string(char **pbcc_area, struct cifs_ses *ses, const struct nls_table *nls_cp) { char *bcc_ptr = *pbcc_area; int bytes_ret = 0; /* copy domain */ if (ses->domainName == NULL) { /* Sending null domain better than using a bogus domain name (as we did briefly in 2.6.18) since server will use its default */ *bcc_ptr = 0; *(bcc_ptr+1) = 0; bytes_ret = 0; } else bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->domainName, CIFS_MAX_DOMAINNAME_LEN, nls_cp); bcc_ptr += 2 * bytes_ret; bcc_ptr += 2; /* account for null terminator */ *pbcc_area = bcc_ptr; } static void unicode_ssetup_strings(char **pbcc_area, struct cifs_ses *ses, const struct nls_table *nls_cp) { char *bcc_ptr = *pbcc_area; int bytes_ret = 0; /* BB FIXME add check that strings total less than 335 or will need to send them as arrays */ /* unicode strings, must be word aligned before the call */ /* if ((long) bcc_ptr % 2) { *bcc_ptr = 0; bcc_ptr++; } */ /* copy user */ if (ses->user_name == NULL) { /* null user mount */ *bcc_ptr = 0; *(bcc_ptr+1) = 0; } else { bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->user_name, CIFS_MAX_USERNAME_LEN, nls_cp); } bcc_ptr += 2 * bytes_ret; bcc_ptr += 2; /* account for null termination */ unicode_domain_string(&bcc_ptr, ses, nls_cp); unicode_oslm_strings(&bcc_ptr, nls_cp); *pbcc_area = bcc_ptr; } static void ascii_ssetup_strings(char **pbcc_area, struct cifs_ses *ses, const struct nls_table *nls_cp) { char *bcc_ptr = *pbcc_area; /* copy user */ /* BB what about null user mounts - check that we do this BB */ /* copy user */ if (ses->user_name != NULL) { strncpy(bcc_ptr, ses->user_name, CIFS_MAX_USERNAME_LEN); bcc_ptr += strnlen(ses->user_name, CIFS_MAX_USERNAME_LEN); } /* else null user mount */ *bcc_ptr = 0; bcc_ptr++; /* account for null termination */ /* copy domain */ if (ses->domainName != NULL) { strncpy(bcc_ptr, ses->domainName, CIFS_MAX_DOMAINNAME_LEN); bcc_ptr += strnlen(ses->domainName, CIFS_MAX_DOMAINNAME_LEN); } /* else we will send a null domain name so the server will default to its own domain */ *bcc_ptr = 0; bcc_ptr++; /* BB check for overflow here */ strcpy(bcc_ptr, "Linux version "); bcc_ptr += strlen("Linux version "); strcpy(bcc_ptr, init_utsname()->release); bcc_ptr += strlen(init_utsname()->release) + 1; strcpy(bcc_ptr, CIFS_NETWORK_OPSYS); bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1; *pbcc_area = bcc_ptr; } static void decode_unicode_ssetup(char **pbcc_area, int bleft, struct cifs_ses *ses, const struct nls_table *nls_cp) { int len; char *data = *pbcc_area; cifs_dbg(FYI, "bleft %d\n", bleft); kfree(ses->serverOS); ses->serverOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp); cifs_dbg(FYI, "serverOS=%s\n", ses->serverOS); len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2; data += len; bleft -= len; if (bleft <= 0) return; kfree(ses->serverNOS); ses->serverNOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp); cifs_dbg(FYI, "serverNOS=%s\n", ses->serverNOS); len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2; data += len; bleft -= len; if (bleft <= 0) return; kfree(ses->serverDomain); ses->serverDomain = cifs_strndup_from_utf16(data, bleft, true, nls_cp); cifs_dbg(FYI, "serverDomain=%s\n", ses->serverDomain); return; } static void decode_ascii_ssetup(char **pbcc_area, __u16 bleft, struct cifs_ses *ses, const struct nls_table *nls_cp) { int len; char *bcc_ptr = *pbcc_area; cifs_dbg(FYI, "decode sessetup ascii. bleft %d\n", bleft); len = strnlen(bcc_ptr, bleft); if (len >= bleft) return; kfree(ses->serverOS); ses->serverOS = kzalloc(len + 1, GFP_KERNEL); if (ses->serverOS) { strncpy(ses->serverOS, bcc_ptr, len); if (strncmp(ses->serverOS, "OS/2", 4) == 0) cifs_dbg(FYI, "OS/2 server\n"); } bcc_ptr += len + 1; bleft -= len + 1; len = strnlen(bcc_ptr, bleft); if (len >= bleft) return; kfree(ses->serverNOS); ses->serverNOS = kzalloc(len + 1, GFP_KERNEL); if (ses->serverNOS) strncpy(ses->serverNOS, bcc_ptr, len); bcc_ptr += len + 1; bleft -= len + 1; len = strnlen(bcc_ptr, bleft); if (len > bleft) return; /* No domain field in LANMAN case. Domain is returned by old servers in the SMB negprot response */ /* BB For newer servers which do not support Unicode, but thus do return domain here we could add parsing for it later, but it is not very important */ cifs_dbg(FYI, "ascii: bytes left %d\n", bleft); } int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len, struct cifs_ses *ses) { unsigned int tioffset; /* challenge message target info area */ unsigned int tilen; /* challenge message target info area length */ CHALLENGE_MESSAGE *pblob = (CHALLENGE_MESSAGE *)bcc_ptr; if (blob_len < sizeof(CHALLENGE_MESSAGE)) { cifs_dbg(VFS, "challenge blob len %d too small\n", blob_len); return -EINVAL; } if (memcmp(pblob->Signature, "NTLMSSP", 8)) { cifs_dbg(VFS, "blob signature incorrect %s\n", pblob->Signature); return -EINVAL; } if (pblob->MessageType != NtLmChallenge) { cifs_dbg(VFS, "Incorrect message type %d\n", pblob->MessageType); return -EINVAL; } memcpy(ses->ntlmssp->cryptkey, pblob->Challenge, CIFS_CRYPTO_KEY_SIZE); /* BB we could decode pblob->NegotiateFlags; some may be useful */ /* In particular we can examine sign flags */ /* BB spec says that if AvId field of MsvAvTimestamp is populated then we must set the MIC field of the AUTHENTICATE_MESSAGE */ ses->ntlmssp->server_flags = le32_to_cpu(pblob->NegotiateFlags); tioffset = le32_to_cpu(pblob->TargetInfoArray.BufferOffset); tilen = le16_to_cpu(pblob->TargetInfoArray.Length); if (tioffset > blob_len || tioffset + tilen > blob_len) { cifs_dbg(VFS, "tioffset + tilen too high %u + %u", tioffset, tilen); return -EINVAL; } if (tilen) { ses->auth_key.response = kmemdup(bcc_ptr + tioffset, tilen, GFP_KERNEL); if (!ses->auth_key.response) { cifs_dbg(VFS, "Challenge target info alloc failure"); return -ENOMEM; } ses->auth_key.len = tilen; } return 0; } /* BB Move to ntlmssp.c eventually */ /* We do not malloc the blob, it is passed in pbuffer, because it is fixed size, and small, making this approach cleaner */ void build_ntlmssp_negotiate_blob(unsigned char *pbuffer, struct cifs_ses *ses) { NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer; __u32 flags; memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE)); memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); sec_blob->MessageType = NtLmNegotiate; /* BB is NTLMV2 session security format easier to use here? */ flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | NTLMSSP_NEGOTIATE_SEAL; if (ses->server->sign) flags |= NTLMSSP_NEGOTIATE_SIGN; if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) flags |= NTLMSSP_NEGOTIATE_KEY_XCH; sec_blob->NegotiateFlags = cpu_to_le32(flags); sec_blob->WorkstationName.BufferOffset = 0; sec_blob->WorkstationName.Length = 0; sec_blob->WorkstationName.MaximumLength = 0; /* Domain name is sent on the Challenge not Negotiate NTLMSSP request */ sec_blob->DomainName.BufferOffset = 0; sec_blob->DomainName.Length = 0; sec_blob->DomainName.MaximumLength = 0; } static int size_of_ntlmssp_blob(struct cifs_ses *ses) { int sz = sizeof(AUTHENTICATE_MESSAGE) + ses->auth_key.len - CIFS_SESS_KEY_SIZE + CIFS_CPHTXT_SIZE + 2; if (ses->domainName) sz += 2 * strnlen(ses->domainName, CIFS_MAX_DOMAINNAME_LEN); else sz += 2; if (ses->user_name) sz += 2 * strnlen(ses->user_name, CIFS_MAX_USERNAME_LEN); else sz += 2; return sz; } int build_ntlmssp_auth_blob(unsigned char **pbuffer, u16 *buflen, struct cifs_ses *ses, const struct nls_table *nls_cp) { int rc; AUTHENTICATE_MESSAGE *sec_blob; __u32 flags; unsigned char *tmp; rc = setup_ntlmv2_rsp(ses, nls_cp); if (rc) { cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc); *buflen = 0; goto setup_ntlmv2_ret; } *pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL); sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer; memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); sec_blob->MessageType = NtLmAuthenticate; flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | NTLMSSP_NEGOTIATE_SEAL; if (ses->server->sign) flags |= NTLMSSP_NEGOTIATE_SIGN; if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) flags |= NTLMSSP_NEGOTIATE_KEY_XCH; tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE); sec_blob->NegotiateFlags = cpu_to_le32(flags); sec_blob->LmChallengeResponse.BufferOffset = cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE)); sec_blob->LmChallengeResponse.Length = 0; sec_blob->LmChallengeResponse.MaximumLength = 0; sec_blob->NtChallengeResponse.BufferOffset = cpu_to_le32(tmp - *pbuffer); if (ses->user_name != NULL) { memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE, ses->auth_key.len - CIFS_SESS_KEY_SIZE); tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE; sec_blob->NtChallengeResponse.Length = cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); sec_blob->NtChallengeResponse.MaximumLength = cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); } else { /* * don't send an NT Response for anonymous access */ sec_blob->NtChallengeResponse.Length = 0; sec_blob->NtChallengeResponse.MaximumLength = 0; } if (ses->domainName == NULL) { sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->DomainName.Length = 0; sec_blob->DomainName.MaximumLength = 0; tmp += 2; } else { int len; len = cifs_strtoUTF16((__le16 *)tmp, ses->domainName, CIFS_MAX_DOMAINNAME_LEN, nls_cp); len *= 2; /* unicode is 2 bytes each */ sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->DomainName.Length = cpu_to_le16(len); sec_blob->DomainName.MaximumLength = cpu_to_le16(len); tmp += len; } if (ses->user_name == NULL) { sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->UserName.Length = 0; sec_blob->UserName.MaximumLength = 0; tmp += 2; } else { int len; len = cifs_strtoUTF16((__le16 *)tmp, ses->user_name, CIFS_MAX_USERNAME_LEN, nls_cp); len *= 2; /* unicode is 2 bytes each */ sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->UserName.Length = cpu_to_le16(len); sec_blob->UserName.MaximumLength = cpu_to_le16(len); tmp += len; } sec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->WorkstationName.Length = 0; sec_blob->WorkstationName.MaximumLength = 0; tmp += 2; if (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) || (ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)) && !calc_seckey(ses)) { memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE); sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE); sec_blob->SessionKey.MaximumLength = cpu_to_le16(CIFS_CPHTXT_SIZE); tmp += CIFS_CPHTXT_SIZE; } else { sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer); sec_blob->SessionKey.Length = 0; sec_blob->SessionKey.MaximumLength = 0; } *buflen = tmp - *pbuffer; setup_ntlmv2_ret: return rc; } enum securityEnum select_sectype(struct TCP_Server_Info *server, enum securityEnum requested) { switch (server->negflavor) { case CIFS_NEGFLAVOR_EXTENDED: switch (requested) { case Kerberos: case RawNTLMSSP: return requested; case Unspecified: if (server->sec_ntlmssp && (global_secflags & CIFSSEC_MAY_NTLMSSP)) return RawNTLMSSP; if ((server->sec_kerberos || server->sec_mskerberos) && (global_secflags & CIFSSEC_MAY_KRB5)) return Kerberos; /* Fallthrough */ default: return Unspecified; } case CIFS_NEGFLAVOR_UNENCAP: switch (requested) { case NTLM: case NTLMv2: return requested; case Unspecified: if (global_secflags & CIFSSEC_MAY_NTLMV2) return NTLMv2; if (global_secflags & CIFSSEC_MAY_NTLM) return NTLM; default: /* Fallthrough to attempt LANMAN authentication next */ break; } case CIFS_NEGFLAVOR_LANMAN: switch (requested) { case LANMAN: return requested; case Unspecified: if (global_secflags & CIFSSEC_MAY_LANMAN) return LANMAN; /* Fallthrough */ default: return Unspecified; } default: return Unspecified; } } struct sess_data { unsigned int xid; struct cifs_ses *ses; struct nls_table *nls_cp; void (*func)(struct sess_data *); int result; /* we will send the SMB in three pieces: * a fixed length beginning part, an optional * SPNEGO blob (which can be zero length), and a * last part which will include the strings * and rest of bcc area. This allows us to avoid * a large buffer 17K allocation */ int buf0_type; struct kvec iov[3]; }; static int sess_alloc_buffer(struct sess_data *sess_data, int wct) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb_hdr *smb_buf; rc = small_smb_init_no_tc(SMB_COM_SESSION_SETUP_ANDX, wct, ses, (void **)&smb_buf); if (rc) return rc; sess_data->iov[0].iov_base = (char *)smb_buf; sess_data->iov[0].iov_len = be32_to_cpu(smb_buf->smb_buf_length) + 4; /* * This variable will be used to clear the buffer * allocated above in case of any error in the calling function. */ sess_data->buf0_type = CIFS_SMALL_BUFFER; /* 2000 big enough to fit max user, domain, NOS name etc. */ sess_data->iov[2].iov_base = kmalloc(2000, GFP_KERNEL); if (!sess_data->iov[2].iov_base) { rc = -ENOMEM; goto out_free_smb_buf; } return 0; out_free_smb_buf: kfree(smb_buf); sess_data->iov[0].iov_base = NULL; sess_data->iov[0].iov_len = 0; sess_data->buf0_type = CIFS_NO_BUFFER; return rc; } static void sess_free_buffer(struct sess_data *sess_data) { free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base); sess_data->buf0_type = CIFS_NO_BUFFER; kfree(sess_data->iov[2].iov_base); } static int sess_establish_session(struct sess_data *sess_data) { struct cifs_ses *ses = sess_data->ses; mutex_lock(&ses->server->srv_mutex); if (!ses->server->session_estab) { if (ses->server->sign) { ses->server->session_key.response = kmemdup(ses->auth_key.response, ses->auth_key.len, GFP_KERNEL); if (!ses->server->session_key.response) { mutex_unlock(&ses->server->srv_mutex); return -ENOMEM; } ses->server->session_key.len = ses->auth_key.len; } ses->server->sequence_number = 0x2; ses->server->session_estab = true; } mutex_unlock(&ses->server->srv_mutex); cifs_dbg(FYI, "CIFS session established successfully\n"); spin_lock(&GlobalMid_Lock); ses->status = CifsGood; ses->need_reconnect = false; spin_unlock(&GlobalMid_Lock); return 0; } static int sess_sendreceive(struct sess_data *sess_data) { int rc; struct smb_hdr *smb_buf = (struct smb_hdr *) sess_data->iov[0].iov_base; __u16 count; struct kvec rsp_iov = { NULL, 0 }; count = sess_data->iov[1].iov_len + sess_data->iov[2].iov_len; smb_buf->smb_buf_length = cpu_to_be32(be32_to_cpu(smb_buf->smb_buf_length) + count); put_bcc(count, smb_buf); rc = SendReceive2(sess_data->xid, sess_data->ses, sess_data->iov, 3 /* num_iovecs */, &sess_data->buf0_type, CIFS_LOG_ERROR, &rsp_iov); cifs_small_buf_release(sess_data->iov[0].iov_base); memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec)); return rc; } /* * LANMAN and plaintext are less secure and off by default. * So we make this explicitly be turned on in kconfig (in the * build) and turned on at runtime (changed from the default) * in proc/fs/cifs or via mount parm. Unfortunately this is * needed for old Win (e.g. Win95), some obscure NAS and OS/2 */ #ifdef CONFIG_CIFS_WEAK_PW_HASH static void sess_auth_lanman(struct sess_data *sess_data) { int rc = 0; struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; char *bcc_ptr; struct cifs_ses *ses = sess_data->ses; char lnm_session_key[CIFS_AUTH_RESP_SIZE]; __u32 capabilities; __u16 bytes_remaining; /* lanman 2 style sessionsetup */ /* wct = 10 */ rc = sess_alloc_buffer(sess_data, 10); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; bcc_ptr = sess_data->iov[2].iov_base; capabilities = cifs_ssetup_hdr(ses, pSMB); pSMB->req.hdr.Flags2 &= ~SMBFLG2_UNICODE; if (ses->user_name != NULL) { /* no capabilities flags in old lanman negotiation */ pSMB->old_req.PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE); /* Calculate hash with password and copy into bcc_ptr. * Encryption Key (stored as in cryptkey) gets used if the * security mode bit in Negottiate Protocol response states * to use challenge/response method (i.e. Password bit is 1). */ rc = calc_lanman_hash(ses->password, ses->server->cryptkey, ses->server->sec_mode & SECMODE_PW_ENCRYPT ? true : false, lnm_session_key); if (rc) goto out; memcpy(bcc_ptr, (char *)lnm_session_key, CIFS_AUTH_RESP_SIZE); bcc_ptr += CIFS_AUTH_RESP_SIZE; } else { pSMB->old_req.PasswordLength = 0; } /* * can not sign if LANMAN negotiated so no need * to calculate signing key? but what if server * changed to do higher than lanman dialect and * we reconnected would we ever calc signing_key? */ cifs_dbg(FYI, "Negotiating LANMAN setting up strings\n"); /* Unicode not allowed for LANMAN dialects */ ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp); sess_data->iov[2].iov_len = (long) bcc_ptr - (long) sess_data->iov[2].iov_base; rc = sess_sendreceive(sess_data); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base; /* lanman response has a word count of 3 */ if (smb_buf->WordCount != 3) { rc = -EIO; cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount); goto out; } if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN) cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */ ses->Suid = smb_buf->Uid; /* UID left in wire format (le) */ cifs_dbg(FYI, "UID = %llu\n", ses->Suid); bytes_remaining = get_bcc(smb_buf); bcc_ptr = pByteArea(smb_buf); /* BB check if Unicode and decode strings */ if (bytes_remaining == 0) { /* no string area to decode, do nothing */ } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) { /* unicode string area must be word-aligned */ if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) { ++bcc_ptr; --bytes_remaining; } decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } else { decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } rc = sess_establish_session(sess_data); out: sess_data->result = rc; sess_data->func = NULL; sess_free_buffer(sess_data); } #endif static void sess_auth_ntlm(struct sess_data *sess_data) { int rc = 0; struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; char *bcc_ptr; struct cifs_ses *ses = sess_data->ses; __u32 capabilities; __u16 bytes_remaining; /* old style NTLM sessionsetup */ /* wct = 13 */ rc = sess_alloc_buffer(sess_data, 13); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; bcc_ptr = sess_data->iov[2].iov_base; capabilities = cifs_ssetup_hdr(ses, pSMB); pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities); if (ses->user_name != NULL) { pSMB->req_no_secext.CaseInsensitivePasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE); pSMB->req_no_secext.CaseSensitivePasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE); /* calculate ntlm response and session key */ rc = setup_ntlm_response(ses, sess_data->nls_cp); if (rc) { cifs_dbg(VFS, "Error %d during NTLM authentication\n", rc); goto out; } /* copy ntlm response */ memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE, CIFS_AUTH_RESP_SIZE); bcc_ptr += CIFS_AUTH_RESP_SIZE; memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE, CIFS_AUTH_RESP_SIZE); bcc_ptr += CIFS_AUTH_RESP_SIZE; } else { pSMB->req_no_secext.CaseInsensitivePasswordLength = 0; pSMB->req_no_secext.CaseSensitivePasswordLength = 0; } if (ses->capabilities & CAP_UNICODE) { /* unicode strings must be word aligned */ if (sess_data->iov[0].iov_len % 2) { *bcc_ptr = 0; bcc_ptr++; } unicode_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp); } else { ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp); } sess_data->iov[2].iov_len = (long) bcc_ptr - (long) sess_data->iov[2].iov_base; rc = sess_sendreceive(sess_data); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base; if (smb_buf->WordCount != 3) { rc = -EIO; cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount); goto out; } if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN) cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */ ses->Suid = smb_buf->Uid; /* UID left in wire format (le) */ cifs_dbg(FYI, "UID = %llu\n", ses->Suid); bytes_remaining = get_bcc(smb_buf); bcc_ptr = pByteArea(smb_buf); /* BB check if Unicode and decode strings */ if (bytes_remaining == 0) { /* no string area to decode, do nothing */ } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) { /* unicode string area must be word-aligned */ if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) { ++bcc_ptr; --bytes_remaining; } decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } else { decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } rc = sess_establish_session(sess_data); out: sess_data->result = rc; sess_data->func = NULL; sess_free_buffer(sess_data); kfree(ses->auth_key.response); ses->auth_key.response = NULL; } static void sess_auth_ntlmv2(struct sess_data *sess_data) { int rc = 0; struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; char *bcc_ptr; struct cifs_ses *ses = sess_data->ses; __u32 capabilities; __u16 bytes_remaining; /* old style NTLM sessionsetup */ /* wct = 13 */ rc = sess_alloc_buffer(sess_data, 13); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; bcc_ptr = sess_data->iov[2].iov_base; capabilities = cifs_ssetup_hdr(ses, pSMB); pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities); /* LM2 password would be here if we supported it */ pSMB->req_no_secext.CaseInsensitivePasswordLength = 0; if (ses->user_name != NULL) { /* calculate nlmv2 response and session key */ rc = setup_ntlmv2_rsp(ses, sess_data->nls_cp); if (rc) { cifs_dbg(VFS, "Error %d during NTLMv2 authentication\n", rc); goto out; } memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE, ses->auth_key.len - CIFS_SESS_KEY_SIZE); bcc_ptr += ses->auth_key.len - CIFS_SESS_KEY_SIZE; /* set case sensitive password length after tilen may get * assigned, tilen is 0 otherwise. */ pSMB->req_no_secext.CaseSensitivePasswordLength = cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); } else { pSMB->req_no_secext.CaseSensitivePasswordLength = 0; } if (ses->capabilities & CAP_UNICODE) { if (sess_data->iov[0].iov_len % 2) { *bcc_ptr = 0; bcc_ptr++; } unicode_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp); } else { ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp); } sess_data->iov[2].iov_len = (long) bcc_ptr - (long) sess_data->iov[2].iov_base; rc = sess_sendreceive(sess_data); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base; if (smb_buf->WordCount != 3) { rc = -EIO; cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount); goto out; } if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN) cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */ ses->Suid = smb_buf->Uid; /* UID left in wire format (le) */ cifs_dbg(FYI, "UID = %llu\n", ses->Suid); bytes_remaining = get_bcc(smb_buf); bcc_ptr = pByteArea(smb_buf); /* BB check if Unicode and decode strings */ if (bytes_remaining == 0) { /* no string area to decode, do nothing */ } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) { /* unicode string area must be word-aligned */ if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) { ++bcc_ptr; --bytes_remaining; } decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } else { decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } rc = sess_establish_session(sess_data); out: sess_data->result = rc; sess_data->func = NULL; sess_free_buffer(sess_data); kfree(ses->auth_key.response); ses->auth_key.response = NULL; } #ifdef CONFIG_CIFS_UPCALL static void sess_auth_kerberos(struct sess_data *sess_data) { int rc = 0; struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; char *bcc_ptr; struct cifs_ses *ses = sess_data->ses; __u32 capabilities; __u16 bytes_remaining; struct key *spnego_key = NULL; struct cifs_spnego_msg *msg; u16 blob_len; /* extended security */ /* wct = 12 */ rc = sess_alloc_buffer(sess_data, 12); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; bcc_ptr = sess_data->iov[2].iov_base; capabilities = cifs_ssetup_hdr(ses, pSMB); spnego_key = cifs_get_spnego_key(ses); if (IS_ERR(spnego_key)) { rc = PTR_ERR(spnego_key); spnego_key = NULL; goto out; } msg = spnego_key->payload.data[0]; /* * check version field to make sure that cifs.upcall is * sending us a response in an expected form */ if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) { cifs_dbg(VFS, "incorrect version of cifs.upcall (expected %d but got %d)", CIFS_SPNEGO_UPCALL_VERSION, msg->version); rc = -EKEYREJECTED; goto out_put_spnego_key; } ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len, GFP_KERNEL); if (!ses->auth_key.response) { cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory", msg->sesskey_len); rc = -ENOMEM; goto out_put_spnego_key; } ses->auth_key.len = msg->sesskey_len; pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC; capabilities |= CAP_EXTENDED_SECURITY; pSMB->req.Capabilities = cpu_to_le32(capabilities); sess_data->iov[1].iov_base = msg->data + msg->sesskey_len; sess_data->iov[1].iov_len = msg->secblob_len; pSMB->req.SecurityBlobLength = cpu_to_le16(sess_data->iov[1].iov_len); if (ses->capabilities & CAP_UNICODE) { /* unicode strings must be word aligned */ if ((sess_data->iov[0].iov_len + sess_data->iov[1].iov_len) % 2) { *bcc_ptr = 0; bcc_ptr++; } unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp); unicode_domain_string(&bcc_ptr, ses, sess_data->nls_cp); } else { /* BB: is this right? */ ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp); } sess_data->iov[2].iov_len = (long) bcc_ptr - (long) sess_data->iov[2].iov_base; rc = sess_sendreceive(sess_data); if (rc) goto out_put_spnego_key; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base; if (smb_buf->WordCount != 4) { rc = -EIO; cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount); goto out_put_spnego_key; } if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN) cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */ ses->Suid = smb_buf->Uid; /* UID left in wire format (le) */ cifs_dbg(FYI, "UID = %llu\n", ses->Suid); bytes_remaining = get_bcc(smb_buf); bcc_ptr = pByteArea(smb_buf); blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength); if (blob_len > bytes_remaining) { cifs_dbg(VFS, "bad security blob length %d\n", blob_len); rc = -EINVAL; goto out_put_spnego_key; } bcc_ptr += blob_len; bytes_remaining -= blob_len; /* BB check if Unicode and decode strings */ if (bytes_remaining == 0) { /* no string area to decode, do nothing */ } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) { /* unicode string area must be word-aligned */ if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) { ++bcc_ptr; --bytes_remaining; } decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } else { decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } rc = sess_establish_session(sess_data); out_put_spnego_key: key_invalidate(spnego_key); key_put(spnego_key); out: sess_data->result = rc; sess_data->func = NULL; sess_free_buffer(sess_data); kfree(ses->auth_key.response); ses->auth_key.response = NULL; } #endif /* ! CONFIG_CIFS_UPCALL */ /* * The required kvec buffers have to be allocated before calling this * function. */ static int _sess_auth_rawntlmssp_assemble_req(struct sess_data *sess_data) { struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; struct cifs_ses *ses = sess_data->ses; __u32 capabilities; char *bcc_ptr; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)pSMB; capabilities = cifs_ssetup_hdr(ses, pSMB); if ((pSMB->req.hdr.Flags2 & SMBFLG2_UNICODE) == 0) { cifs_dbg(VFS, "NTLMSSP requires Unicode support\n"); return -ENOSYS; } pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC; capabilities |= CAP_EXTENDED_SECURITY; pSMB->req.Capabilities |= cpu_to_le32(capabilities); bcc_ptr = sess_data->iov[2].iov_base; /* unicode strings must be word aligned */ if ((sess_data->iov[0].iov_len + sess_data->iov[1].iov_len) % 2) { *bcc_ptr = 0; bcc_ptr++; } unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp); sess_data->iov[2].iov_len = (long) bcc_ptr - (long) sess_data->iov[2].iov_base; return 0; } static void sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data); static void sess_auth_rawntlmssp_negotiate(struct sess_data *sess_data) { int rc; struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; struct cifs_ses *ses = sess_data->ses; __u16 bytes_remaining; char *bcc_ptr; u16 blob_len; cifs_dbg(FYI, "rawntlmssp session setup negotiate phase\n"); /* * if memory allocation is successful, caller of this function * frees it. */ ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL); if (!ses->ntlmssp) { rc = -ENOMEM; goto out; } ses->ntlmssp->sesskey_per_smbsess = false; /* wct = 12 */ rc = sess_alloc_buffer(sess_data, 12); if (rc) goto out; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; /* Build security blob before we assemble the request */ build_ntlmssp_negotiate_blob(pSMB->req.SecurityBlob, ses); sess_data->iov[1].iov_len = sizeof(NEGOTIATE_MESSAGE); sess_data->iov[1].iov_base = pSMB->req.SecurityBlob; pSMB->req.SecurityBlobLength = cpu_to_le16(sizeof(NEGOTIATE_MESSAGE)); rc = _sess_auth_rawntlmssp_assemble_req(sess_data); if (rc) goto out; rc = sess_sendreceive(sess_data); pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base; /* If true, rc here is expected and not an error */ if (sess_data->buf0_type != CIFS_NO_BUFFER && smb_buf->Status.CifsError == cpu_to_le32(NT_STATUS_MORE_PROCESSING_REQUIRED)) rc = 0; if (rc) goto out; cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n"); if (smb_buf->WordCount != 4) { rc = -EIO; cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount); goto out; } ses->Suid = smb_buf->Uid; /* UID left in wire format (le) */ cifs_dbg(FYI, "UID = %llu\n", ses->Suid); bytes_remaining = get_bcc(smb_buf); bcc_ptr = pByteArea(smb_buf); blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength); if (blob_len > bytes_remaining) { cifs_dbg(VFS, "bad security blob length %d\n", blob_len); rc = -EINVAL; goto out; } rc = decode_ntlmssp_challenge(bcc_ptr, blob_len, ses); out: sess_free_buffer(sess_data); if (!rc) { sess_data->func = sess_auth_rawntlmssp_authenticate; return; } /* Else error. Cleanup */ kfree(ses->auth_key.response); ses->auth_key.response = NULL; kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->func = NULL; sess_data->result = rc; } static void sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data) { int rc; struct smb_hdr *smb_buf; SESSION_SETUP_ANDX *pSMB; struct cifs_ses *ses = sess_data->ses; __u16 bytes_remaining; char *bcc_ptr; unsigned char *ntlmsspblob = NULL; u16 blob_len; cifs_dbg(FYI, "rawntlmssp session setup authenticate phase\n"); /* wct = 12 */ rc = sess_alloc_buffer(sess_data, 12); if (rc) goto out; /* Build security blob before we assemble the request */ pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)pSMB; rc = build_ntlmssp_auth_blob(&ntlmsspblob, &blob_len, ses, sess_data->nls_cp); if (rc) goto out_free_ntlmsspblob; sess_data->iov[1].iov_len = blob_len; sess_data->iov[1].iov_base = ntlmsspblob; pSMB->req.SecurityBlobLength = cpu_to_le16(blob_len); /* * Make sure that we tell the server that we are using * the uid that it just gave us back on the response * (challenge) */ smb_buf->Uid = ses->Suid; rc = _sess_auth_rawntlmssp_assemble_req(sess_data); if (rc) goto out_free_ntlmsspblob; rc = sess_sendreceive(sess_data); if (rc) goto out_free_ntlmsspblob; pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base; smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base; if (smb_buf->WordCount != 4) { rc = -EIO; cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount); goto out_free_ntlmsspblob; } if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN) cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */ if (ses->Suid != smb_buf->Uid) { ses->Suid = smb_buf->Uid; cifs_dbg(FYI, "UID changed! new UID = %llu\n", ses->Suid); } bytes_remaining = get_bcc(smb_buf); bcc_ptr = pByteArea(smb_buf); blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength); if (blob_len > bytes_remaining) { cifs_dbg(VFS, "bad security blob length %d\n", blob_len); rc = -EINVAL; goto out_free_ntlmsspblob; } bcc_ptr += blob_len; bytes_remaining -= blob_len; /* BB check if Unicode and decode strings */ if (bytes_remaining == 0) { /* no string area to decode, do nothing */ } else if (smb_buf->Flags2 & SMBFLG2_UNICODE) { /* unicode string area must be word-aligned */ if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) { ++bcc_ptr; --bytes_remaining; } decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } else { decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses, sess_data->nls_cp); } out_free_ntlmsspblob: kfree(ntlmsspblob); out: sess_free_buffer(sess_data); if (!rc) rc = sess_establish_session(sess_data); /* Cleanup */ kfree(ses->auth_key.response); ses->auth_key.response = NULL; kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->func = NULL; sess_data->result = rc; } static int select_sec(struct cifs_ses *ses, struct sess_data *sess_data) { int type; type = select_sectype(ses->server, ses->sectype); cifs_dbg(FYI, "sess setup type %d\n", type); if (type == Unspecified) { cifs_dbg(VFS, "Unable to select appropriate authentication method!"); return -EINVAL; } switch (type) { case LANMAN: /* LANMAN and plaintext are less secure and off by default. * So we make this explicitly be turned on in kconfig (in the * build) and turned on at runtime (changed from the default) * in proc/fs/cifs or via mount parm. Unfortunately this is * needed for old Win (e.g. Win95), some obscure NAS and OS/2 */ #ifdef CONFIG_CIFS_WEAK_PW_HASH sess_data->func = sess_auth_lanman; break; #else return -EOPNOTSUPP; #endif case NTLM: sess_data->func = sess_auth_ntlm; break; case NTLMv2: sess_data->func = sess_auth_ntlmv2; break; case Kerberos: #ifdef CONFIG_CIFS_UPCALL sess_data->func = sess_auth_kerberos; break; #else cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n"); return -ENOSYS; break; #endif /* CONFIG_CIFS_UPCALL */ case RawNTLMSSP: sess_data->func = sess_auth_rawntlmssp_negotiate; break; default: cifs_dbg(VFS, "secType %d not supported!\n", type); return -ENOSYS; } return 0; } int CIFS_SessSetup(const unsigned int xid, struct cifs_ses *ses, const struct nls_table *nls_cp) { int rc = 0; struct sess_data *sess_data; if (ses == NULL) { WARN(1, "%s: ses == NULL!", __func__); return -EINVAL; } sess_data = kzalloc(sizeof(struct sess_data), GFP_KERNEL); if (!sess_data) return -ENOMEM; rc = select_sec(ses, sess_data); if (rc) goto out; sess_data->xid = xid; sess_data->ses = ses; sess_data->buf0_type = CIFS_NO_BUFFER; sess_data->nls_cp = (struct nls_table *) nls_cp; while (sess_data->func) sess_data->func(sess_data); /* Store result before we free sess_data */ rc = sess_data->result; out: kfree(sess_data); return rc; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_101_0
crossvul-cpp_data_good_1062_0
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2018 Intel Corporation. */ #include <linux/types.h> #include <linux/module.h> #include <net/ipv6.h> #include <net/ip.h> #include <net/tcp.h> #include <linux/if_macvlan.h> #include <linux/prefetch.h> #include "fm10k.h" #define DRV_VERSION "0.26.1-k" #define DRV_SUMMARY "Intel(R) Ethernet Switch Host Interface Driver" const char fm10k_driver_version[] = DRV_VERSION; char fm10k_driver_name[] = "fm10k"; static const char fm10k_driver_string[] = DRV_SUMMARY; static const char fm10k_copyright[] = "Copyright(c) 2013 - 2018 Intel Corporation."; MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>"); MODULE_DESCRIPTION(DRV_SUMMARY); MODULE_LICENSE("GPL v2"); MODULE_VERSION(DRV_VERSION); /* single workqueue for entire fm10k driver */ struct workqueue_struct *fm10k_workqueue; /** * fm10k_init_module - Driver Registration Routine * * fm10k_init_module is the first routine called when the driver is * loaded. All it does is register with the PCI subsystem. **/ static int __init fm10k_init_module(void) { pr_info("%s - version %s\n", fm10k_driver_string, fm10k_driver_version); pr_info("%s\n", fm10k_copyright); /* create driver workqueue */ fm10k_workqueue = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, fm10k_driver_name); if (!fm10k_workqueue) return -ENOMEM; fm10k_dbg_init(); return fm10k_register_pci_driver(); } module_init(fm10k_init_module); /** * fm10k_exit_module - Driver Exit Cleanup Routine * * fm10k_exit_module is called just before the driver is removed * from memory. **/ static void __exit fm10k_exit_module(void) { fm10k_unregister_pci_driver(); fm10k_dbg_exit(); /* destroy driver workqueue */ destroy_workqueue(fm10k_workqueue); } module_exit(fm10k_exit_module); static bool fm10k_alloc_mapped_page(struct fm10k_ring *rx_ring, struct fm10k_rx_buffer *bi) { struct page *page = bi->page; dma_addr_t dma; /* Only page will be NULL if buffer was consumed */ if (likely(page)) return true; /* alloc new page for storage */ page = dev_alloc_page(); if (unlikely(!page)) { rx_ring->rx_stats.alloc_failed++; return false; } /* map page for use */ dma = dma_map_page(rx_ring->dev, page, 0, PAGE_SIZE, DMA_FROM_DEVICE); /* if mapping failed free memory back to system since * there isn't much point in holding memory we can't use */ if (dma_mapping_error(rx_ring->dev, dma)) { __free_page(page); rx_ring->rx_stats.alloc_failed++; return false; } bi->dma = dma; bi->page = page; bi->page_offset = 0; return true; } /** * fm10k_alloc_rx_buffers - Replace used receive buffers * @rx_ring: ring to place buffers on * @cleaned_count: number of buffers to replace **/ void fm10k_alloc_rx_buffers(struct fm10k_ring *rx_ring, u16 cleaned_count) { union fm10k_rx_desc *rx_desc; struct fm10k_rx_buffer *bi; u16 i = rx_ring->next_to_use; /* nothing to do */ if (!cleaned_count) return; rx_desc = FM10K_RX_DESC(rx_ring, i); bi = &rx_ring->rx_buffer[i]; i -= rx_ring->count; do { if (!fm10k_alloc_mapped_page(rx_ring, bi)) break; /* Refresh the desc even if buffer_addrs didn't change * because each write-back erases this info. */ rx_desc->q.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset); rx_desc++; bi++; i++; if (unlikely(!i)) { rx_desc = FM10K_RX_DESC(rx_ring, 0); bi = rx_ring->rx_buffer; i -= rx_ring->count; } /* clear the status bits for the next_to_use descriptor */ rx_desc->d.staterr = 0; cleaned_count--; } while (cleaned_count); i += rx_ring->count; if (rx_ring->next_to_use != i) { /* record the next descriptor to use */ rx_ring->next_to_use = i; /* update next to alloc since we have filled the ring */ rx_ring->next_to_alloc = i; /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ wmb(); /* notify hardware of new descriptors */ writel(i, rx_ring->tail); } } /** * fm10k_reuse_rx_page - page flip buffer and store it back on the ring * @rx_ring: rx descriptor ring to store buffers on * @old_buff: donor buffer to have page reused * * Synchronizes page for reuse by the interface **/ static void fm10k_reuse_rx_page(struct fm10k_ring *rx_ring, struct fm10k_rx_buffer *old_buff) { struct fm10k_rx_buffer *new_buff; u16 nta = rx_ring->next_to_alloc; new_buff = &rx_ring->rx_buffer[nta]; /* update, and store next to alloc */ nta++; rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0; /* transfer page from old buffer to new buffer */ *new_buff = *old_buff; /* sync the buffer for use by the device */ dma_sync_single_range_for_device(rx_ring->dev, old_buff->dma, old_buff->page_offset, FM10K_RX_BUFSZ, DMA_FROM_DEVICE); } static inline bool fm10k_page_is_reserved(struct page *page) { return (page_to_nid(page) != numa_mem_id()) || page_is_pfmemalloc(page); } static bool fm10k_can_reuse_rx_page(struct fm10k_rx_buffer *rx_buffer, struct page *page, unsigned int __maybe_unused truesize) { /* avoid re-using remote pages */ if (unlikely(fm10k_page_is_reserved(page))) return false; #if (PAGE_SIZE < 8192) /* if we are only owner of page we can reuse it */ if (unlikely(page_count(page) != 1)) return false; /* flip page offset to other buffer */ rx_buffer->page_offset ^= FM10K_RX_BUFSZ; #else /* move offset up to the next cache line */ rx_buffer->page_offset += truesize; if (rx_buffer->page_offset > (PAGE_SIZE - FM10K_RX_BUFSZ)) return false; #endif /* Even if we own the page, we are not allowed to use atomic_set() * This would break get_page_unless_zero() users. */ page_ref_inc(page); return true; } /** * fm10k_add_rx_frag - Add contents of Rx buffer to sk_buff * @rx_buffer: buffer containing page to add * @size: packet size from rx_desc * @rx_desc: descriptor containing length of buffer written by hardware * @skb: sk_buff to place the data into * * This function will add the data contained in rx_buffer->page to the skb. * This is done either through a direct copy if the data in the buffer is * less than the skb header size, otherwise it will just attach the page as * a frag to the skb. * * The function will then update the page offset if necessary and return * true if the buffer can be reused by the interface. **/ static bool fm10k_add_rx_frag(struct fm10k_rx_buffer *rx_buffer, unsigned int size, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { struct page *page = rx_buffer->page; unsigned char *va = page_address(page) + rx_buffer->page_offset; #if (PAGE_SIZE < 8192) unsigned int truesize = FM10K_RX_BUFSZ; #else unsigned int truesize = ALIGN(size, 512); #endif unsigned int pull_len; if (unlikely(skb_is_nonlinear(skb))) goto add_tail_frag; if (likely(size <= FM10K_RX_HDR_LEN)) { memcpy(__skb_put(skb, size), va, ALIGN(size, sizeof(long))); /* page is not reserved, we can reuse buffer as-is */ if (likely(!fm10k_page_is_reserved(page))) return true; /* this page cannot be reused so discard it */ __free_page(page); return false; } /* we need the header to contain the greater of either ETH_HLEN or * 60 bytes if the skb->len is less than 60 for skb_pad. */ pull_len = eth_get_headlen(va, FM10K_RX_HDR_LEN); /* align pull length to size of long to optimize memcpy performance */ memcpy(__skb_put(skb, pull_len), va, ALIGN(pull_len, sizeof(long))); /* update all of the pointers */ va += pull_len; size -= pull_len; add_tail_frag: skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, (unsigned long)va & ~PAGE_MASK, size, truesize); return fm10k_can_reuse_rx_page(rx_buffer, page, truesize); } static struct sk_buff *fm10k_fetch_rx_buffer(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { unsigned int size = le16_to_cpu(rx_desc->w.length); struct fm10k_rx_buffer *rx_buffer; struct page *page; rx_buffer = &rx_ring->rx_buffer[rx_ring->next_to_clean]; page = rx_buffer->page; prefetchw(page); if (likely(!skb)) { void *page_addr = page_address(page) + rx_buffer->page_offset; /* prefetch first cache line of first page */ prefetch(page_addr); #if L1_CACHE_BYTES < 128 prefetch(page_addr + L1_CACHE_BYTES); #endif /* allocate a skb to store the frags */ skb = napi_alloc_skb(&rx_ring->q_vector->napi, FM10K_RX_HDR_LEN); if (unlikely(!skb)) { rx_ring->rx_stats.alloc_failed++; return NULL; } /* we will be copying header into skb->data in * pskb_may_pull so it is in our interest to prefetch * it now to avoid a possible cache miss */ prefetchw(skb->data); } /* we are reusing so sync this buffer for CPU use */ dma_sync_single_range_for_cpu(rx_ring->dev, rx_buffer->dma, rx_buffer->page_offset, size, DMA_FROM_DEVICE); /* pull page into skb */ if (fm10k_add_rx_frag(rx_buffer, size, rx_desc, skb)) { /* hand second half of page back to the ring */ fm10k_reuse_rx_page(rx_ring, rx_buffer); } else { /* we are not reusing the buffer so unmap it */ dma_unmap_page(rx_ring->dev, rx_buffer->dma, PAGE_SIZE, DMA_FROM_DEVICE); } /* clear contents of rx_buffer */ rx_buffer->page = NULL; return skb; } static inline void fm10k_rx_checksum(struct fm10k_ring *ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { skb_checksum_none_assert(skb); /* Rx checksum disabled via ethtool */ if (!(ring->netdev->features & NETIF_F_RXCSUM)) return; /* TCP/UDP checksum error bit is set */ if (fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4E | FM10K_RXD_STATUS_L4E2 | FM10K_RXD_STATUS_IPE | FM10K_RXD_STATUS_IPE2)) { ring->rx_stats.csum_err++; return; } /* It must be a TCP or UDP packet with a valid checksum */ if (fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS2)) skb->encapsulation = true; else if (!fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS)) return; skb->ip_summed = CHECKSUM_UNNECESSARY; ring->rx_stats.csum_good++; } #define FM10K_RSS_L4_TYPES_MASK \ (BIT(FM10K_RSSTYPE_IPV4_TCP) | \ BIT(FM10K_RSSTYPE_IPV4_UDP) | \ BIT(FM10K_RSSTYPE_IPV6_TCP) | \ BIT(FM10K_RSSTYPE_IPV6_UDP)) static inline void fm10k_rx_hash(struct fm10k_ring *ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { u16 rss_type; if (!(ring->netdev->features & NETIF_F_RXHASH)) return; rss_type = le16_to_cpu(rx_desc->w.pkt_info) & FM10K_RXD_RSSTYPE_MASK; if (!rss_type) return; skb_set_hash(skb, le32_to_cpu(rx_desc->d.rss), (BIT(rss_type) & FM10K_RSS_L4_TYPES_MASK) ? PKT_HASH_TYPE_L4 : PKT_HASH_TYPE_L3); } static void fm10k_type_trans(struct fm10k_ring *rx_ring, union fm10k_rx_desc __maybe_unused *rx_desc, struct sk_buff *skb) { struct net_device *dev = rx_ring->netdev; struct fm10k_l2_accel *l2_accel = rcu_dereference_bh(rx_ring->l2_accel); /* check to see if DGLORT belongs to a MACVLAN */ if (l2_accel) { u16 idx = le16_to_cpu(FM10K_CB(skb)->fi.w.dglort) - 1; idx -= l2_accel->dglort; if (idx < l2_accel->size && l2_accel->macvlan[idx]) dev = l2_accel->macvlan[idx]; else l2_accel = NULL; } /* Record Rx queue, or update macvlan statistics */ if (!l2_accel) skb_record_rx_queue(skb, rx_ring->queue_index); else macvlan_count_rx(netdev_priv(dev), skb->len + ETH_HLEN, true, false); skb->protocol = eth_type_trans(skb, dev); } /** * fm10k_process_skb_fields - Populate skb header fields from Rx descriptor * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being populated * * This function checks the ring, descriptor, and packet information in * order to populate the hash, checksum, VLAN, timestamp, protocol, and * other fields within the skb. **/ static unsigned int fm10k_process_skb_fields(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { unsigned int len = skb->len; fm10k_rx_hash(rx_ring, rx_desc, skb); fm10k_rx_checksum(rx_ring, rx_desc, skb); FM10K_CB(skb)->tstamp = rx_desc->q.timestamp; FM10K_CB(skb)->fi.w.vlan = rx_desc->w.vlan; FM10K_CB(skb)->fi.d.glort = rx_desc->d.glort; if (rx_desc->w.vlan) { u16 vid = le16_to_cpu(rx_desc->w.vlan); if ((vid & VLAN_VID_MASK) != rx_ring->vid) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); else if (vid & VLAN_PRIO_MASK) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid & VLAN_PRIO_MASK); } fm10k_type_trans(rx_ring, rx_desc, skb); return len; } /** * fm10k_is_non_eop - process handling of non-EOP buffers * @rx_ring: Rx ring being processed * @rx_desc: Rx descriptor for current buffer * * This function updates next to clean. If the buffer is an EOP buffer * this function exits returning false, otherwise it will place the * sk_buff in the next buffer to be chained and return true indicating * that this is in fact a non-EOP buffer. **/ static bool fm10k_is_non_eop(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc) { u32 ntc = rx_ring->next_to_clean + 1; /* fetch, update, and store next to clean */ ntc = (ntc < rx_ring->count) ? ntc : 0; rx_ring->next_to_clean = ntc; prefetch(FM10K_RX_DESC(rx_ring, ntc)); if (likely(fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_EOP))) return false; return true; } /** * fm10k_cleanup_headers - Correct corrupted or empty headers * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being fixed * * Address the case where we are pulling data in on pages only * and as such no data is present in the skb header. * * In addition if skb is not at least 60 bytes we need to pad it so that * it is large enough to qualify as a valid Ethernet frame. * * Returns true if an error was encountered and skb was freed. **/ static bool fm10k_cleanup_headers(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { if (unlikely((fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_RXE)))) { #define FM10K_TEST_RXD_BIT(rxd, bit) \ ((rxd)->w.csum_err & cpu_to_le16(bit)) if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_ERROR)) rx_ring->rx_stats.switch_errors++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_NO_DESCRIPTOR)) rx_ring->rx_stats.drops++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_PP_ERROR)) rx_ring->rx_stats.pp_errors++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_READY)) rx_ring->rx_stats.link_errors++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_TOO_BIG)) rx_ring->rx_stats.length_errors++; dev_kfree_skb_any(skb); rx_ring->rx_stats.errors++; return true; } /* if eth_skb_pad returns an error the skb was freed */ if (eth_skb_pad(skb)) return true; return false; } /** * fm10k_receive_skb - helper function to handle rx indications * @q_vector: structure containing interrupt and ring information * @skb: packet to send up **/ static void fm10k_receive_skb(struct fm10k_q_vector *q_vector, struct sk_buff *skb) { napi_gro_receive(&q_vector->napi, skb); } static int fm10k_clean_rx_irq(struct fm10k_q_vector *q_vector, struct fm10k_ring *rx_ring, int budget) { struct sk_buff *skb = rx_ring->skb; unsigned int total_bytes = 0, total_packets = 0; u16 cleaned_count = fm10k_desc_unused(rx_ring); while (likely(total_packets < budget)) { union fm10k_rx_desc *rx_desc; /* return some buffers to hardware, one at a time is too slow */ if (cleaned_count >= FM10K_RX_BUFFER_WRITE) { fm10k_alloc_rx_buffers(rx_ring, cleaned_count); cleaned_count = 0; } rx_desc = FM10K_RX_DESC(rx_ring, rx_ring->next_to_clean); if (!rx_desc->d.staterr) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we know the * descriptor has been written back */ dma_rmb(); /* retrieve a buffer from the ring */ skb = fm10k_fetch_rx_buffer(rx_ring, rx_desc, skb); /* exit if we failed to retrieve a buffer */ if (!skb) break; cleaned_count++; /* fetch next buffer in frame if non-eop */ if (fm10k_is_non_eop(rx_ring, rx_desc)) continue; /* verify the packet layout is correct */ if (fm10k_cleanup_headers(rx_ring, rx_desc, skb)) { skb = NULL; continue; } /* populate checksum, timestamp, VLAN, and protocol */ total_bytes += fm10k_process_skb_fields(rx_ring, rx_desc, skb); fm10k_receive_skb(q_vector, skb); /* reset skb pointer */ skb = NULL; /* update budget accounting */ total_packets++; } /* place incomplete frames back on ring for completion */ rx_ring->skb = skb; u64_stats_update_begin(&rx_ring->syncp); rx_ring->stats.packets += total_packets; rx_ring->stats.bytes += total_bytes; u64_stats_update_end(&rx_ring->syncp); q_vector->rx.total_packets += total_packets; q_vector->rx.total_bytes += total_bytes; return total_packets; } #define VXLAN_HLEN (sizeof(struct udphdr) + 8) static struct ethhdr *fm10k_port_is_vxlan(struct sk_buff *skb) { struct fm10k_intfc *interface = netdev_priv(skb->dev); struct fm10k_udp_port *vxlan_port; /* we can only offload a vxlan if we recognize it as such */ vxlan_port = list_first_entry_or_null(&interface->vxlan_port, struct fm10k_udp_port, list); if (!vxlan_port) return NULL; if (vxlan_port->port != udp_hdr(skb)->dest) return NULL; /* return offset of udp_hdr plus 8 bytes for VXLAN header */ return (struct ethhdr *)(skb_transport_header(skb) + VXLAN_HLEN); } #define FM10K_NVGRE_RESERVED0_FLAGS htons(0x9FFF) #define NVGRE_TNI htons(0x2000) struct fm10k_nvgre_hdr { __be16 flags; __be16 proto; __be32 tni; }; static struct ethhdr *fm10k_gre_is_nvgre(struct sk_buff *skb) { struct fm10k_nvgre_hdr *nvgre_hdr; int hlen = ip_hdrlen(skb); /* currently only IPv4 is supported due to hlen above */ if (vlan_get_protocol(skb) != htons(ETH_P_IP)) return NULL; /* our transport header should be NVGRE */ nvgre_hdr = (struct fm10k_nvgre_hdr *)(skb_network_header(skb) + hlen); /* verify all reserved flags are 0 */ if (nvgre_hdr->flags & FM10K_NVGRE_RESERVED0_FLAGS) return NULL; /* report start of ethernet header */ if (nvgre_hdr->flags & NVGRE_TNI) return (struct ethhdr *)(nvgre_hdr + 1); return (struct ethhdr *)(&nvgre_hdr->tni); } __be16 fm10k_tx_encap_offload(struct sk_buff *skb) { u8 l4_hdr = 0, inner_l4_hdr = 0, inner_l4_hlen; struct ethhdr *eth_hdr; if (skb->inner_protocol_type != ENCAP_TYPE_ETHER || skb->inner_protocol != htons(ETH_P_TEB)) return 0; switch (vlan_get_protocol(skb)) { case htons(ETH_P_IP): l4_hdr = ip_hdr(skb)->protocol; break; case htons(ETH_P_IPV6): l4_hdr = ipv6_hdr(skb)->nexthdr; break; default: return 0; } switch (l4_hdr) { case IPPROTO_UDP: eth_hdr = fm10k_port_is_vxlan(skb); break; case IPPROTO_GRE: eth_hdr = fm10k_gre_is_nvgre(skb); break; default: return 0; } if (!eth_hdr) return 0; switch (eth_hdr->h_proto) { case htons(ETH_P_IP): inner_l4_hdr = inner_ip_hdr(skb)->protocol; break; case htons(ETH_P_IPV6): inner_l4_hdr = inner_ipv6_hdr(skb)->nexthdr; break; default: return 0; } switch (inner_l4_hdr) { case IPPROTO_TCP: inner_l4_hlen = inner_tcp_hdrlen(skb); break; case IPPROTO_UDP: inner_l4_hlen = 8; break; default: return 0; } /* The hardware allows tunnel offloads only if the combined inner and * outer header is 184 bytes or less */ if (skb_inner_transport_header(skb) + inner_l4_hlen - skb_mac_header(skb) > FM10K_TUNNEL_HEADER_LENGTH) return 0; return eth_hdr->h_proto; } static int fm10k_tso(struct fm10k_ring *tx_ring, struct fm10k_tx_buffer *first) { struct sk_buff *skb = first->skb; struct fm10k_tx_desc *tx_desc; unsigned char *th; u8 hdrlen; if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; if (!skb_is_gso(skb)) return 0; /* compute header lengths */ if (skb->encapsulation) { if (!fm10k_tx_encap_offload(skb)) goto err_vxlan; th = skb_inner_transport_header(skb); } else { th = skb_transport_header(skb); } /* compute offset from SOF to transport header and add header len */ hdrlen = (th - skb->data) + (((struct tcphdr *)th)->doff << 2); first->tx_flags |= FM10K_TX_FLAGS_CSUM; /* update gso size and bytecount with header size */ first->gso_segs = skb_shinfo(skb)->gso_segs; first->bytecount += (first->gso_segs - 1) * hdrlen; /* populate Tx descriptor header size and mss */ tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use); tx_desc->hdrlen = hdrlen; tx_desc->mss = cpu_to_le16(skb_shinfo(skb)->gso_size); return 1; err_vxlan: tx_ring->netdev->features &= ~NETIF_F_GSO_UDP_TUNNEL; if (net_ratelimit()) netdev_err(tx_ring->netdev, "TSO requested for unsupported tunnel, disabling offload\n"); return -1; } static void fm10k_tx_csum(struct fm10k_ring *tx_ring, struct fm10k_tx_buffer *first) { struct sk_buff *skb = first->skb; struct fm10k_tx_desc *tx_desc; union { struct iphdr *ipv4; struct ipv6hdr *ipv6; u8 *raw; } network_hdr; u8 *transport_hdr; __be16 frag_off; __be16 protocol; u8 l4_hdr = 0; if (skb->ip_summed != CHECKSUM_PARTIAL) goto no_csum; if (skb->encapsulation) { protocol = fm10k_tx_encap_offload(skb); if (!protocol) { if (skb_checksum_help(skb)) { dev_warn(tx_ring->dev, "failed to offload encap csum!\n"); tx_ring->tx_stats.csum_err++; } goto no_csum; } network_hdr.raw = skb_inner_network_header(skb); transport_hdr = skb_inner_transport_header(skb); } else { protocol = vlan_get_protocol(skb); network_hdr.raw = skb_network_header(skb); transport_hdr = skb_transport_header(skb); } switch (protocol) { case htons(ETH_P_IP): l4_hdr = network_hdr.ipv4->protocol; break; case htons(ETH_P_IPV6): l4_hdr = network_hdr.ipv6->nexthdr; if (likely((transport_hdr - network_hdr.raw) == sizeof(struct ipv6hdr))) break; ipv6_skip_exthdr(skb, network_hdr.raw - skb->data + sizeof(struct ipv6hdr), &l4_hdr, &frag_off); if (unlikely(frag_off)) l4_hdr = NEXTHDR_FRAGMENT; break; default: break; } switch (l4_hdr) { case IPPROTO_TCP: case IPPROTO_UDP: break; case IPPROTO_GRE: if (skb->encapsulation) break; /* fall through */ default: if (unlikely(net_ratelimit())) { dev_warn(tx_ring->dev, "partial checksum, version=%d l4 proto=%x\n", protocol, l4_hdr); } skb_checksum_help(skb); tx_ring->tx_stats.csum_err++; goto no_csum; } /* update TX checksum flag */ first->tx_flags |= FM10K_TX_FLAGS_CSUM; tx_ring->tx_stats.csum_good++; no_csum: /* populate Tx descriptor header size and mss */ tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use); tx_desc->hdrlen = 0; tx_desc->mss = 0; } #define FM10K_SET_FLAG(_input, _flag, _result) \ ((_flag <= _result) ? \ ((u32)(_input & _flag) * (_result / _flag)) : \ ((u32)(_input & _flag) / (_flag / _result))) static u8 fm10k_tx_desc_flags(struct sk_buff *skb, u32 tx_flags) { /* set type for advanced descriptor with frame checksum insertion */ u32 desc_flags = 0; /* set checksum offload bits */ desc_flags |= FM10K_SET_FLAG(tx_flags, FM10K_TX_FLAGS_CSUM, FM10K_TXD_FLAG_CSUM); return desc_flags; } static bool fm10k_tx_desc_push(struct fm10k_ring *tx_ring, struct fm10k_tx_desc *tx_desc, u16 i, dma_addr_t dma, unsigned int size, u8 desc_flags) { /* set RS and INT for last frame in a cache line */ if ((++i & (FM10K_TXD_WB_FIFO_SIZE - 1)) == 0) desc_flags |= FM10K_TXD_FLAG_RS | FM10K_TXD_FLAG_INT; /* record values to descriptor */ tx_desc->buffer_addr = cpu_to_le64(dma); tx_desc->flags = desc_flags; tx_desc->buflen = cpu_to_le16(size); /* return true if we just wrapped the ring */ return i == tx_ring->count; } static int __fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size) { netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index); /* Memory barrier before checking head and tail */ smp_mb(); /* Check again in a case another CPU has just made room available */ if (likely(fm10k_desc_unused(tx_ring) < size)) return -EBUSY; /* A reprieve! - use start_queue because it doesn't call schedule */ netif_start_subqueue(tx_ring->netdev, tx_ring->queue_index); ++tx_ring->tx_stats.restart_queue; return 0; } static inline int fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size) { if (likely(fm10k_desc_unused(tx_ring) >= size)) return 0; return __fm10k_maybe_stop_tx(tx_ring, size); } static void fm10k_tx_map(struct fm10k_ring *tx_ring, struct fm10k_tx_buffer *first) { struct sk_buff *skb = first->skb; struct fm10k_tx_buffer *tx_buffer; struct fm10k_tx_desc *tx_desc; struct skb_frag_struct *frag; unsigned char *data; dma_addr_t dma; unsigned int data_len, size; u32 tx_flags = first->tx_flags; u16 i = tx_ring->next_to_use; u8 flags = fm10k_tx_desc_flags(skb, tx_flags); tx_desc = FM10K_TX_DESC(tx_ring, i); /* add HW VLAN tag */ if (skb_vlan_tag_present(skb)) tx_desc->vlan = cpu_to_le16(skb_vlan_tag_get(skb)); else tx_desc->vlan = 0; size = skb_headlen(skb); data = skb->data; dma = dma_map_single(tx_ring->dev, data, size, DMA_TO_DEVICE); data_len = skb->data_len; tx_buffer = first; for (frag = &skb_shinfo(skb)->frags[0];; frag++) { if (dma_mapping_error(tx_ring->dev, dma)) goto dma_error; /* record length, and DMA address */ dma_unmap_len_set(tx_buffer, len, size); dma_unmap_addr_set(tx_buffer, dma, dma); while (unlikely(size > FM10K_MAX_DATA_PER_TXD)) { if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++, dma, FM10K_MAX_DATA_PER_TXD, flags)) { tx_desc = FM10K_TX_DESC(tx_ring, 0); i = 0; } dma += FM10K_MAX_DATA_PER_TXD; size -= FM10K_MAX_DATA_PER_TXD; } if (likely(!data_len)) break; if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++, dma, size, flags)) { tx_desc = FM10K_TX_DESC(tx_ring, 0); i = 0; } size = skb_frag_size(frag); data_len -= size; dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size, DMA_TO_DEVICE); tx_buffer = &tx_ring->tx_buffer[i]; } /* write last descriptor with LAST bit set */ flags |= FM10K_TXD_FLAG_LAST; if (fm10k_tx_desc_push(tx_ring, tx_desc, i++, dma, size, flags)) i = 0; /* record bytecount for BQL */ netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount); /* record SW timestamp if HW timestamp is not available */ skb_tx_timestamp(first->skb); /* Force memory writes to complete before letting h/w know there * are new descriptors to fetch. (Only applicable for weak-ordered * memory model archs, such as IA-64). * * We also need this memory barrier to make certain all of the * status bits have been updated before next_to_watch is written. */ wmb(); /* set next_to_watch value indicating a packet is present */ first->next_to_watch = tx_desc; tx_ring->next_to_use = i; /* Make sure there is space in the ring for the next send. */ fm10k_maybe_stop_tx(tx_ring, DESC_NEEDED); /* notify HW of packet */ if (netif_xmit_stopped(txring_txq(tx_ring)) || !skb->xmit_more) { writel(i, tx_ring->tail); /* we need this if more than one processor can write to our tail * at a time, it synchronizes IO on IA64/Altix systems */ mmiowb(); } return; dma_error: dev_err(tx_ring->dev, "TX DMA map failed\n"); /* clear dma mappings for failed tx_buffer map */ for (;;) { tx_buffer = &tx_ring->tx_buffer[i]; fm10k_unmap_and_free_tx_resource(tx_ring, tx_buffer); if (tx_buffer == first) break; if (i == 0) i = tx_ring->count; i--; } tx_ring->next_to_use = i; } netdev_tx_t fm10k_xmit_frame_ring(struct sk_buff *skb, struct fm10k_ring *tx_ring) { u16 count = TXD_USE_COUNT(skb_headlen(skb)); struct fm10k_tx_buffer *first; unsigned short f; u32 tx_flags = 0; int tso; /* need: 1 descriptor per page * PAGE_SIZE/FM10K_MAX_DATA_PER_TXD, * + 1 desc for skb_headlen/FM10K_MAX_DATA_PER_TXD, * + 2 desc gap to keep tail from touching head * otherwise try next time */ for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) count += TXD_USE_COUNT(skb_shinfo(skb)->frags[f].size); if (fm10k_maybe_stop_tx(tx_ring, count + 3)) { tx_ring->tx_stats.tx_busy++; return NETDEV_TX_BUSY; } /* record the location of the first descriptor for this packet */ first = &tx_ring->tx_buffer[tx_ring->next_to_use]; first->skb = skb; first->bytecount = max_t(unsigned int, skb->len, ETH_ZLEN); first->gso_segs = 1; /* record initial flags and protocol */ first->tx_flags = tx_flags; tso = fm10k_tso(tx_ring, first); if (tso < 0) goto out_drop; else if (!tso) fm10k_tx_csum(tx_ring, first); fm10k_tx_map(tx_ring, first); return NETDEV_TX_OK; out_drop: dev_kfree_skb_any(first->skb); first->skb = NULL; return NETDEV_TX_OK; } static u64 fm10k_get_tx_completed(struct fm10k_ring *ring) { return ring->stats.packets; } /** * fm10k_get_tx_pending - how many Tx descriptors not processed * @ring: the ring structure * @in_sw: is tx_pending being checked in SW or in HW? */ u64 fm10k_get_tx_pending(struct fm10k_ring *ring, bool in_sw) { struct fm10k_intfc *interface = ring->q_vector->interface; struct fm10k_hw *hw = &interface->hw; u32 head, tail; if (likely(in_sw)) { head = ring->next_to_clean; tail = ring->next_to_use; } else { head = fm10k_read_reg(hw, FM10K_TDH(ring->reg_idx)); tail = fm10k_read_reg(hw, FM10K_TDT(ring->reg_idx)); } return ((head <= tail) ? tail : tail + ring->count) - head; } bool fm10k_check_tx_hang(struct fm10k_ring *tx_ring) { u32 tx_done = fm10k_get_tx_completed(tx_ring); u32 tx_done_old = tx_ring->tx_stats.tx_done_old; u32 tx_pending = fm10k_get_tx_pending(tx_ring, true); clear_check_for_tx_hang(tx_ring); /* Check for a hung queue, but be thorough. This verifies * that a transmit has been completed since the previous * check AND there is at least one packet pending. By * requiring this to fail twice we avoid races with * clearing the ARMED bit and conditions where we * run the check_tx_hang logic with a transmit completion * pending but without time to complete it yet. */ if (!tx_pending || (tx_done_old != tx_done)) { /* update completed stats and continue */ tx_ring->tx_stats.tx_done_old = tx_done; /* reset the countdown */ clear_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state); return false; } /* make sure it is true for two checks in a row */ return test_and_set_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state); } /** * fm10k_tx_timeout_reset - initiate reset due to Tx timeout * @interface: driver private struct **/ void fm10k_tx_timeout_reset(struct fm10k_intfc *interface) { /* Do the reset outside of interrupt context */ if (!test_bit(__FM10K_DOWN, interface->state)) { interface->tx_timeout_count++; set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); fm10k_service_event_schedule(interface); } } /** * fm10k_clean_tx_irq - Reclaim resources after transmit completes * @q_vector: structure containing interrupt and ring information * @tx_ring: tx ring to clean * @napi_budget: Used to determine if we are in netpoll **/ static bool fm10k_clean_tx_irq(struct fm10k_q_vector *q_vector, struct fm10k_ring *tx_ring, int napi_budget) { struct fm10k_intfc *interface = q_vector->interface; struct fm10k_tx_buffer *tx_buffer; struct fm10k_tx_desc *tx_desc; unsigned int total_bytes = 0, total_packets = 0; unsigned int budget = q_vector->tx.work_limit; unsigned int i = tx_ring->next_to_clean; if (test_bit(__FM10K_DOWN, interface->state)) return true; tx_buffer = &tx_ring->tx_buffer[i]; tx_desc = FM10K_TX_DESC(tx_ring, i); i -= tx_ring->count; do { struct fm10k_tx_desc *eop_desc = tx_buffer->next_to_watch; /* if next_to_watch is not set then there is no work pending */ if (!eop_desc) break; /* prevent any other reads prior to eop_desc */ smp_rmb(); /* if DD is not set pending work has not been completed */ if (!(eop_desc->flags & FM10K_TXD_FLAG_DONE)) break; /* clear next_to_watch to prevent false hangs */ tx_buffer->next_to_watch = NULL; /* update the statistics for this packet */ total_bytes += tx_buffer->bytecount; total_packets += tx_buffer->gso_segs; /* free the skb */ napi_consume_skb(tx_buffer->skb, napi_budget); /* unmap skb header data */ dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); /* clear tx_buffer data */ tx_buffer->skb = NULL; dma_unmap_len_set(tx_buffer, len, 0); /* unmap remaining buffers */ while (tx_desc != eop_desc) { tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer; tx_desc = FM10K_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buffer, len)) { dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer, len, 0); } } /* move us one more past the eop_desc for start of next pkt */ tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer; tx_desc = FM10K_TX_DESC(tx_ring, 0); } /* issue prefetch for next Tx descriptor */ prefetch(tx_desc); /* update budget accounting */ budget--; } while (likely(budget)); i += tx_ring->count; tx_ring->next_to_clean = i; u64_stats_update_begin(&tx_ring->syncp); tx_ring->stats.bytes += total_bytes; tx_ring->stats.packets += total_packets; u64_stats_update_end(&tx_ring->syncp); q_vector->tx.total_bytes += total_bytes; q_vector->tx.total_packets += total_packets; if (check_for_tx_hang(tx_ring) && fm10k_check_tx_hang(tx_ring)) { /* schedule immediate reset if we believe we hung */ struct fm10k_hw *hw = &interface->hw; netif_err(interface, drv, tx_ring->netdev, "Detected Tx Unit Hang\n" " Tx Queue <%d>\n" " TDH, TDT <%x>, <%x>\n" " next_to_use <%x>\n" " next_to_clean <%x>\n", tx_ring->queue_index, fm10k_read_reg(hw, FM10K_TDH(tx_ring->reg_idx)), fm10k_read_reg(hw, FM10K_TDT(tx_ring->reg_idx)), tx_ring->next_to_use, i); netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index); netif_info(interface, probe, tx_ring->netdev, "tx hang %d detected on queue %d, resetting interface\n", interface->tx_timeout_count + 1, tx_ring->queue_index); fm10k_tx_timeout_reset(interface); /* the netdev is about to reset, no point in enabling stuff */ return true; } /* notify netdev of completed buffers */ netdev_tx_completed_queue(txring_txq(tx_ring), total_packets, total_bytes); #define TX_WAKE_THRESHOLD min_t(u16, FM10K_MIN_TXD - 1, DESC_NEEDED * 2) if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) && (fm10k_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD))) { /* Make sure that anybody stopping the queue after this * sees the new next_to_clean. */ smp_mb(); if (__netif_subqueue_stopped(tx_ring->netdev, tx_ring->queue_index) && !test_bit(__FM10K_DOWN, interface->state)) { netif_wake_subqueue(tx_ring->netdev, tx_ring->queue_index); ++tx_ring->tx_stats.restart_queue; } } return !!budget; } /** * fm10k_update_itr - update the dynamic ITR value based on packet size * * Stores a new ITR value based on strictly on packet size. The * divisors and thresholds used by this function were determined based * on theoretical maximum wire speed and testing data, in order to * minimize response time while increasing bulk throughput. * * @ring_container: Container for rings to have ITR updated **/ static void fm10k_update_itr(struct fm10k_ring_container *ring_container) { unsigned int avg_wire_size, packets, itr_round; /* Only update ITR if we are using adaptive setting */ if (!ITR_IS_ADAPTIVE(ring_container->itr)) goto clear_counts; packets = ring_container->total_packets; if (!packets) goto clear_counts; avg_wire_size = ring_container->total_bytes / packets; /* The following is a crude approximation of: * wmem_default / (size + overhead) = desired_pkts_per_int * rate / bits_per_byte / (size + ethernet overhead) = pkt_rate * (desired_pkt_rate / pkt_rate) * usecs_per_sec = ITR value * * Assuming wmem_default is 212992 and overhead is 640 bytes per * packet, (256 skb, 64 headroom, 320 shared info), we can reduce the * formula down to * * (34 * (size + 24)) / (size + 640) = ITR * * We first do some math on the packet size and then finally bitshift * by 8 after rounding up. We also have to account for PCIe link speed * difference as ITR scales based on this. */ if (avg_wire_size <= 360) { /* Start at 250K ints/sec and gradually drop to 77K ints/sec */ avg_wire_size *= 8; avg_wire_size += 376; } else if (avg_wire_size <= 1152) { /* 77K ints/sec to 45K ints/sec */ avg_wire_size *= 3; avg_wire_size += 2176; } else if (avg_wire_size <= 1920) { /* 45K ints/sec to 38K ints/sec */ avg_wire_size += 4480; } else { /* plateau at a limit of 38K ints/sec */ avg_wire_size = 6656; } /* Perform final bitshift for division after rounding up to ensure * that the calculation will never get below a 1. The bit shift * accounts for changes in the ITR due to PCIe link speed. */ itr_round = READ_ONCE(ring_container->itr_scale) + 8; avg_wire_size += BIT(itr_round) - 1; avg_wire_size >>= itr_round; /* write back value and retain adaptive flag */ ring_container->itr = avg_wire_size | FM10K_ITR_ADAPTIVE; clear_counts: ring_container->total_bytes = 0; ring_container->total_packets = 0; } static void fm10k_qv_enable(struct fm10k_q_vector *q_vector) { /* Enable auto-mask and clear the current mask */ u32 itr = FM10K_ITR_ENABLE; /* Update Tx ITR */ fm10k_update_itr(&q_vector->tx); /* Update Rx ITR */ fm10k_update_itr(&q_vector->rx); /* Store Tx itr in timer slot 0 */ itr |= (q_vector->tx.itr & FM10K_ITR_MAX); /* Shift Rx itr to timer slot 1 */ itr |= (q_vector->rx.itr & FM10K_ITR_MAX) << FM10K_ITR_INTERVAL1_SHIFT; /* Write the final value to the ITR register */ writel(itr, q_vector->itr); } static int fm10k_poll(struct napi_struct *napi, int budget) { struct fm10k_q_vector *q_vector = container_of(napi, struct fm10k_q_vector, napi); struct fm10k_ring *ring; int per_ring_budget, work_done = 0; bool clean_complete = true; fm10k_for_each_ring(ring, q_vector->tx) { if (!fm10k_clean_tx_irq(q_vector, ring, budget)) clean_complete = false; } /* Handle case where we are called by netpoll with a budget of 0 */ if (budget <= 0) return budget; /* attempt to distribute budget to each queue fairly, but don't * allow the budget to go below 1 because we'll exit polling */ if (q_vector->rx.count > 1) per_ring_budget = max(budget / q_vector->rx.count, 1); else per_ring_budget = budget; fm10k_for_each_ring(ring, q_vector->rx) { int work = fm10k_clean_rx_irq(q_vector, ring, per_ring_budget); work_done += work; if (work >= per_ring_budget) clean_complete = false; } /* If all work not completed, return budget and keep polling */ if (!clean_complete) return budget; /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (likely(napi_complete_done(napi, work_done))) fm10k_qv_enable(q_vector); return min(work_done, budget - 1); } /** * fm10k_set_qos_queues: Allocate queues for a QOS-enabled device * @interface: board private structure to initialize * * When QoS (Quality of Service) is enabled, allocate queues for * each traffic class. If multiqueue isn't available,then abort QoS * initialization. * * This function handles all combinations of Qos and RSS. * **/ static bool fm10k_set_qos_queues(struct fm10k_intfc *interface) { struct net_device *dev = interface->netdev; struct fm10k_ring_feature *f; int rss_i, i; int pcs; /* Map queue offset and counts onto allocated tx queues */ pcs = netdev_get_num_tc(dev); if (pcs <= 1) return false; /* set QoS mask and indices */ f = &interface->ring_feature[RING_F_QOS]; f->indices = pcs; f->mask = BIT(fls(pcs - 1)) - 1; /* determine the upper limit for our current DCB mode */ rss_i = interface->hw.mac.max_queues / pcs; rss_i = BIT(fls(rss_i) - 1); /* set RSS mask and indices */ f = &interface->ring_feature[RING_F_RSS]; rss_i = min_t(u16, rss_i, f->limit); f->indices = rss_i; f->mask = BIT(fls(rss_i - 1)) - 1; /* configure pause class to queue mapping */ for (i = 0; i < pcs; i++) netdev_set_tc_queue(dev, i, rss_i, rss_i * i); interface->num_rx_queues = rss_i * pcs; interface->num_tx_queues = rss_i * pcs; return true; } /** * fm10k_set_rss_queues: Allocate queues for RSS * @interface: board private structure to initialize * * This is our "base" multiqueue mode. RSS (Receive Side Scaling) will try * to allocate one Rx queue per CPU, and if available, one Tx queue per CPU. * **/ static bool fm10k_set_rss_queues(struct fm10k_intfc *interface) { struct fm10k_ring_feature *f; u16 rss_i; f = &interface->ring_feature[RING_F_RSS]; rss_i = min_t(u16, interface->hw.mac.max_queues, f->limit); /* record indices and power of 2 mask for RSS */ f->indices = rss_i; f->mask = BIT(fls(rss_i - 1)) - 1; interface->num_rx_queues = rss_i; interface->num_tx_queues = rss_i; return true; } /** * fm10k_set_num_queues: Allocate queues for device, feature dependent * @interface: board private structure to initialize * * This is the top level queue allocation routine. The order here is very * important, starting with the "most" number of features turned on at once, * and ending with the smallest set of features. This way large combinations * can be allocated if they're turned on, and smaller combinations are the * fallthrough conditions. * **/ static void fm10k_set_num_queues(struct fm10k_intfc *interface) { /* Attempt to setup QoS and RSS first */ if (fm10k_set_qos_queues(interface)) return; /* If we don't have QoS, just fallback to only RSS. */ fm10k_set_rss_queues(interface); } /** * fm10k_reset_num_queues - Reset the number of queues to zero * @interface: board private structure * * This function should be called whenever we need to reset the number of * queues after an error condition. */ static void fm10k_reset_num_queues(struct fm10k_intfc *interface) { interface->num_tx_queues = 0; interface->num_rx_queues = 0; interface->num_q_vectors = 0; } /** * fm10k_alloc_q_vector - Allocate memory for a single interrupt vector * @interface: board private structure to initialize * @v_count: q_vectors allocated on interface, used for ring interleaving * @v_idx: index of vector in interface struct * @txr_count: total number of Tx rings to allocate * @txr_idx: index of first Tx ring to allocate * @rxr_count: total number of Rx rings to allocate * @rxr_idx: index of first Rx ring to allocate * * We allocate one q_vector. If allocation fails we return -ENOMEM. **/ static int fm10k_alloc_q_vector(struct fm10k_intfc *interface, unsigned int v_count, unsigned int v_idx, unsigned int txr_count, unsigned int txr_idx, unsigned int rxr_count, unsigned int rxr_idx) { struct fm10k_q_vector *q_vector; struct fm10k_ring *ring; int ring_count; ring_count = txr_count + rxr_count; /* allocate q_vector and rings */ q_vector = kzalloc(struct_size(q_vector, ring, ring_count), GFP_KERNEL); if (!q_vector) return -ENOMEM; /* initialize NAPI */ netif_napi_add(interface->netdev, &q_vector->napi, fm10k_poll, NAPI_POLL_WEIGHT); /* tie q_vector and interface together */ interface->q_vector[v_idx] = q_vector; q_vector->interface = interface; q_vector->v_idx = v_idx; /* initialize pointer to rings */ ring = q_vector->ring; /* save Tx ring container info */ q_vector->tx.ring = ring; q_vector->tx.work_limit = FM10K_DEFAULT_TX_WORK; q_vector->tx.itr = interface->tx_itr; q_vector->tx.itr_scale = interface->hw.mac.itr_scale; q_vector->tx.count = txr_count; while (txr_count) { /* assign generic ring traits */ ring->dev = &interface->pdev->dev; ring->netdev = interface->netdev; /* configure backlink on ring */ ring->q_vector = q_vector; /* apply Tx specific ring traits */ ring->count = interface->tx_ring_count; ring->queue_index = txr_idx; /* assign ring to interface */ interface->tx_ring[txr_idx] = ring; /* update count and index */ txr_count--; txr_idx += v_count; /* push pointer to next ring */ ring++; } /* save Rx ring container info */ q_vector->rx.ring = ring; q_vector->rx.itr = interface->rx_itr; q_vector->rx.itr_scale = interface->hw.mac.itr_scale; q_vector->rx.count = rxr_count; while (rxr_count) { /* assign generic ring traits */ ring->dev = &interface->pdev->dev; ring->netdev = interface->netdev; rcu_assign_pointer(ring->l2_accel, interface->l2_accel); /* configure backlink on ring */ ring->q_vector = q_vector; /* apply Rx specific ring traits */ ring->count = interface->rx_ring_count; ring->queue_index = rxr_idx; /* assign ring to interface */ interface->rx_ring[rxr_idx] = ring; /* update count and index */ rxr_count--; rxr_idx += v_count; /* push pointer to next ring */ ring++; } fm10k_dbg_q_vector_init(q_vector); return 0; } /** * fm10k_free_q_vector - Free memory allocated for specific interrupt vector * @interface: board private structure to initialize * @v_idx: Index of vector to be freed * * This function frees the memory allocated to the q_vector. In addition if * NAPI is enabled it will delete any references to the NAPI struct prior * to freeing the q_vector. **/ static void fm10k_free_q_vector(struct fm10k_intfc *interface, int v_idx) { struct fm10k_q_vector *q_vector = interface->q_vector[v_idx]; struct fm10k_ring *ring; fm10k_dbg_q_vector_exit(q_vector); fm10k_for_each_ring(ring, q_vector->tx) interface->tx_ring[ring->queue_index] = NULL; fm10k_for_each_ring(ring, q_vector->rx) interface->rx_ring[ring->queue_index] = NULL; interface->q_vector[v_idx] = NULL; netif_napi_del(&q_vector->napi); kfree_rcu(q_vector, rcu); } /** * fm10k_alloc_q_vectors - Allocate memory for interrupt vectors * @interface: board private structure to initialize * * We allocate one q_vector per queue interrupt. If allocation fails we * return -ENOMEM. **/ static int fm10k_alloc_q_vectors(struct fm10k_intfc *interface) { unsigned int q_vectors = interface->num_q_vectors; unsigned int rxr_remaining = interface->num_rx_queues; unsigned int txr_remaining = interface->num_tx_queues; unsigned int rxr_idx = 0, txr_idx = 0, v_idx = 0; int err; if (q_vectors >= (rxr_remaining + txr_remaining)) { for (; rxr_remaining; v_idx++) { err = fm10k_alloc_q_vector(interface, q_vectors, v_idx, 0, 0, 1, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining--; rxr_idx++; } } for (; v_idx < q_vectors; v_idx++) { int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx); int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx); err = fm10k_alloc_q_vector(interface, q_vectors, v_idx, tqpv, txr_idx, rqpv, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining -= rqpv; txr_remaining -= tqpv; rxr_idx++; txr_idx++; } return 0; err_out: fm10k_reset_num_queues(interface); while (v_idx--) fm10k_free_q_vector(interface, v_idx); return -ENOMEM; } /** * fm10k_free_q_vectors - Free memory allocated for interrupt vectors * @interface: board private structure to initialize * * This function frees the memory allocated to the q_vectors. In addition if * NAPI is enabled it will delete any references to the NAPI struct prior * to freeing the q_vector. **/ static void fm10k_free_q_vectors(struct fm10k_intfc *interface) { int v_idx = interface->num_q_vectors; fm10k_reset_num_queues(interface); while (v_idx--) fm10k_free_q_vector(interface, v_idx); } /** * f10k_reset_msix_capability - reset MSI-X capability * @interface: board private structure to initialize * * Reset the MSI-X capability back to its starting state **/ static void fm10k_reset_msix_capability(struct fm10k_intfc *interface) { pci_disable_msix(interface->pdev); kfree(interface->msix_entries); interface->msix_entries = NULL; } /** * f10k_init_msix_capability - configure MSI-X capability * @interface: board private structure to initialize * * Attempt to configure the interrupts using the best available * capabilities of the hardware and the kernel. **/ static int fm10k_init_msix_capability(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; int v_budget, vector; /* It's easy to be greedy for MSI-X vectors, but it really * doesn't do us much good if we have a lot more vectors * than CPU's. So let's be conservative and only ask for * (roughly) the same number of vectors as there are CPU's. * the default is to use pairs of vectors */ v_budget = max(interface->num_rx_queues, interface->num_tx_queues); v_budget = min_t(u16, v_budget, num_online_cpus()); /* account for vectors not related to queues */ v_budget += NON_Q_VECTORS(hw); /* At the same time, hardware can only support a maximum of * hw.mac->max_msix_vectors vectors. With features * such as RSS and VMDq, we can easily surpass the number of Rx and Tx * descriptor queues supported by our device. Thus, we cap it off in * those rare cases where the cpu count also exceeds our vector limit. */ v_budget = min_t(int, v_budget, hw->mac.max_msix_vectors); /* A failure in MSI-X entry allocation is fatal. */ interface->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry), GFP_KERNEL); if (!interface->msix_entries) return -ENOMEM; /* populate entry values */ for (vector = 0; vector < v_budget; vector++) interface->msix_entries[vector].entry = vector; /* Attempt to enable MSI-X with requested value */ v_budget = pci_enable_msix_range(interface->pdev, interface->msix_entries, MIN_MSIX_COUNT(hw), v_budget); if (v_budget < 0) { kfree(interface->msix_entries); interface->msix_entries = NULL; return v_budget; } /* record the number of queues available for q_vectors */ interface->num_q_vectors = v_budget - NON_Q_VECTORS(hw); return 0; } /** * fm10k_cache_ring_qos - Descriptor ring to register mapping for QoS * @interface: Interface structure continaining rings and devices * * Cache the descriptor ring offsets for Qos **/ static bool fm10k_cache_ring_qos(struct fm10k_intfc *interface) { struct net_device *dev = interface->netdev; int pc, offset, rss_i, i, q_idx; u16 pc_stride = interface->ring_feature[RING_F_QOS].mask + 1; u8 num_pcs = netdev_get_num_tc(dev); if (num_pcs <= 1) return false; rss_i = interface->ring_feature[RING_F_RSS].indices; for (pc = 0, offset = 0; pc < num_pcs; pc++, offset += rss_i) { q_idx = pc; for (i = 0; i < rss_i; i++) { interface->tx_ring[offset + i]->reg_idx = q_idx; interface->tx_ring[offset + i]->qos_pc = pc; interface->rx_ring[offset + i]->reg_idx = q_idx; interface->rx_ring[offset + i]->qos_pc = pc; q_idx += pc_stride; } } return true; } /** * fm10k_cache_ring_rss - Descriptor ring to register mapping for RSS * @interface: Interface structure continaining rings and devices * * Cache the descriptor ring offsets for RSS **/ static void fm10k_cache_ring_rss(struct fm10k_intfc *interface) { int i; for (i = 0; i < interface->num_rx_queues; i++) interface->rx_ring[i]->reg_idx = i; for (i = 0; i < interface->num_tx_queues; i++) interface->tx_ring[i]->reg_idx = i; } /** * fm10k_assign_rings - Map rings to network devices * @interface: Interface structure containing rings and devices * * This function is meant to go though and configure both the network * devices so that they contain rings, and configure the rings so that * they function with their network devices. **/ static void fm10k_assign_rings(struct fm10k_intfc *interface) { if (fm10k_cache_ring_qos(interface)) return; fm10k_cache_ring_rss(interface); } static void fm10k_init_reta(struct fm10k_intfc *interface) { u16 i, rss_i = interface->ring_feature[RING_F_RSS].indices; u32 reta; /* If the Rx flow indirection table has been configured manually, we * need to maintain it when possible. */ if (netif_is_rxfh_configured(interface->netdev)) { for (i = FM10K_RETA_SIZE; i--;) { reta = interface->reta[i]; if ((((reta << 24) >> 24) < rss_i) && (((reta << 16) >> 24) < rss_i) && (((reta << 8) >> 24) < rss_i) && (((reta) >> 24) < rss_i)) continue; /* this should never happen */ dev_err(&interface->pdev->dev, "RSS indirection table assigned flows out of queue bounds. Reconfiguring.\n"); goto repopulate_reta; } /* do nothing if all of the elements are in bounds */ return; } repopulate_reta: fm10k_write_reta(interface, NULL); } /** * fm10k_init_queueing_scheme - Determine proper queueing scheme * @interface: board private structure to initialize * * We determine which queueing scheme to use based on... * - Hardware queue count (num_*_queues) * - defined by miscellaneous hardware support/features (RSS, etc.) **/ int fm10k_init_queueing_scheme(struct fm10k_intfc *interface) { int err; /* Number of supported queues */ fm10k_set_num_queues(interface); /* Configure MSI-X capability */ err = fm10k_init_msix_capability(interface); if (err) { dev_err(&interface->pdev->dev, "Unable to initialize MSI-X capability\n"); goto err_init_msix; } /* Allocate memory for queues */ err = fm10k_alloc_q_vectors(interface); if (err) { dev_err(&interface->pdev->dev, "Unable to allocate queue vectors\n"); goto err_alloc_q_vectors; } /* Map rings to devices, and map devices to physical queues */ fm10k_assign_rings(interface); /* Initialize RSS redirection table */ fm10k_init_reta(interface); return 0; err_alloc_q_vectors: fm10k_reset_msix_capability(interface); err_init_msix: fm10k_reset_num_queues(interface); return err; } /** * fm10k_clear_queueing_scheme - Clear the current queueing scheme settings * @interface: board private structure to clear queueing scheme on * * We go through and clear queueing specific resources and reset the structure * to pre-load conditions **/ void fm10k_clear_queueing_scheme(struct fm10k_intfc *interface) { fm10k_free_q_vectors(interface); fm10k_reset_msix_capability(interface); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_1062_0
crossvul-cpp_data_bad_5715_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Server Peer * * Copyright 2011 Vic Lee * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "certificate.h" #include <freerdp/utils/tcp.h> #include "peer.h" static BOOL freerdp_peer_initialize(freerdp_peer* client) { client->context->rdp->settings->ServerMode = TRUE; client->context->rdp->settings->FrameAcknowledge = 0; client->context->rdp->settings->LocalConnection = client->local; client->context->rdp->state = CONNECTION_STATE_INITIAL; if (client->context->rdp->settings->RdpKeyFile != NULL) { client->context->rdp->settings->RdpServerRsaKey = key_new(client->context->rdp->settings->RdpKeyFile); } return TRUE; } static BOOL freerdp_peer_get_fds(freerdp_peer* client, void** rfds, int* rcount) { rfds[*rcount] = (void*)(long)(client->context->rdp->transport->TcpIn->sockfd); (*rcount)++; return TRUE; } static BOOL freerdp_peer_check_fds(freerdp_peer* client) { int status; rdpRdp* rdp; rdp = client->context->rdp; status = rdp_check_fds(rdp); if (status < 0) return FALSE; return TRUE; } static BOOL peer_recv_data_pdu(freerdp_peer* client, wStream* s) { BYTE type; UINT16 length; UINT32 share_id; BYTE compressed_type; UINT16 compressed_len; if (!rdp_read_share_data_header(s, &length, &type, &share_id, &compressed_type, &compressed_len)) return FALSE; switch (type) { case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_client_synchronize_pdu(client->context->rdp, s)) return FALSE; break; case DATA_PDU_TYPE_CONTROL: if (!rdp_server_accept_client_control_pdu(client->context->rdp, s)) return FALSE; break; case DATA_PDU_TYPE_INPUT: if (!input_recv(client->context->rdp->input, s)) return FALSE; break; case DATA_PDU_TYPE_BITMAP_CACHE_PERSISTENT_LIST: /* TODO: notify server bitmap cache data */ break; case DATA_PDU_TYPE_FONT_LIST: if (!rdp_server_accept_client_font_list_pdu(client->context->rdp, s)) return FALSE; if (!client->connected) { /** * PostConnect should only be called once and should not be called * after a reactivation sequence. */ IFCALLRET(client->PostConnect, client->connected, client); if (!client->connected) return FALSE; } if (!client->activated) { /* Activate will be called everytime after the client is activated/reactivated. */ IFCALLRET(client->Activate, client->activated, client); if (!client->activated) return FALSE; } break; case DATA_PDU_TYPE_SHUTDOWN_REQUEST: mcs_send_disconnect_provider_ultimatum(client->context->rdp->mcs); return FALSE; case DATA_PDU_TYPE_FRAME_ACKNOWLEDGE: if(Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, client->ack_frame_id); IFCALL(client->update->SurfaceFrameAcknowledge, client->update->context, client->ack_frame_id); break; case DATA_PDU_TYPE_REFRESH_RECT: if (!update_read_refresh_rect(client->update, s)) return FALSE; break; case DATA_PDU_TYPE_SUPPRESS_OUTPUT: if (!update_read_suppress_output(client->update, s)) return FALSE; break; default: fprintf(stderr, "Data PDU type %d\n", type); break; } return TRUE; } static int peer_recv_tpkt_pdu(freerdp_peer* client, wStream* s) { rdpRdp* rdp; UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId; UINT16 securityFlags; rdp = client->context->rdp; if (!rdp_read_header(rdp, s, &length, &channelId)) { fprintf(stderr, "Incorrect RDP header.\n"); return -1; } if (rdp->settings->DisableEncryption) { if (!rdp_read_security_header(s, &securityFlags)) return -1; if (securityFlags & SEC_ENCRYPT) { if (!rdp_decrypt(rdp, s, length - 4, securityFlags)) { fprintf(stderr, "rdp_decrypt failed\n"); return -1; } } } if (channelId != MCS_GLOBAL_CHANNEL_ID) { if(!freerdp_channel_peer_process(client, s, channelId)) return -1; } else { if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) return -1; client->settings->PduSource = pduSource; switch (pduType) { case PDU_TYPE_DATA: if (!peer_recv_data_pdu(client, s)) return -1; break; default: fprintf(stderr, "Client sent pduType %d\n", pduType); return -1; } } return 0; } static int peer_recv_fastpath_pdu(freerdp_peer* client, wStream* s) { rdpRdp* rdp; UINT16 length; rdpFastPath* fastpath; rdp = client->context->rdp; fastpath = rdp->fastpath; //if (!fastpath_read_header_rdp(fastpath, s, &length)) // return -1; fastpath_read_header_rdp(fastpath, s, &length); if ((length == 0) || (length > Stream_GetRemainingLength(s))) { fprintf(stderr, "incorrect FastPath PDU header length %d\n", length); return -1; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { if (!rdp_decrypt(rdp, s, length, (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0)) return -1; } return fastpath_recv_inputs(fastpath, s); } static int peer_recv_pdu(freerdp_peer* client, wStream* s) { if (tpkt_verify_header(s)) return peer_recv_tpkt_pdu(client, s); else return peer_recv_fastpath_pdu(client, s); } static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, "Invalid state %d\n", rdp->state); return -1; } return 0; } static BOOL freerdp_peer_close(freerdp_peer* client) { /** * [MS-RDPBCGR] 1.3.1.4.2 User-Initiated Disconnection Sequence on Server * The server first sends the client a Deactivate All PDU followed by an * optional MCS Disconnect Provider Ultimatum PDU. */ if (!rdp_send_deactivate_all(client->context->rdp)) return FALSE; return mcs_send_disconnect_provider_ultimatum(client->context->rdp->mcs); } static void freerdp_peer_disconnect(freerdp_peer* client) { transport_disconnect(client->context->rdp->transport); } static int freerdp_peer_send_channel_data(freerdp_peer* client, int channelId, BYTE* data, int size) { return rdp_send_channel_data(client->context->rdp, channelId, data, size); } void freerdp_peer_context_new(freerdp_peer* client) { rdpRdp* rdp; rdp = rdp_new(NULL); client->input = rdp->input; client->update = rdp->update; client->settings = rdp->settings; client->context = (rdpContext*) malloc(client->ContextSize); ZeroMemory(client->context, client->ContextSize); client->context->rdp = rdp; client->context->peer = client; client->context->input = client->input; client->context->update = client->update; client->context->settings = client->settings; client->update->context = client->context; client->input->context = client->context; update_register_server_callbacks(client->update); transport_attach(rdp->transport, client->sockfd); rdp->transport->ReceiveCallback = peer_recv_callback; rdp->transport->ReceiveExtra = client; transport_set_blocking_mode(rdp->transport, FALSE); IFCALL(client->ContextNew, client, client->context); } void freerdp_peer_context_free(freerdp_peer* client) { IFCALL(client->ContextFree, client, client->context); } freerdp_peer* freerdp_peer_new(int sockfd) { freerdp_peer* client; client = (freerdp_peer*) malloc(sizeof(freerdp_peer)); ZeroMemory(client, sizeof(freerdp_peer)); freerdp_tcp_set_no_delay(sockfd, TRUE); if (client != NULL) { client->sockfd = sockfd; client->ContextSize = sizeof(rdpContext); client->Initialize = freerdp_peer_initialize; client->GetFileDescriptor = freerdp_peer_get_fds; client->CheckFileDescriptor = freerdp_peer_check_fds; client->Close = freerdp_peer_close; client->Disconnect = freerdp_peer_disconnect; client->SendChannelData = freerdp_peer_send_channel_data; } return client; } void freerdp_peer_free(freerdp_peer* client) { if (client) { rdp_free(client->context->rdp); free(client->context); free(client); } }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5715_1
crossvul-cpp_data_bad_5488_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5488_3
crossvul-cpp_data_good_1275_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, &regFree1); r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2); 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) ){ 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, &regToFree); } 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 ){ sqlite3ExprCode(pParse, pCol->pDflt, regOut); if( pCol->affinity>=SQLITE_AFF_TEXT ){ sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); } } #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 ){ sqlite3VdbeChangeP5(pParse->pVdbe, 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){ assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); 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; } case 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, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); 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, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); 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, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2); 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, &regFree1); 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, &regFree1); 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, &regFree1); 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 + (iCol>=0 ? sqlite3TableColumnToStorage(pTab, iCol) : -1); 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. */ default: assert( op==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, &regFree1)); 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, &regFree1)); 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, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); 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, &regFree1); 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, &regFree1); 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, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); 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, &regFree1); 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, &regFree1); 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-476/c/good_1275_2
crossvul-cpp_data_bad_5363_1
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Windows Bitmap File Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <assert.h> #include "jasper/jas_types.h" #include "jasper/jas_stream.h" #include "jasper/jas_image.h" #include "jasper/jas_malloc.h" #include "bmp_cod.h" /******************************************************************************\ * Local prototypes. \******************************************************************************/ static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr); static bmp_info_t *bmp_getinfo(jas_stream_t *in); static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image); static int bmp_getint16(jas_stream_t *in, int_fast16_t *val); static int bmp_getint32(jas_stream_t *in, int_fast32_t *val); static int bmp_gobble(jas_stream_t *in, long n); /******************************************************************************\ * Interface functions. \******************************************************************************/ jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; } int bmp_validate(jas_stream_t *in) { int n; int i; uchar buf[2]; assert(JAS_STREAM_MAXPUTBACK >= 2); /* Read the first two characters that constitute the signature. */ if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { return -1; } /* Put the characters read back onto the stream. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough characters? */ if (n < 2) { return -1; } /* Is the signature correct for the BMP format? */ if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) { return 0; } return -1; } /******************************************************************************\ * Code for aggregate types. \******************************************************************************/ static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr) { if (bmp_getint16(in, &hdr->magic) || hdr->magic != BMP_MAGIC || bmp_getint32(in, &hdr->siz) || bmp_getint16(in, &hdr->reserved1) || bmp_getint16(in, &hdr->reserved2) || bmp_getint32(in, &hdr->off)) { return -1; } return 0; } static bmp_info_t *bmp_getinfo(jas_stream_t *in) { bmp_info_t *info; int i; bmp_palent_t *palent; if (!(info = bmp_info_create())) { return 0; } if (bmp_getint32(in, &info->len) || info->len != 40 || bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) || bmp_getint16(in, &info->numplanes) || bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) || bmp_getint32(in, &info->siz) || bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) || bmp_getint32(in, &info->numcolors) || bmp_getint32(in, &info->mincolors)) { bmp_info_destroy(info); return 0; } if (info->height < 0) { info->topdown = 1; info->height = -info->height; } else { info->topdown = 0; } if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 || info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) { bmp_info_destroy(info); return 0; } if (info->enctype != BMP_ENC_RGB) { jas_eprintf("unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } if (info->numcolors > 0) { if (!(info->palents = jas_alloc2(info->numcolors, sizeof(bmp_palent_t)))) { bmp_info_destroy(info); return 0; } } else { info->palents = 0; } for (i = 0; i < info->numcolors; ++i) { palent = &info->palents[i]; if ((palent->blu = jas_stream_getc(in)) == EOF || (palent->grn = jas_stream_getc(in)) == EOF || (palent->red = jas_stream_getc(in)) == EOF || (palent->res = jas_stream_getc(in)) == EOF) { bmp_info_destroy(info); return 0; } } return info; } static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image) { int i; int j; int y; jas_matrix_t *cmpts[3]; int numpad; int red; int grn; int blu; int ret; int numcmpts; int cmptno; int ind; bmp_palent_t *palent; int mxind; int haspal; assert(info->depth == 8 || info->depth == 24); assert(info->enctype == BMP_ENC_RGB); numcmpts = bmp_numcmpts(info); haspal = bmp_haspal(info); ret = 0; for (i = 0; i < numcmpts; ++i) { cmpts[i] = 0; } /* Create temporary matrices to hold component data. */ for (i = 0; i < numcmpts; ++i) { if (!(cmpts[i] = jas_matrix_create(1, info->width))) { ret = -1; goto bmp_getdata_done; } } /* Calculate number of padding bytes per row of image data. */ numpad = (numcmpts * info->width) % 4; if (numpad) { numpad = 4 - numpad; } mxind = (1 << info->depth) - 1; for (i = 0; i < info->height; ++i) { for (j = 0; j < info->width; ++j) { if (haspal) { if ((ind = jas_stream_getc(in)) == EOF) { ret = -1; goto bmp_getdata_done; } if (ind > mxind) { ret = -1; goto bmp_getdata_done; } if (ind < info->numcolors) { palent = &info->palents[ind]; red = palent->red; grn = palent->grn; blu = palent->blu; } else { red = ind; grn = ind; blu = ind; } } else { if ((blu = jas_stream_getc(in)) == EOF || (grn = jas_stream_getc(in)) == EOF || (red = jas_stream_getc(in)) == EOF) { ret = -1; goto bmp_getdata_done; } } if (numcmpts == 3) { jas_matrix_setv(cmpts[0], j, red); jas_matrix_setv(cmpts[1], j, grn); jas_matrix_setv(cmpts[2], j, blu); } else { jas_matrix_setv(cmpts[0], j, red); } } for (j = numpad; j > 0; --j) { if (jas_stream_getc(in) == EOF) { ret = -1; goto bmp_getdata_done; } } for (cmptno = 0; cmptno < numcmpts; ++cmptno) { y = info->topdown ? i : (info->height - 1 - i); if (jas_image_writecmpt(image, cmptno, 0, y, info->width, 1, cmpts[cmptno])) { ret = -1; goto bmp_getdata_done; } } } bmp_getdata_done: /* Destroy the temporary matrices. */ for (i = 0; i < numcmpts; ++i) { if (cmpts[i]) { jas_matrix_destroy(cmpts[i]); } } return ret; } /******************************************************************************\ * Code for primitive types. \******************************************************************************/ static int bmp_getint16(jas_stream_t *in, int_fast16_t *val) { int lo; int hi; if ((lo = jas_stream_getc(in)) == EOF || (hi = jas_stream_getc(in)) == EOF) { return -1; } if (val) { *val = (hi << 8) | lo; } return 0; } static int bmp_getint32(jas_stream_t *in, int_fast32_t *val) { int n; uint_fast32_t v; int c; for (n = 4, v = 0;;) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } v |= (c << 24); if (--n <= 0) { break; } v >>= 8; } if (val) { *val = v; } return 0; } static int bmp_gobble(jas_stream_t *in, long n) { while (--n >= 0) { if (jas_stream_getc(in) == EOF) { return -1; } } return 0; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5363_1
crossvul-cpp_data_bad_5485_2
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT X X TTTTT % % T X X T % % T X T % % T X X T % % T X X T % % % % % % Render Text Onto A Canvas Image. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 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 "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteTXTImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T X T % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTXT() returns MagickTrue if the image format type, identified by the magick % string, is TXT. % % The format of the IsTXT method is: % % MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length) { #define MagickID "# ImageMagick pixel enumeration:" char colorspace[MagickPathExtent]; ssize_t count; unsigned long columns, depth, rows; if (length < 40) return(MagickFalse); if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0) return(MagickFalse); count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns, &rows,&depth,colorspace); if (count != 4) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T E X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTEXTImage() reads a text file and returns it as an image. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadTEXTImage method is: % % Image *ReadTEXTImage(const ImageInfo *image_info,Image *image, % char *text,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o text: the text storage buffer. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadTEXTImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent], geometry[MagickPathExtent], *p, text[MagickPathExtent]; DrawInfo *draw_info; Image *image, *texture; MagickBooleanType status; PointInfo delta; RectangleInfo page; ssize_t offset; TypeMetric metrics; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); /* Set the page geometry. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } page.width=612; page.height=792; page.x=43; page.y=43; if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); /* Initialize Image structure. */ image->columns=(size_t) floor((((double) page.width*image->resolution.x)/ delta.x)+0.5); image->rows=(size_t) floor((((double) page.height*image->resolution.y)/ delta.y)+0.5); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); image->page.x=0; image->page.y=0; texture=(Image *) NULL; if (image_info->texture != (char *) NULL) { ImageInfo *read_info; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->filename,image_info->texture, MagickPathExtent); texture=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); } /* Annotate the text image. */ (void) SetImageBackgroundColor(image,exception); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,image_info->filename); (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double) image->columns,(double) image->rows,(double) page.x,(double) page.y); (void) CloneString(&draw_info->geometry,geometry); status=GetTypeMetrics(image,draw_info,&metrics,exception); if (status == MagickFalse) ThrowReaderException(TypeError,"UnableToGetTypeMetrics"); page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double) image->columns,(double) image->rows,(double) page.x,(double) page.y); (void) CloneString(&draw_info->geometry,geometry); (void) CopyMagickString(filename,image_info->filename,MagickPathExtent); if (*draw_info->text != '\0') *draw_info->text='\0'; p=text; for (offset=2*page.y; p != (char *) NULL; ) { /* Annotate image with text. */ (void) ConcatenateString(&draw_info->text,text); (void) ConcatenateString(&draw_info->text,"\n"); offset+=(ssize_t) (metrics.ascent-metrics.descent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset, image->rows); if (status == MagickFalse) break; } p=ReadBlobString(image,text); if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) continue; if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture,exception); (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); } (void) AnnotateImage(image,draw_info,exception); if (p == (char *) NULL) break; /* Page is full-- allocate next image structure. */ *draw_info->text='\0'; offset=2*page.y; AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image->next->columns=image->columns; image->next->rows=image->rows; image=SyncNextImageInList(image); (void) CopyMagickString(image->filename,filename,MagickPathExtent); (void) SetImageBackgroundColor(image,exception); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture,exception); (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); } (void) AnnotateImage(image,draw_info,exception); if (texture != (Image *) NULL) texture=DestroyImage(texture); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTXTImage() reads a text file and returns it as an image. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadTXTImage method is: % % Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MagickPathExtent], text[MagickPathExtent]; Image *image; long x_offset, y_offset; PixelInfo pixel; MagickBooleanType status; QuantumAny range; register ssize_t i, x; register Quantum *q; ssize_t count, type, y; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->alpha_trait=UndefinedPixelTrait; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->alpha_trait=BlendPixelTrait; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) SetImageBackgroundColor(image,exception); (void) SetImageColorspace(image,(ColorspaceType) type,exception); GetPixelInfo(image,&pixel); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double alpha, black, blue, green, red; red=0.0; green=0.0; blue=0.0; black=0.0; alpha=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&alpha); green=red; blue=red; break; } count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset, &y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&black,&alpha); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&black); break; } default: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&alpha); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; black*=0.01*range; alpha*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5), range); pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5), range); pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5), range); pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5), range); pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5), range); q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1, exception); if (q == (Quantum *) NULL) continue; SetPixelViaPixelInfo(image,&pixel,q); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is: % % size_t RegisterTXTImage(void) % */ ModuleExport size_t RegisterTXTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("TXT","SPARSE-COLOR","Sparse Color"); entry->encoder=(EncodeImageHandler *) WriteTXTImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TXT","TEXT","Text"); entry->decoder=(DecodeImageHandler *) ReadTEXTImage; entry->format_type=ImplicitFormatType; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TXT","TXT","Text"); entry->decoder=(DecodeImageHandler *) ReadTXTImage; entry->encoder=(EncodeImageHandler *) WriteTXTImage; entry->magick=(IsImageFormatHandler *) IsTXT; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTXTImage() removes format registrations made by the % TXT module from the list of supported format. % % The format of the UnregisterTXTImage method is: % % UnregisterTXTImage(void) % */ ModuleExport void UnregisterTXTImage(void) { (void) UnregisterMagickInfo("SPARSE-COLOR"); (void) UnregisterMagickInfo("TEXT"); (void) UnregisterMagickInfo("TXT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTXTImage writes the pixel values as text numbers. % % The format of the WriteTXTImage method is: % % MagickBooleanType WriteTXTImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], colorspace[MagickPathExtent], tuple[MagickPathExtent]; MagickBooleanType status; MagickOffsetType scene; PixelInfo pixel; register const Quantum *p; register ssize_t x; ssize_t y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { ComplianceType compliance; const char *value; (void) CopyMagickString(colorspace,CommandOptionToMnemonic( MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent); LocaleLower(colorspace); image->depth=GetImageQuantumDepth(image,MagickTrue); if (image->alpha_trait != UndefinedPixelTrait) (void) ConcatenateMagickString(colorspace,"a",MagickPathExtent); compliance=NoCompliance; value=GetImageOption(image_info,"txt:compliance"); if (value != (char *) NULL) compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions, MagickFalse,value); if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0) { size_t depth; depth=compliance == SVGCompliance ? image->depth : MAGICKCORE_QUANTUM_DEPTH; (void) FormatLocaleString(buffer,MagickPathExtent, "# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double) image->columns,(double) image->rows,(double) ((MagickOffsetType) GetQuantumRange(depth)),colorspace); (void) WriteBlobString(image,buffer); } GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,p,&pixel); if (pixel.colorspace == LabColorspace) { pixel.green-=(QuantumRange+1)/2.0; pixel.blue-=(QuantumRange+1)/2.0; } if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0) { /* Sparse-color format. */ if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha) { GetColorTuple(&pixel,MagickFalse,tuple); (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g,%.20g,",(double) x,(double) y); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); } p+=GetPixelChannels(image); continue; } (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ", (double) x,(double) y); (void) WriteBlobString(image,buffer); (void) CopyMagickString(tuple,"(",MagickPathExtent); if (pixel.colorspace == GRAYColorspace) ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance, tuple); else { ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance, tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple); } if (pixel.colorspace == CMYKColorspace) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance, tuple); } if (pixel.alpha_trait != UndefinedPixelTrait) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance, tuple); } (void) ConcatenateMagickString(tuple,")",MagickPathExtent); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); GetColorTuple(&pixel,MagickTrue,tuple); (void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," "); (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image,"\n"); p+=GetPixelChannels(image); } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5485_2
crossvul-cpp_data_bad_1324_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 only if bFree is true. */ 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); } /* ** 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 ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); 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 } /* 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. ** ** (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 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ /* (3a) (3c) (3b) */ 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 if( sqlite3WindowRewrite(pParse, p) ){ 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-476/c/bad_1324_2
crossvul-cpp_data_good_5715_0
/** * WinPR: Windows Portable Runtime * Network Level Authentication (NLA) * * Copyright 2010-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <time.h> #ifndef _WIN32 #include <unistd.h> #endif #include <freerdp/crypto/tls.h> #include <winpr/crt.h> #include <winpr/sspi.h> #include <winpr/print.h> #include <winpr/tchar.h> #include <winpr/library.h> #include <winpr/registry.h> #include "nla.h" /** * TSRequest ::= SEQUENCE { * version [0] INTEGER, * negoTokens [1] NegoData OPTIONAL, * authInfo [2] OCTET STRING OPTIONAL, * pubKeyAuth [3] OCTET STRING OPTIONAL * } * * NegoData ::= SEQUENCE OF NegoDataItem * * NegoDataItem ::= SEQUENCE { * negoToken [0] OCTET STRING * } * * TSCredentials ::= SEQUENCE { * credType [0] INTEGER, * credentials [1] OCTET STRING * } * * TSPasswordCreds ::= SEQUENCE { * domainName [0] OCTET STRING, * userName [1] OCTET STRING, * password [2] OCTET STRING * } * * TSSmartCardCreds ::= SEQUENCE { * pin [0] OCTET STRING, * cspData [1] TSCspDataDetail, * userHint [2] OCTET STRING OPTIONAL, * domainHint [3] OCTET STRING OPTIONAL * } * * TSCspDataDetail ::= SEQUENCE { * keySpec [0] INTEGER, * cardName [1] OCTET STRING OPTIONAL, * readerName [2] OCTET STRING OPTIONAL, * containerName [3] OCTET STRING OPTIONAL, * cspName [4] OCTET STRING OPTIONAL * } * */ #ifdef WITH_DEBUG_NLA #define WITH_DEBUG_CREDSSP #endif #ifdef WITH_NATIVE_SSPI #define NLA_PKG_NAME NTLMSP_NAME #else #define NLA_PKG_NAME NTLMSP_NAME #endif #define TERMSRV_SPN_PREFIX "TERMSRV/" void credssp_send(rdpCredssp* credssp); int credssp_recv(rdpCredssp* credssp); void credssp_buffer_print(rdpCredssp* credssp); void credssp_buffer_free(rdpCredssp* credssp); SECURITY_STATUS credssp_encrypt_public_key_echo(rdpCredssp* credssp); SECURITY_STATUS credssp_decrypt_public_key_echo(rdpCredssp* credssp); SECURITY_STATUS credssp_encrypt_ts_credentials(rdpCredssp* credssp); SECURITY_STATUS credssp_decrypt_ts_credentials(rdpCredssp* credssp); #define ber_sizeof_sequence_octet_string(length) ber_sizeof_contextual_tag(ber_sizeof_octet_string(length)) + ber_sizeof_octet_string(length) #define ber_write_sequence_octet_string(stream, context, value, length) ber_write_contextual_tag(stream, context, ber_sizeof_octet_string(length), TRUE) + ber_write_octet_string(stream, value, length) /** * Initialize NTLMSSP authentication module (client). * @param credssp */ int credssp_ntlm_client_init(rdpCredssp* credssp) { char* spn; int length; freerdp* instance; rdpSettings* settings; settings = credssp->settings; instance = (freerdp*) settings->instance; if ((settings->Password == NULL) || (settings->Username == NULL)) { if (instance->Authenticate) { BOOL proceed = instance->Authenticate(instance, &settings->Username, &settings->Password, &settings->Domain); if (!proceed) return 0; } } sspi_SetAuthIdentity(&(credssp->identity), settings->Username, settings->Domain, settings->Password); #ifdef WITH_DEBUG_NLA _tprintf(_T("User: %s Domain: %s Password: %s\n"), (char*) credssp->identity.User, (char*) credssp->identity.Domain, (char*) credssp->identity.Password); #endif sspi_SecBufferAlloc(&credssp->PublicKey, credssp->transport->TlsIn->PublicKeyLength); CopyMemory(credssp->PublicKey.pvBuffer, credssp->transport->TlsIn->PublicKey, credssp->transport->TlsIn->PublicKeyLength); length = sizeof(TERMSRV_SPN_PREFIX) + strlen(settings->ServerHostname); spn = (SEC_CHAR*) malloc(length + 1); sprintf(spn, "%s%s", TERMSRV_SPN_PREFIX, settings->ServerHostname); #ifdef UNICODE credssp->ServicePrincipalName = (LPTSTR) malloc(length * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, spn, length, (LPWSTR) credssp->ServicePrincipalName, length); free(spn); #else credssp->ServicePrincipalName = spn; #endif return 1; } /** * Initialize NTLMSSP authentication module (server). * @param credssp */ int credssp_ntlm_server_init(rdpCredssp* credssp) { freerdp* instance; rdpSettings* settings = credssp->settings; instance = (freerdp*) settings->instance; sspi_SecBufferAlloc(&credssp->PublicKey, credssp->transport->TlsIn->PublicKeyLength); CopyMemory(credssp->PublicKey.pvBuffer, credssp->transport->TlsIn->PublicKey, credssp->transport->TlsIn->PublicKeyLength); return 1; } int credssp_client_authenticate(rdpCredssp* credssp) { ULONG cbMaxToken; ULONG fContextReq; ULONG pfContextAttr; SECURITY_STATUS status; CredHandle credentials; TimeStamp expiration; PSecPkgInfo pPackageInfo; SecBuffer input_buffer; SecBuffer output_buffer; SecBufferDesc input_buffer_desc; SecBufferDesc output_buffer_desc; BOOL have_context; BOOL have_input_buffer; BOOL have_pub_key_auth; sspi_GlobalInit(); if (credssp_ntlm_client_init(credssp) == 0) return 0; #ifdef WITH_NATIVE_SSPI { HMODULE hSSPI; INIT_SECURITY_INTERFACE InitSecurityInterface; PSecurityFunctionTable pSecurityInterface = NULL; hSSPI = LoadLibrary(_T("secur32.dll")); #ifdef UNICODE InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceW"); #else InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceA"); #endif credssp->table = (*InitSecurityInterface)(); } #else credssp->table = InitSecurityInterface(); #endif status = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo); if (status != SEC_E_OK) { fprintf(stderr, "QuerySecurityPackageInfo status: 0x%08X\n", status); return 0; } cbMaxToken = pPackageInfo->cbMaxToken; status = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME, SECPKG_CRED_OUTBOUND, NULL, &credssp->identity, NULL, NULL, &credentials, &expiration); if (status != SEC_E_OK) { fprintf(stderr, "AcquireCredentialsHandle status: 0x%08X\n", status); return 0; } have_context = FALSE; have_input_buffer = FALSE; have_pub_key_auth = FALSE; ZeroMemory(&input_buffer, sizeof(SecBuffer)); ZeroMemory(&output_buffer, sizeof(SecBuffer)); ZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes)); /* * from tspkg.dll: 0x00000132 * ISC_REQ_MUTUAL_AUTH * ISC_REQ_CONFIDENTIALITY * ISC_REQ_USE_SESSION_KEY * ISC_REQ_ALLOCATE_MEMORY */ fContextReq = ISC_REQ_MUTUAL_AUTH | ISC_REQ_CONFIDENTIALITY | ISC_REQ_USE_SESSION_KEY; while (TRUE) { output_buffer_desc.ulVersion = SECBUFFER_VERSION; output_buffer_desc.cBuffers = 1; output_buffer_desc.pBuffers = &output_buffer; output_buffer.BufferType = SECBUFFER_TOKEN; output_buffer.cbBuffer = cbMaxToken; output_buffer.pvBuffer = malloc(output_buffer.cbBuffer); status = credssp->table->InitializeSecurityContext(&credentials, (have_context) ? &credssp->context : NULL, credssp->ServicePrincipalName, fContextReq, 0, SECURITY_NATIVE_DREP, (have_input_buffer) ? &input_buffer_desc : NULL, 0, &credssp->context, &output_buffer_desc, &pfContextAttr, &expiration); if (have_input_buffer && (input_buffer.pvBuffer != NULL)) { free(input_buffer.pvBuffer); input_buffer.pvBuffer = NULL; } if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED) || (status == SEC_E_OK)) { if (credssp->table->CompleteAuthToken != NULL) credssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc); have_pub_key_auth = TRUE; if (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK) { fprintf(stderr, "QueryContextAttributes SECPKG_ATTR_SIZES failure\n"); return 0; } credssp_encrypt_public_key_echo(credssp); if (status == SEC_I_COMPLETE_NEEDED) status = SEC_E_OK; else if (status == SEC_I_COMPLETE_AND_CONTINUE) status = SEC_I_CONTINUE_NEEDED; } /* send authentication token to server */ if (output_buffer.cbBuffer > 0) { credssp->negoToken.pvBuffer = output_buffer.pvBuffer; credssp->negoToken.cbBuffer = output_buffer.cbBuffer; #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Sending Authentication Token\n"); winpr_HexDump(credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer); #endif credssp_send(credssp); credssp_buffer_free(credssp); } if (status != SEC_I_CONTINUE_NEEDED) break; /* receive server response and place in input buffer */ input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; if (credssp_recv(credssp) < 0) return -1; #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Receiving Authentication Token (%d)\n", (int) credssp->negoToken.cbBuffer); winpr_HexDump(credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer); #endif input_buffer.pvBuffer = credssp->negoToken.pvBuffer; input_buffer.cbBuffer = credssp->negoToken.cbBuffer; have_input_buffer = TRUE; have_context = TRUE; } /* Encrypted Public Key +1 */ if (credssp_recv(credssp) < 0) return -1; /* Verify Server Public Key Echo */ status = credssp_decrypt_public_key_echo(credssp); credssp_buffer_free(credssp); if (status != SEC_E_OK) { fprintf(stderr, "Could not verify public key echo!\n"); return -1; } /* Send encrypted credentials */ status = credssp_encrypt_ts_credentials(credssp); if (status != SEC_E_OK) { fprintf(stderr, "credssp_encrypt_ts_credentials status: 0x%08X\n", status); return 0; } credssp_send(credssp); credssp_buffer_free(credssp); /* Free resources */ credssp->table->FreeCredentialsHandle(&credentials); credssp->table->FreeContextBuffer(pPackageInfo); return 1; } /** * Authenticate with client using CredSSP (server). * @param credssp * @return 1 if authentication is successful */ int credssp_server_authenticate(rdpCredssp* credssp) { UINT32 cbMaxToken; ULONG fContextReq; ULONG pfContextAttr; SECURITY_STATUS status; CredHandle credentials; TimeStamp expiration; PSecPkgInfo pPackageInfo; SecBuffer input_buffer; SecBuffer output_buffer; SecBufferDesc input_buffer_desc; SecBufferDesc output_buffer_desc; BOOL have_context; BOOL have_input_buffer; BOOL have_pub_key_auth; sspi_GlobalInit(); if (credssp_ntlm_server_init(credssp) == 0) return 0; #ifdef WITH_NATIVE_SSPI if (!credssp->SspiModule) credssp->SspiModule = _tcsdup(_T("secur32.dll")); #endif if (credssp->SspiModule) { HMODULE hSSPI; INIT_SECURITY_INTERFACE pInitSecurityInterface; hSSPI = LoadLibrary(credssp->SspiModule); if (!hSSPI) { _tprintf(_T("Failed to load SSPI module: %s\n"), credssp->SspiModule); return 0; } #ifdef UNICODE pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceW"); #else pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceA"); #endif credssp->table = (*pInitSecurityInterface)(); } #ifndef WITH_NATIVE_SSPI else { credssp->table = InitSecurityInterface(); } #endif status = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo); if (status != SEC_E_OK) { fprintf(stderr, "QuerySecurityPackageInfo status: 0x%08X\n", status); return 0; } cbMaxToken = pPackageInfo->cbMaxToken; status = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME, SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &credentials, &expiration); if (status != SEC_E_OK) { fprintf(stderr, "AcquireCredentialsHandle status: 0x%08X\n", status); return 0; } have_context = FALSE; have_input_buffer = FALSE; have_pub_key_auth = FALSE; ZeroMemory(&input_buffer, sizeof(SecBuffer)); ZeroMemory(&output_buffer, sizeof(SecBuffer)); ZeroMemory(&input_buffer_desc, sizeof(SecBufferDesc)); ZeroMemory(&output_buffer_desc, sizeof(SecBufferDesc)); ZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes)); /* * from tspkg.dll: 0x00000112 * ASC_REQ_MUTUAL_AUTH * ASC_REQ_CONFIDENTIALITY * ASC_REQ_ALLOCATE_MEMORY */ fContextReq = 0; fContextReq |= ASC_REQ_MUTUAL_AUTH; fContextReq |= ASC_REQ_CONFIDENTIALITY; fContextReq |= ASC_REQ_CONNECTION; fContextReq |= ASC_REQ_USE_SESSION_KEY; fContextReq |= ASC_REQ_REPLAY_DETECT; fContextReq |= ASC_REQ_SEQUENCE_DETECT; fContextReq |= ASC_REQ_EXTENDED_ERROR; while (TRUE) { input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; /* receive authentication token */ input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; if (credssp_recv(credssp) < 0) return -1; #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Receiving Authentication Token\n"); credssp_buffer_print(credssp); #endif input_buffer.pvBuffer = credssp->negoToken.pvBuffer; input_buffer.cbBuffer = credssp->negoToken.cbBuffer; if (credssp->negoToken.cbBuffer < 1) { fprintf(stderr, "CredSSP: invalid negoToken!\n"); return -1; } output_buffer_desc.ulVersion = SECBUFFER_VERSION; output_buffer_desc.cBuffers = 1; output_buffer_desc.pBuffers = &output_buffer; output_buffer.BufferType = SECBUFFER_TOKEN; output_buffer.cbBuffer = cbMaxToken; output_buffer.pvBuffer = malloc(output_buffer.cbBuffer); status = credssp->table->AcceptSecurityContext(&credentials, have_context? &credssp->context: NULL, &input_buffer_desc, fContextReq, SECURITY_NATIVE_DREP, &credssp->context, &output_buffer_desc, &pfContextAttr, &expiration); credssp->negoToken.pvBuffer = output_buffer.pvBuffer; credssp->negoToken.cbBuffer = output_buffer.cbBuffer; if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED)) { if (credssp->table->CompleteAuthToken != NULL) credssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc); if (status == SEC_I_COMPLETE_NEEDED) status = SEC_E_OK; else if (status == SEC_I_COMPLETE_AND_CONTINUE) status = SEC_I_CONTINUE_NEEDED; } if (status == SEC_E_OK) { have_pub_key_auth = TRUE; if (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK) { fprintf(stderr, "QueryContextAttributes SECPKG_ATTR_SIZES failure\n"); return 0; } if (credssp_decrypt_public_key_echo(credssp) != SEC_E_OK) { fprintf(stderr, "Error: could not verify client's public key echo\n"); return -1; } sspi_SecBufferFree(&credssp->negoToken); credssp->negoToken.pvBuffer = NULL; credssp->negoToken.cbBuffer = 0; credssp_encrypt_public_key_echo(credssp); } if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED)) { fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status); return -1; } /* send authentication token */ #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Sending Authentication Token\n"); credssp_buffer_print(credssp); #endif credssp_send(credssp); credssp_buffer_free(credssp); if (status != SEC_I_CONTINUE_NEEDED) break; have_context = TRUE; } /* Receive encrypted credentials */ if (credssp_recv(credssp) < 0) return -1; if (credssp_decrypt_ts_credentials(credssp) != SEC_E_OK) { fprintf(stderr, "Could not decrypt TSCredentials status: 0x%08X\n", status); return 0; } if (status != SEC_E_OK) { fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status); return 0; } status = credssp->table->ImpersonateSecurityContext(&credssp->context); if (status != SEC_E_OK) { fprintf(stderr, "ImpersonateSecurityContext status: 0x%08X\n", status); return 0; } else { status = credssp->table->RevertSecurityContext(&credssp->context); if (status != SEC_E_OK) { fprintf(stderr, "RevertSecurityContext status: 0x%08X\n", status); return 0; } } credssp->table->FreeContextBuffer(pPackageInfo); return 1; } /** * Authenticate using CredSSP. * @param credssp * @return 1 if authentication is successful */ int credssp_authenticate(rdpCredssp* credssp) { if (credssp->server) return credssp_server_authenticate(credssp); else return credssp_client_authenticate(credssp); } void ap_integer_increment_le(BYTE* number, int size) { int index; for (index = 0; index < size; index++) { if (number[index] < 0xFF) { number[index]++; break; } else { number[index] = 0; continue; } } } void ap_integer_decrement_le(BYTE* number, int size) { int index; for (index = 0; index < size; index++) { if (number[index] > 0) { number[index]--; break; } else { number[index] = 0xFF; continue; } } } SECURITY_STATUS credssp_encrypt_public_key_echo(rdpCredssp* credssp) { SecBuffer Buffers[2]; SecBufferDesc Message; SECURITY_STATUS status; int public_key_length; public_key_length = credssp->PublicKey.cbBuffer; Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */ Buffers[1].BufferType = SECBUFFER_DATA; /* TLS Public Key */ sspi_SecBufferAlloc(&credssp->pubKeyAuth, credssp->ContextSizes.cbMaxSignature + public_key_length); Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature; Buffers[0].pvBuffer = credssp->pubKeyAuth.pvBuffer; Buffers[1].cbBuffer = public_key_length; Buffers[1].pvBuffer = ((BYTE*) credssp->pubKeyAuth.pvBuffer) + credssp->ContextSizes.cbMaxSignature; CopyMemory(Buffers[1].pvBuffer, credssp->PublicKey.pvBuffer, Buffers[1].cbBuffer); if (credssp->server) { /* server echos the public key +1 */ ap_integer_increment_le((BYTE*) Buffers[1].pvBuffer, Buffers[1].cbBuffer); } Message.cBuffers = 2; Message.ulVersion = SECBUFFER_VERSION; Message.pBuffers = (PSecBuffer) &Buffers; status = credssp->table->EncryptMessage(&credssp->context, 0, &Message, credssp->send_seq_num++); if (status != SEC_E_OK) { fprintf(stderr, "EncryptMessage status: 0x%08X\n", status); return status; } return status; } SECURITY_STATUS credssp_decrypt_public_key_echo(rdpCredssp* credssp) { int length; BYTE* buffer; ULONG pfQOP; BYTE* public_key1; BYTE* public_key2; int public_key_length; SecBuffer Buffers[2]; SecBufferDesc Message; SECURITY_STATUS status; if (credssp->PublicKey.cbBuffer + credssp->ContextSizes.cbMaxSignature != credssp->pubKeyAuth.cbBuffer) { fprintf(stderr, "unexpected pubKeyAuth buffer size:%d\n", (int) credssp->pubKeyAuth.cbBuffer); return SEC_E_INVALID_TOKEN; } length = credssp->pubKeyAuth.cbBuffer; buffer = (BYTE*) malloc(length); CopyMemory(buffer, credssp->pubKeyAuth.pvBuffer, length); public_key_length = credssp->PublicKey.cbBuffer; Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */ Buffers[1].BufferType = SECBUFFER_DATA; /* Encrypted TLS Public Key */ Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature; Buffers[0].pvBuffer = buffer; Buffers[1].cbBuffer = length - credssp->ContextSizes.cbMaxSignature; Buffers[1].pvBuffer = buffer + credssp->ContextSizes.cbMaxSignature; Message.cBuffers = 2; Message.ulVersion = SECBUFFER_VERSION; Message.pBuffers = (PSecBuffer) &Buffers; status = credssp->table->DecryptMessage(&credssp->context, &Message, credssp->recv_seq_num++, &pfQOP); if (status != SEC_E_OK) { fprintf(stderr, "DecryptMessage failure: 0x%08X\n", status); return status; } public_key1 = (BYTE*) credssp->PublicKey.pvBuffer; public_key2 = (BYTE*) Buffers[1].pvBuffer; if (!credssp->server) { /* server echos the public key +1 */ ap_integer_decrement_le(public_key2, public_key_length); } if (memcmp(public_key1, public_key2, public_key_length) != 0) { fprintf(stderr, "Could not verify server's public key echo\n"); fprintf(stderr, "Expected (length = %d):\n", public_key_length); winpr_HexDump(public_key1, public_key_length); fprintf(stderr, "Actual (length = %d):\n", public_key_length); winpr_HexDump(public_key2, public_key_length); return SEC_E_MESSAGE_ALTERED; /* DO NOT SEND CREDENTIALS! */ } free(buffer); return SEC_E_OK; } int credssp_sizeof_ts_password_creds(rdpCredssp* credssp) { int length = 0; length += ber_sizeof_sequence_octet_string(credssp->identity.DomainLength * 2); length += ber_sizeof_sequence_octet_string(credssp->identity.UserLength * 2); length += ber_sizeof_sequence_octet_string(credssp->identity.PasswordLength * 2); return length; } void credssp_read_ts_password_creds(rdpCredssp* credssp, wStream* s) { int length; /* TSPasswordCreds (SEQUENCE) */ ber_read_sequence_tag(s, &length); /* [0] domainName (OCTET STRING) */ ber_read_contextual_tag(s, 0, &length, TRUE); ber_read_octet_string_tag(s, &length); credssp->identity.DomainLength = (UINT32) length; credssp->identity.Domain = (UINT16*) malloc(length); CopyMemory(credssp->identity.Domain, Stream_Pointer(s), credssp->identity.DomainLength); Stream_Seek(s, credssp->identity.DomainLength); credssp->identity.DomainLength /= 2; /* [1] userName (OCTET STRING) */ ber_read_contextual_tag(s, 1, &length, TRUE); ber_read_octet_string_tag(s, &length); credssp->identity.UserLength = (UINT32) length; credssp->identity.User = (UINT16*) malloc(length); CopyMemory(credssp->identity.User, Stream_Pointer(s), credssp->identity.UserLength); Stream_Seek(s, credssp->identity.UserLength); credssp->identity.UserLength /= 2; /* [2] password (OCTET STRING) */ ber_read_contextual_tag(s, 2, &length, TRUE); ber_read_octet_string_tag(s, &length); credssp->identity.PasswordLength = (UINT32) length; credssp->identity.Password = (UINT16*) malloc(length); CopyMemory(credssp->identity.Password, Stream_Pointer(s), credssp->identity.PasswordLength); Stream_Seek(s, credssp->identity.PasswordLength); credssp->identity.PasswordLength /= 2; credssp->identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; } int credssp_write_ts_password_creds(rdpCredssp* credssp, wStream* s) { int size = 0; int innerSize = credssp_sizeof_ts_password_creds(credssp); /* TSPasswordCreds (SEQUENCE) */ size += ber_write_sequence_tag(s, innerSize); /* [0] domainName (OCTET STRING) */ size += ber_write_sequence_octet_string(s, 0, (BYTE*) credssp->identity.Domain, credssp->identity.DomainLength * 2); /* [1] userName (OCTET STRING) */ size += ber_write_sequence_octet_string(s, 1, (BYTE*) credssp->identity.User, credssp->identity.UserLength * 2); /* [2] password (OCTET STRING) */ size += ber_write_sequence_octet_string(s, 2, (BYTE*) credssp->identity.Password, credssp->identity.PasswordLength * 2); return size; } int credssp_sizeof_ts_credentials(rdpCredssp* credssp) { int size = 0; size += ber_sizeof_integer(1); size += ber_sizeof_contextual_tag(ber_sizeof_integer(1)); size += ber_sizeof_sequence_octet_string(ber_sizeof_sequence(credssp_sizeof_ts_password_creds(credssp))); return size; } void credssp_read_ts_credentials(rdpCredssp* credssp, PSecBuffer ts_credentials) { wStream* s; int length; int ts_password_creds_length; s = Stream_New(ts_credentials->pvBuffer, ts_credentials->cbBuffer); /* TSCredentials (SEQUENCE) */ ber_read_sequence_tag(s, &length); /* [0] credType (INTEGER) */ ber_read_contextual_tag(s, 0, &length, TRUE); ber_read_integer(s, NULL); /* [1] credentials (OCTET STRING) */ ber_read_contextual_tag(s, 1, &length, TRUE); ber_read_octet_string_tag(s, &ts_password_creds_length); credssp_read_ts_password_creds(credssp, s); Stream_Free(s, FALSE); } int credssp_write_ts_credentials(rdpCredssp* credssp, wStream* s) { int size = 0; int innerSize = credssp_sizeof_ts_credentials(credssp); int passwordSize; /* TSCredentials (SEQUENCE) */ size += ber_write_sequence_tag(s, innerSize); /* [0] credType (INTEGER) */ size += ber_write_contextual_tag(s, 0, ber_sizeof_integer(1), TRUE); size += ber_write_integer(s, 1); /* [1] credentials (OCTET STRING) */ passwordSize = ber_sizeof_sequence(credssp_sizeof_ts_password_creds(credssp)); size += ber_write_contextual_tag(s, 1, ber_sizeof_octet_string(passwordSize), TRUE); size += ber_write_octet_string_tag(s, passwordSize); size += credssp_write_ts_password_creds(credssp, s); return size; } /** * Encode TSCredentials structure. * @param credssp */ void credssp_encode_ts_credentials(rdpCredssp* credssp) { wStream* s; int length; length = ber_sizeof_sequence(credssp_sizeof_ts_credentials(credssp)); sspi_SecBufferAlloc(&credssp->ts_credentials, length); s = Stream_New(credssp->ts_credentials.pvBuffer, length); credssp_write_ts_credentials(credssp, s); Stream_Free(s, FALSE); } SECURITY_STATUS credssp_encrypt_ts_credentials(rdpCredssp* credssp) { SecBuffer Buffers[2]; SecBufferDesc Message; SECURITY_STATUS status; credssp_encode_ts_credentials(credssp); Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */ Buffers[1].BufferType = SECBUFFER_DATA; /* TSCredentials */ sspi_SecBufferAlloc(&credssp->authInfo, credssp->ContextSizes.cbMaxSignature + credssp->ts_credentials.cbBuffer); Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature; Buffers[0].pvBuffer = credssp->authInfo.pvBuffer; ZeroMemory(Buffers[0].pvBuffer, Buffers[0].cbBuffer); Buffers[1].cbBuffer = credssp->ts_credentials.cbBuffer; Buffers[1].pvBuffer = &((BYTE*) credssp->authInfo.pvBuffer)[Buffers[0].cbBuffer]; CopyMemory(Buffers[1].pvBuffer, credssp->ts_credentials.pvBuffer, Buffers[1].cbBuffer); Message.cBuffers = 2; Message.ulVersion = SECBUFFER_VERSION; Message.pBuffers = (PSecBuffer) &Buffers; status = credssp->table->EncryptMessage(&credssp->context, 0, &Message, credssp->send_seq_num++); if (status != SEC_E_OK) return status; return SEC_E_OK; } SECURITY_STATUS credssp_decrypt_ts_credentials(rdpCredssp* credssp) { int length; BYTE* buffer; ULONG pfQOP; SecBuffer Buffers[2]; SecBufferDesc Message; SECURITY_STATUS status; Buffers[0].BufferType = SECBUFFER_TOKEN; /* Signature */ Buffers[1].BufferType = SECBUFFER_DATA; /* TSCredentials */ if (credssp->authInfo.cbBuffer < 1) { fprintf(stderr, "credssp_decrypt_ts_credentials missing authInfo buffer\n"); return SEC_E_INVALID_TOKEN; } length = credssp->authInfo.cbBuffer; buffer = (BYTE*) malloc(length); CopyMemory(buffer, credssp->authInfo.pvBuffer, length); Buffers[0].cbBuffer = credssp->ContextSizes.cbMaxSignature; Buffers[0].pvBuffer = buffer; Buffers[1].cbBuffer = length - credssp->ContextSizes.cbMaxSignature; Buffers[1].pvBuffer = &buffer[credssp->ContextSizes.cbMaxSignature]; Message.cBuffers = 2; Message.ulVersion = SECBUFFER_VERSION; Message.pBuffers = (PSecBuffer) &Buffers; status = credssp->table->DecryptMessage(&credssp->context, &Message, credssp->recv_seq_num++, &pfQOP); if (status != SEC_E_OK) return status; credssp_read_ts_credentials(credssp, &Buffers[1]); free(buffer); return SEC_E_OK; } int credssp_sizeof_nego_token(int length) { length = ber_sizeof_octet_string(length); length += ber_sizeof_contextual_tag(length); return length; } int credssp_sizeof_nego_tokens(int length) { length = credssp_sizeof_nego_token(length); length += ber_sizeof_sequence_tag(length); length += ber_sizeof_sequence_tag(length); length += ber_sizeof_contextual_tag(length); return length; } int credssp_sizeof_pub_key_auth(int length) { length = ber_sizeof_octet_string(length); length += ber_sizeof_contextual_tag(length); return length; } int credssp_sizeof_auth_info(int length) { length = ber_sizeof_octet_string(length); length += ber_sizeof_contextual_tag(length); return length; } int credssp_sizeof_ts_request(int length) { length += ber_sizeof_integer(2); length += ber_sizeof_contextual_tag(3); return length; } /** * Send CredSSP message. * @param credssp */ void credssp_send(rdpCredssp* credssp) { wStream* s; int length; int ts_request_length; int nego_tokens_length; int pub_key_auth_length; int auth_info_length; nego_tokens_length = (credssp->negoToken.cbBuffer > 0) ? credssp_sizeof_nego_tokens(credssp->negoToken.cbBuffer) : 0; pub_key_auth_length = (credssp->pubKeyAuth.cbBuffer > 0) ? credssp_sizeof_pub_key_auth(credssp->pubKeyAuth.cbBuffer) : 0; auth_info_length = (credssp->authInfo.cbBuffer > 0) ? credssp_sizeof_auth_info(credssp->authInfo.cbBuffer) : 0; length = nego_tokens_length + pub_key_auth_length + auth_info_length; ts_request_length = credssp_sizeof_ts_request(length); s = Stream_New(NULL, ber_sizeof_sequence(ts_request_length)); /* TSRequest */ ber_write_sequence_tag(s, ts_request_length); /* SEQUENCE */ /* [0] version */ ber_write_contextual_tag(s, 0, 3, TRUE); ber_write_integer(s, 2); /* INTEGER */ /* [1] negoTokens (NegoData) */ if (nego_tokens_length > 0) { length = nego_tokens_length; length -= ber_write_contextual_tag(s, 1, ber_sizeof_sequence(ber_sizeof_sequence(ber_sizeof_sequence_octet_string(credssp->negoToken.cbBuffer))), TRUE); /* NegoData */ length -= ber_write_sequence_tag(s, ber_sizeof_sequence(ber_sizeof_sequence_octet_string(credssp->negoToken.cbBuffer))); /* SEQUENCE OF NegoDataItem */ length -= ber_write_sequence_tag(s, ber_sizeof_sequence_octet_string(credssp->negoToken.cbBuffer)); /* NegoDataItem */ length -= ber_write_sequence_octet_string(s, 0, (BYTE*) credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer); /* OCTET STRING */ // assert length == 0 } /* [2] authInfo (OCTET STRING) */ if (auth_info_length > 0) { length = auth_info_length; length -= ber_write_sequence_octet_string(s, 2, credssp->authInfo.pvBuffer, credssp->authInfo.cbBuffer); // assert length == 0 } /* [3] pubKeyAuth (OCTET STRING) */ if (pub_key_auth_length > 0) { length = pub_key_auth_length; length -= ber_write_sequence_octet_string(s, 3, credssp->pubKeyAuth.pvBuffer, credssp->pubKeyAuth.cbBuffer); // assert length == 0 } Stream_SealLength(s); transport_write(credssp->transport, s); Stream_Free(s, TRUE); } /** * Receive CredSSP message. * @param credssp * @return */ int credssp_recv(rdpCredssp* credssp) { wStream* s; int length; int status; UINT32 version; s = Stream_New(NULL, 4096); status = transport_read(credssp->transport, s); Stream_Length(s) = status; if (status < 0) { fprintf(stderr, "credssp_recv() error: %d\n", status); Stream_Free(s, TRUE); return -1; } /* TSRequest */ if(!ber_read_sequence_tag(s, &length) || !ber_read_contextual_tag(s, 0, &length, TRUE) || !ber_read_integer(s, &version)) return -1; /* [1] negoTokens (NegoData) */ if (ber_read_contextual_tag(s, 1, &length, TRUE) != FALSE) { if (!ber_read_sequence_tag(s, &length) || /* SEQUENCE OF NegoDataItem */ !ber_read_sequence_tag(s, &length) || /* NegoDataItem */ !ber_read_contextual_tag(s, 0, &length, TRUE) || /* [0] negoToken */ !ber_read_octet_string_tag(s, &length) || /* OCTET STRING */ Stream_GetRemainingLength(s) < length) return -1; sspi_SecBufferAlloc(&credssp->negoToken, length); Stream_Read(s, credssp->negoToken.pvBuffer, length); credssp->negoToken.cbBuffer = length; } /* [2] authInfo (OCTET STRING) */ if (ber_read_contextual_tag(s, 2, &length, TRUE) != FALSE) { if(!ber_read_octet_string_tag(s, &length) || /* OCTET STRING */ Stream_GetRemainingLength(s) < length) return -1; sspi_SecBufferAlloc(&credssp->authInfo, length); Stream_Read(s, credssp->authInfo.pvBuffer, length); credssp->authInfo.cbBuffer = length; } /* [3] pubKeyAuth (OCTET STRING) */ if (ber_read_contextual_tag(s, 3, &length, TRUE) != FALSE) { if(!ber_read_octet_string_tag(s, &length) || /* OCTET STRING */ Stream_GetRemainingLength(s) < length) return -1; sspi_SecBufferAlloc(&credssp->pubKeyAuth, length); Stream_Read(s, credssp->pubKeyAuth.pvBuffer, length); credssp->pubKeyAuth.cbBuffer = length; } Stream_Free(s, TRUE); return 0; } void credssp_buffer_print(rdpCredssp* credssp) { if (credssp->negoToken.cbBuffer > 0) { fprintf(stderr, "CredSSP.negoToken (length = %d):\n", (int) credssp->negoToken.cbBuffer); winpr_HexDump(credssp->negoToken.pvBuffer, credssp->negoToken.cbBuffer); } if (credssp->pubKeyAuth.cbBuffer > 0) { fprintf(stderr, "CredSSP.pubKeyAuth (length = %d):\n", (int) credssp->pubKeyAuth.cbBuffer); winpr_HexDump(credssp->pubKeyAuth.pvBuffer, credssp->pubKeyAuth.cbBuffer); } if (credssp->authInfo.cbBuffer > 0) { fprintf(stderr, "CredSSP.authInfo (length = %d):\n", (int) credssp->authInfo.cbBuffer); winpr_HexDump(credssp->authInfo.pvBuffer, credssp->authInfo.cbBuffer); } } void credssp_buffer_free(rdpCredssp* credssp) { sspi_SecBufferFree(&credssp->negoToken); sspi_SecBufferFree(&credssp->pubKeyAuth); sspi_SecBufferFree(&credssp->authInfo); } /** * Create new CredSSP state machine. * @param transport * @return new CredSSP state machine. */ rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { rdpCredssp* credssp; credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp)); ZeroMemory(credssp, sizeof(rdpCredssp)); if (credssp != NULL) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; credssp->instance = instance; credssp->settings = settings; credssp->server = settings->ServerMode; credssp->transport = transport; credssp->send_seq_num = 0; credssp->recv_seq_num = 0; ZeroMemory(&credssp->negoToken, sizeof(SecBuffer)); ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer)); ZeroMemory(&credssp->authInfo, sizeof(SecBuffer)); SecInvalidateHandle(&credssp->context); if (credssp->server) { status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); if (status == ERROR_SUCCESS) { credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, (BYTE*) credssp->SspiModule, &dwSize); if (status == ERROR_SUCCESS) { _tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule); RegCloseKey(hKey); } } } } } return credssp; } /** * Free CredSSP state machine. * @param credssp */ void credssp_free(rdpCredssp* credssp) { if (credssp != NULL) { if (credssp->table) credssp->table->DeleteSecurityContext(&credssp->context); sspi_SecBufferFree(&credssp->PublicKey); sspi_SecBufferFree(&credssp->ts_credentials); free(credssp->ServicePrincipalName); free(credssp->identity.User); free(credssp->identity.Domain); free(credssp->identity.Password); free(credssp); } }
./CrossVul/dataset_final_sorted/CWE-476/c/good_5715_0
crossvul-cpp_data_bad_1319_2
/* ** 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); if( bIntToNull && pDup && pDup->op==TK_INTEGER ){ pDup->op = TK_NULL; pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); } 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-476/c/bad_1319_2
crossvul-cpp_data_bad_528_3
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Terminal window support, see ":help :terminal". * * There are three parts: * 1. Generic code for all systems. * Uses libvterm for the terminal emulator. * 2. The MS-Windows implementation. * Uses winpty. * 3. The Unix-like implementation. * Uses pseudo-tty's (pty's). * * For each terminal one VTerm is constructed. This uses libvterm. A copy of * this library is in the libvterm directory. * * When a terminal window is opened, a job is started that will be connected to * the terminal emulator. * * If the terminal window has keyboard focus, typed keys are converted to the * terminal encoding and writing to the job over a channel. * * If the job produces output, it is written to the terminal emulator. The * terminal emulator invokes callbacks when its screen content changes. The * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a * while, if the terminal window is visible, the screen contents is drawn. * * When the job ends the text is put in a buffer. Redrawing then happens from * that buffer, attributes come from the scrollback buffer tl_scrollback. * When the buffer is changed it is turned into a normal buffer, the attributes * in tl_scrollback are no longer used. */ #include "vim.h" #if defined(FEAT_TERMINAL) || defined(PROTO) #ifndef MIN # define MIN(x,y) ((x) < (y) ? (x) : (y)) #endif #ifndef MAX # define MAX(x,y) ((x) > (y) ? (x) : (y)) #endif #include "libvterm/include/vterm.h" /* This is VTermScreenCell without the characters, thus much smaller. */ typedef struct { VTermScreenCellAttrs attrs; char width; VTermColor fg; VTermColor bg; } cellattr_T; typedef struct sb_line_S { int sb_cols; /* can differ per line */ cellattr_T *sb_cells; /* allocated */ cellattr_T sb_fill_attr; /* for short line */ } sb_line_T; /* typedef term_T in structs.h */ struct terminal_S { term_T *tl_next; VTerm *tl_vterm; job_T *tl_job; buf_T *tl_buffer; #if defined(FEAT_GUI) int tl_system; /* when non-zero used for :!cmd output */ int tl_toprow; /* row with first line of system terminal */ #endif /* Set when setting the size of a vterm, reset after redrawing. */ int tl_vterm_size_changed; int tl_normal_mode; /* TRUE: Terminal-Normal mode */ int tl_channel_closed; int tl_channel_recently_closed; // still need to handle tl_finish int tl_finish; #define TL_FINISH_UNSET NUL #define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */ #define TL_FINISH_NOCLOSE 'n' /* ++noclose */ #define TL_FINISH_OPEN 'o' /* ++open */ char_u *tl_opencmd; char_u *tl_eof_chars; #ifdef WIN3264 void *tl_winpty_config; void *tl_winpty; FILE *tl_out_fd; #endif #if defined(FEAT_SESSION) char_u *tl_command; #endif char_u *tl_kill; /* last known vterm size */ int tl_rows; int tl_cols; char_u *tl_title; /* NULL or allocated */ char_u *tl_status_text; /* NULL or allocated */ /* Range of screen rows to update. Zero based. */ int tl_dirty_row_start; /* MAX_ROW if nothing dirty */ int tl_dirty_row_end; /* row below last one to update */ int tl_dirty_snapshot; /* text updated after making snapshot */ #ifdef FEAT_TIMERS int tl_timer_set; proftime_T tl_timer_due; #endif int tl_postponed_scroll; /* to be scrolled up */ garray_T tl_scrollback; int tl_scrollback_scrolled; cellattr_T tl_default_color; linenr_T tl_top_diff_rows; /* rows of top diff file or zero */ linenr_T tl_bot_diff_rows; /* rows of bottom diff file */ VTermPos tl_cursor_pos; int tl_cursor_visible; int tl_cursor_blink; int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */ char_u *tl_cursor_color; /* NULL or allocated */ int tl_using_altscreen; }; #define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */ #define TMODE_LOOP 2 /* CTRL-W N used */ /* * List of all active terminals. */ static term_T *first_term = NULL; /* Terminal active in terminal_loop(). */ static term_T *in_terminal_loop = NULL; #define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */ #define KEY_BUF_LEN 200 /* * Functions with separate implementation for MS-Windows and Unix-like systems. */ static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt); static int create_pty_only(term_T *term, jobopt_T *opt); static void term_report_winsize(term_T *term, int rows, int cols); static void term_free_vterm(term_T *term); #ifdef FEAT_GUI static void update_system_term(term_T *term); #endif /* The character that we know (or assume) that the terminal expects for the * backspace key. */ static int term_backspace_char = BS; /* "Terminal" highlight group colors. */ static int term_default_cterm_fg = -1; static int term_default_cterm_bg = -1; /* Store the last set and the desired cursor properties, so that we only update * them when needed. Doing it unnecessary may result in flicker. */ static char_u *last_set_cursor_color = NULL; static char_u *desired_cursor_color = NULL; static int last_set_cursor_shape = -1; static int desired_cursor_shape = -1; static int last_set_cursor_blink = -1; static int desired_cursor_blink = -1; /************************************** * 1. Generic code for all systems. */ static int cursor_color_equal(char_u *lhs_color, char_u *rhs_color) { if (lhs_color != NULL && rhs_color != NULL) return STRCMP(lhs_color, rhs_color) == 0; return lhs_color == NULL && rhs_color == NULL; } static void cursor_color_copy(char_u **to_color, char_u *from_color) { // Avoid a free & alloc if the value is already right. if (cursor_color_equal(*to_color, from_color)) return; vim_free(*to_color); *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color); } static char_u * cursor_color_get(char_u *color) { return (color == NULL) ? (char_u *)"" : color; } /* * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the * current window. * Sets "rows" and/or "cols" to zero when it should follow the window size. * Return TRUE if the size is the minimum size: "24*80". */ static int parse_termwinsize(win_T *wp, int *rows, int *cols) { int minsize = FALSE; *rows = 0; *cols = 0; if (*wp->w_p_tws != NUL) { char_u *p = vim_strchr(wp->w_p_tws, 'x'); /* Syntax of value was already checked when it's set. */ if (p == NULL) { minsize = TRUE; p = vim_strchr(wp->w_p_tws, '*'); } *rows = atoi((char *)wp->w_p_tws); *cols = atoi((char *)p + 1); } return minsize; } /* * Determine the terminal size from 'termwinsize' and the current window. */ static void set_term_and_win_size(term_T *term) { #ifdef FEAT_GUI if (term->tl_system) { /* Use the whole screen for the system command. However, it will start * at the command line and scroll up as needed, using tl_toprow. */ term->tl_rows = Rows; term->tl_cols = Columns; return; } #endif if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols)) { if (term->tl_rows != 0) term->tl_rows = MAX(term->tl_rows, curwin->w_height); if (term->tl_cols != 0) term->tl_cols = MAX(term->tl_cols, curwin->w_width); } if (term->tl_rows == 0) term->tl_rows = curwin->w_height; else win_setheight_win(term->tl_rows, curwin); if (term->tl_cols == 0) term->tl_cols = curwin->w_width; else win_setwidth_win(term->tl_cols, curwin); } /* * Initialize job options for a terminal job. * Caller may overrule some of them. */ void init_job_options(jobopt_T *opt) { clear_job_options(opt); opt->jo_mode = MODE_RAW; opt->jo_out_mode = MODE_RAW; opt->jo_err_mode = MODE_RAW; opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE; } /* * Set job options mandatory for a terminal job. */ static void setup_job_options(jobopt_T *opt, int rows, int cols) { #ifndef WIN3264 /* Win32: Redirecting the job output won't work, thus always connect stdout * here. */ if (!(opt->jo_set & JO_OUT_IO)) #endif { /* Connect stdout to the terminal. */ opt->jo_io[PART_OUT] = JIO_BUFFER; opt->jo_io_buf[PART_OUT] = curbuf->b_fnum; opt->jo_modifiable[PART_OUT] = 0; opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE; } #ifndef WIN3264 /* Win32: Redirecting the job output won't work, thus always connect stderr * here. */ if (!(opt->jo_set & JO_ERR_IO)) #endif { /* Connect stderr to the terminal. */ opt->jo_io[PART_ERR] = JIO_BUFFER; opt->jo_io_buf[PART_ERR] = curbuf->b_fnum; opt->jo_modifiable[PART_ERR] = 0; opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE; } opt->jo_pty = TRUE; if ((opt->jo_set2 & JO2_TERM_ROWS) == 0) opt->jo_term_rows = rows; if ((opt->jo_set2 & JO2_TERM_COLS) == 0) opt->jo_term_cols = cols; } /* * Close a terminal buffer (and its window). Used when creating the terminal * fails. */ static void term_close_buffer(buf_T *buf, buf_T *old_curbuf) { free_terminal(buf); if (old_curbuf != NULL) { --curbuf->b_nwindows; curbuf = old_curbuf; curwin->w_buffer = curbuf; ++curbuf->b_nwindows; } /* Wiping out the buffer will also close the window and call * free_terminal(). */ do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE); } /* * Start a terminal window and return its buffer. * Use either "argvar" or "argv", the other must be NULL. * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open * the window. * Returns NULL when failed. */ buf_T * term_start( typval_T *argvar, char **argv, jobopt_T *opt, int flags) { exarg_T split_ea; win_T *old_curwin = curwin; term_T *term; buf_T *old_curbuf = NULL; int res; buf_T *newbuf; int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT); jobopt_T orig_opt; // only partly filled if (check_restricted() || check_secure()) return NULL; if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)) == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO) || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF)) || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))) { EMSG(_(e_invarg)); return NULL; } term = (term_T *)alloc_clear(sizeof(term_T)); if (term == NULL) return NULL; term->tl_dirty_row_end = MAX_ROW; term->tl_cursor_visible = TRUE; term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK; term->tl_finish = opt->jo_term_finish; #ifdef FEAT_GUI term->tl_system = (flags & TERM_START_SYSTEM); #endif ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300); vim_memset(&split_ea, 0, sizeof(split_ea)); if (opt->jo_curwin) { /* Create a new buffer in the current window. */ if (!can_abandon(curbuf, flags & TERM_START_FORCEIT)) { no_write_message(); vim_free(term); return NULL; } if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE, ECMD_HIDE + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0), curwin) == FAIL) { vim_free(term); return NULL; } } else if (opt->jo_hidden || (flags & TERM_START_SYSTEM)) { buf_T *buf; /* Create a new buffer without a window. Make it the current buffer for * a moment to be able to do the initialisations. */ buf = buflist_new((char_u *)"", NULL, (linenr_T)0, BLN_NEW | BLN_LISTED); if (buf == NULL || ml_open(buf) == FAIL) { vim_free(term); return NULL; } old_curbuf = curbuf; --curbuf->b_nwindows; curbuf = buf; curwin->w_buffer = buf; ++curbuf->b_nwindows; } else { /* Open a new window or tab. */ split_ea.cmdidx = CMD_new; split_ea.cmd = (char_u *)"new"; split_ea.arg = (char_u *)""; if (opt->jo_term_rows > 0 && !vertical) { split_ea.line2 = opt->jo_term_rows; split_ea.addr_count = 1; } if (opt->jo_term_cols > 0 && vertical) { split_ea.line2 = opt->jo_term_cols; split_ea.addr_count = 1; } if (vertical) cmdmod.split |= WSP_VERT; ex_splitview(&split_ea); if (curwin == old_curwin) { /* split failed */ vim_free(term); return NULL; } } term->tl_buffer = curbuf; curbuf->b_term = term; if (!opt->jo_hidden) { /* Only one size was taken care of with :new, do the other one. With * "curwin" both need to be done. */ if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical)) win_setheight(opt->jo_term_rows); if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical)) win_setwidth(opt->jo_term_cols); } /* Link the new terminal in the list of active terminals. */ term->tl_next = first_term; first_term = term; if (opt->jo_term_name != NULL) curbuf->b_ffname = vim_strsave(opt->jo_term_name); else if (argv != NULL) curbuf->b_ffname = vim_strsave((char_u *)"!system"); else { int i; size_t len; char_u *cmd, *p; if (argvar->v_type == VAR_STRING) { cmd = argvar->vval.v_string; if (cmd == NULL) cmd = (char_u *)""; else if (STRCMP(cmd, "NONE") == 0) cmd = (char_u *)"pty"; } else if (argvar->v_type != VAR_LIST || argvar->vval.v_list == NULL || argvar->vval.v_list->lv_len < 1 || (cmd = tv_get_string_chk( &argvar->vval.v_list->lv_first->li_tv)) == NULL) cmd = (char_u*)""; len = STRLEN(cmd) + 10; p = alloc((int)len); for (i = 0; p != NULL; ++i) { /* Prepend a ! to the command name to avoid the buffer name equals * the executable, otherwise ":w!" would overwrite it. */ if (i == 0) vim_snprintf((char *)p, len, "!%s", cmd); else vim_snprintf((char *)p, len, "!%s (%d)", cmd, i); if (buflist_findname(p) == NULL) { vim_free(curbuf->b_ffname); curbuf->b_ffname = p; break; } } } curbuf->b_fname = curbuf->b_ffname; if (opt->jo_term_opencmd != NULL) term->tl_opencmd = vim_strsave(opt->jo_term_opencmd); if (opt->jo_eof_chars != NULL) term->tl_eof_chars = vim_strsave(opt->jo_eof_chars); set_string_option_direct((char_u *)"buftype", -1, (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0); // Avoid that 'buftype' is reset when this buffer is entered. curbuf->b_p_initialized = TRUE; /* Mark the buffer as not modifiable. It can only be made modifiable after * the job finished. */ curbuf->b_p_ma = FALSE; set_term_and_win_size(term); #ifdef WIN3264 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io)); #endif setup_job_options(opt, term->tl_rows, term->tl_cols); if (flags & TERM_START_NOJOB) return curbuf; #if defined(FEAT_SESSION) /* Remember the command for the session file. */ if (opt->jo_term_norestore || argv != NULL) { term->tl_command = vim_strsave((char_u *)"NONE"); } else if (argvar->v_type == VAR_STRING) { char_u *cmd = argvar->vval.v_string; if (cmd != NULL && STRCMP(cmd, p_sh) != 0) term->tl_command = vim_strsave(cmd); } else if (argvar->v_type == VAR_LIST && argvar->vval.v_list != NULL && argvar->vval.v_list->lv_len > 0) { garray_T ga; listitem_T *item; ga_init2(&ga, 1, 100); for (item = argvar->vval.v_list->lv_first; item != NULL; item = item->li_next) { char_u *s = tv_get_string_chk(&item->li_tv); char_u *p; if (s == NULL) break; p = vim_strsave_fnameescape(s, FALSE); if (p == NULL) break; ga_concat(&ga, p); vim_free(p); ga_append(&ga, ' '); } if (item == NULL) { ga_append(&ga, NUL); term->tl_command = ga.ga_data; } else ga_clear(&ga); } #endif if (opt->jo_term_kill != NULL) { char_u *p = skiptowhite(opt->jo_term_kill); term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill); } /* System dependent: setup the vterm and maybe start the job in it. */ if (argv == NULL && argvar->v_type == VAR_STRING && argvar->vval.v_string != NULL && STRCMP(argvar->vval.v_string, "NONE") == 0) res = create_pty_only(term, opt); else res = term_and_job_init(term, argvar, argv, opt, &orig_opt); newbuf = curbuf; if (res == OK) { /* Get and remember the size we ended up with. Update the pty. */ vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols); term_report_winsize(term, term->tl_rows, term->tl_cols); #ifdef FEAT_GUI if (term->tl_system) { /* display first line below typed command */ term->tl_toprow = msg_row + 1; term->tl_dirty_row_end = 0; } #endif /* Make sure we don't get stuck on sending keys to the job, it leads to * a deadlock if the job is waiting for Vim to read. */ channel_set_nonblock(term->tl_job->jv_channel, PART_IN); if (old_curbuf != NULL) { --curbuf->b_nwindows; curbuf = old_curbuf; curwin->w_buffer = curbuf; ++curbuf->b_nwindows; } } else { term_close_buffer(curbuf, old_curbuf); return NULL; } apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf); return newbuf; } /* * ":terminal": open a terminal window and execute a job in it. */ void ex_terminal(exarg_T *eap) { typval_T argvar[2]; jobopt_T opt; char_u *cmd; char_u *tofree = NULL; init_job_options(&opt); cmd = eap->arg; while (*cmd == '+' && *(cmd + 1) == '+') { char_u *p, *ep; cmd += 2; p = skiptowhite(cmd); ep = vim_strchr(cmd, '='); if (ep != NULL && ep < p) p = ep; if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0) opt.jo_term_finish = 'c'; else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0) opt.jo_term_finish = 'n'; else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0) opt.jo_term_finish = 'o'; else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0) opt.jo_curwin = 1; else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0) opt.jo_hidden = 1; else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0) opt.jo_term_norestore = 1; else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0 && ep != NULL) { opt.jo_set2 |= JO2_TERM_KILL; opt.jo_term_kill = ep + 1; p = skiptowhite(cmd); } else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0 && ep != NULL && isdigit(ep[1])) { opt.jo_set2 |= JO2_TERM_ROWS; opt.jo_term_rows = atoi((char *)ep + 1); p = skiptowhite(cmd); } else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0 && ep != NULL && isdigit(ep[1])) { opt.jo_set2 |= JO2_TERM_COLS; opt.jo_term_cols = atoi((char *)ep + 1); p = skiptowhite(cmd); } else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0 && ep != NULL) { char_u *buf = NULL; char_u *keys; p = skiptowhite(cmd); *p = NUL; keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE); opt.jo_set2 |= JO2_EOF_CHARS; opt.jo_eof_chars = vim_strsave(keys); vim_free(buf); *p = ' '; } else { if (*p) *p = NUL; EMSG2(_("E181: Invalid attribute: %s"), cmd); goto theend; } cmd = skipwhite(p); } if (*cmd == NUL) { /* Make a copy of 'shell', an autocommand may change the option. */ tofree = cmd = vim_strsave(p_sh); /* default to close when the shell exits */ if (opt.jo_term_finish == NUL) opt.jo_term_finish = 'c'; } if (eap->addr_count > 0) { /* Write lines from current buffer to the job. */ opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT; opt.jo_io[PART_IN] = JIO_BUFFER; opt.jo_io_buf[PART_IN] = curbuf->b_fnum; opt.jo_in_top = eap->line1; opt.jo_in_bot = eap->line2; } argvar[0].v_type = VAR_STRING; argvar[0].vval.v_string = cmd; argvar[1].v_type = VAR_UNKNOWN; term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0); vim_free(tofree); theend: vim_free(opt.jo_eof_chars); } #if defined(FEAT_SESSION) || defined(PROTO) /* * Write a :terminal command to the session file to restore the terminal in * window "wp". * Return FAIL if writing fails. */ int term_write_session(FILE *fd, win_T *wp) { term_T *term = wp->w_buffer->b_term; /* Create the terminal and run the command. This is not without * risk, but let's assume the user only creates a session when this * will be OK. */ if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ", term->tl_cols, term->tl_rows) < 0) return FAIL; if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0) return FAIL; return put_eol(fd); } /* * Return TRUE if "buf" has a terminal that should be restored. */ int term_should_restore(buf_T *buf) { term_T *term = buf->b_term; return term != NULL && (term->tl_command == NULL || STRCMP(term->tl_command, "NONE") != 0); } #endif /* * Free the scrollback buffer for "term". */ static void free_scrollback(term_T *term) { int i; for (i = 0; i < term->tl_scrollback.ga_len; ++i) vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells); ga_clear(&term->tl_scrollback); } /* * Free a terminal and everything it refers to. * Kills the job if there is one. * Called when wiping out a buffer. */ void free_terminal(buf_T *buf) { term_T *term = buf->b_term; term_T *tp; if (term == NULL) return; if (first_term == term) first_term = term->tl_next; else for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next) if (tp->tl_next == term) { tp->tl_next = term->tl_next; break; } if (term->tl_job != NULL) { if (term->tl_job->jv_status != JOB_ENDED && term->tl_job->jv_status != JOB_FINISHED && term->tl_job->jv_status != JOB_FAILED) job_stop(term->tl_job, NULL, "kill"); job_unref(term->tl_job); } free_scrollback(term); term_free_vterm(term); vim_free(term->tl_title); #ifdef FEAT_SESSION vim_free(term->tl_command); #endif vim_free(term->tl_kill); vim_free(term->tl_status_text); vim_free(term->tl_opencmd); vim_free(term->tl_eof_chars); #ifdef WIN3264 if (term->tl_out_fd != NULL) fclose(term->tl_out_fd); #endif vim_free(term->tl_cursor_color); vim_free(term); buf->b_term = NULL; if (in_terminal_loop == term) in_terminal_loop = NULL; } /* * Get the part that is connected to the tty. Normally this is PART_IN, but * when writing buffer lines to the job it can be another. This makes it * possible to do "1,5term vim -". */ static ch_part_T get_tty_part(term_T *term) { #ifdef UNIX ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR}; int i; for (i = 0; i < 3; ++i) { int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd; if (isatty(fd)) return parts[i]; } #endif return PART_IN; } /* * Write job output "msg[len]" to the vterm. */ static void term_write_job_output(term_T *term, char_u *msg, size_t len) { VTerm *vterm = term->tl_vterm; size_t prevlen = vterm_output_get_buffer_current(vterm); vterm_input_write(vterm, (char *)msg, len); /* flush vterm buffer when vterm responded to control sequence */ if (prevlen != vterm_output_get_buffer_current(vterm)) { char buf[KEY_BUF_LEN]; size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN); if (curlen > 0) channel_send(term->tl_job->jv_channel, get_tty_part(term), (char_u *)buf, (int)curlen, NULL); } /* this invokes the damage callbacks */ vterm_screen_flush_damage(vterm_obtain_screen(vterm)); } static void update_cursor(term_T *term, int redraw) { if (term->tl_normal_mode) return; #ifdef FEAT_GUI if (term->tl_system) windgoto(term->tl_cursor_pos.row + term->tl_toprow, term->tl_cursor_pos.col); else #endif setcursor(); if (redraw) { if (term->tl_buffer == curbuf && term->tl_cursor_visible) cursor_on(); out_flush(); #ifdef FEAT_GUI if (gui.in_use) { gui_update_cursor(FALSE, FALSE); gui_mch_flush(); } #endif } } /* * Invoked when "msg" output from a job was received. Write it to the terminal * of "buffer". */ void write_to_term(buf_T *buffer, char_u *msg, channel_T *channel) { size_t len = STRLEN(msg); term_T *term = buffer->b_term; #ifdef WIN3264 /* Win32: Cannot redirect output of the job, intercept it here and write to * the file. */ if (term->tl_out_fd != NULL) { ch_log(channel, "Writing %d bytes to output file", (int)len); fwrite(msg, len, 1, term->tl_out_fd); return; } #endif if (term->tl_vterm == NULL) { ch_log(channel, "NOT writing %d bytes to terminal", (int)len); return; } ch_log(channel, "writing %d bytes to terminal", (int)len); term_write_job_output(term, msg, len); #ifdef FEAT_GUI if (term->tl_system) { /* show system output, scrolling up the screen as needed */ update_system_term(term); update_cursor(term, TRUE); } else #endif /* In Terminal-Normal mode we are displaying the buffer, not the terminal * contents, thus no screen update is needed. */ if (!term->tl_normal_mode) { // Don't use update_screen() when editing the command line, it gets // cleared. // TODO: only update once in a while. ch_log(term->tl_job->jv_channel, "updating screen"); if (buffer == curbuf && (State & CMDLINE) == 0) { update_screen(VALID_NO_UPDATE); /* update_screen() can be slow, check the terminal wasn't closed * already */ if (buffer == curbuf && curbuf->b_term != NULL) update_cursor(curbuf->b_term, TRUE); } else redraw_after_callback(TRUE); } } /* * Send a mouse position and click to the vterm */ static int term_send_mouse(VTerm *vterm, int button, int pressed) { VTermModifier mod = VTERM_MOD_NONE; vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin), mouse_col - curwin->w_wincol, mod); if (button != 0) vterm_mouse_button(vterm, button, pressed, mod); return TRUE; } static int enter_mouse_col = -1; static int enter_mouse_row = -1; /* * Handle a mouse click, drag or release. * Return TRUE when a mouse event is sent to the terminal. */ static int term_mouse_click(VTerm *vterm, int key) { #if defined(FEAT_CLIPBOARD) /* For modeless selection mouse drag and release events are ignored, unless * they are preceded with a mouse down event */ static int ignore_drag_release = TRUE; VTermMouseState mouse_state; vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state); if (mouse_state.flags == 0) { /* Terminal is not using the mouse, use modeless selection. */ switch (key) { case K_LEFTDRAG: case K_LEFTRELEASE: case K_RIGHTDRAG: case K_RIGHTRELEASE: /* Ignore drag and release events when the button-down wasn't * seen before. */ if (ignore_drag_release) { int save_mouse_col, save_mouse_row; if (enter_mouse_col < 0) break; /* mouse click in the window gave us focus, handle that * click now */ save_mouse_col = mouse_col; save_mouse_row = mouse_row; mouse_col = enter_mouse_col; mouse_row = enter_mouse_row; clip_modeless(MOUSE_LEFT, TRUE, FALSE); mouse_col = save_mouse_col; mouse_row = save_mouse_row; } /* FALLTHROUGH */ case K_LEFTMOUSE: case K_RIGHTMOUSE: if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE) ignore_drag_release = TRUE; else ignore_drag_release = FALSE; /* Should we call mouse_has() here? */ if (clip_star.available) { int button, is_click, is_drag; button = get_mouse_button(KEY2TERMCAP1(key), &is_click, &is_drag); if (mouse_model_popup() && button == MOUSE_LEFT && (mod_mask & MOD_MASK_SHIFT)) { /* Translate shift-left to right button. */ button = MOUSE_RIGHT; mod_mask &= ~MOD_MASK_SHIFT; } clip_modeless(button, is_click, is_drag); } break; case K_MIDDLEMOUSE: if (clip_star.available) insert_reg('*', TRUE); break; } enter_mouse_col = -1; return FALSE; } #endif enter_mouse_col = -1; switch (key) { case K_LEFTMOUSE: case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break; case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break; case K_LEFTRELEASE: case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break; case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break; case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break; case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break; case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break; case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break; case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break; case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break; } return TRUE; } /* * Convert typed key "c" into bytes to send to the job. * Return the number of bytes in "buf". */ static int term_convert_key(term_T *term, int c, char *buf) { VTerm *vterm = term->tl_vterm; VTermKey key = VTERM_KEY_NONE; VTermModifier mod = VTERM_MOD_NONE; int other = FALSE; switch (c) { /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */ /* don't use VTERM_KEY_BACKSPACE, it always * becomes 0x7f DEL */ case K_BS: c = term_backspace_char; break; case ESC: key = VTERM_KEY_ESCAPE; break; case K_DEL: key = VTERM_KEY_DEL; break; case K_DOWN: key = VTERM_KEY_DOWN; break; case K_S_DOWN: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_DOWN; break; case K_END: key = VTERM_KEY_END; break; case K_S_END: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_END; break; case K_C_END: mod = VTERM_MOD_CTRL; key = VTERM_KEY_END; break; case K_F10: key = VTERM_KEY_FUNCTION(10); break; case K_F11: key = VTERM_KEY_FUNCTION(11); break; case K_F12: key = VTERM_KEY_FUNCTION(12); break; case K_F1: key = VTERM_KEY_FUNCTION(1); break; case K_F2: key = VTERM_KEY_FUNCTION(2); break; case K_F3: key = VTERM_KEY_FUNCTION(3); break; case K_F4: key = VTERM_KEY_FUNCTION(4); break; case K_F5: key = VTERM_KEY_FUNCTION(5); break; case K_F6: key = VTERM_KEY_FUNCTION(6); break; case K_F7: key = VTERM_KEY_FUNCTION(7); break; case K_F8: key = VTERM_KEY_FUNCTION(8); break; case K_F9: key = VTERM_KEY_FUNCTION(9); break; case K_HOME: key = VTERM_KEY_HOME; break; case K_S_HOME: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_HOME; break; case K_C_HOME: mod = VTERM_MOD_CTRL; key = VTERM_KEY_HOME; break; case K_INS: key = VTERM_KEY_INS; break; case K_K0: key = VTERM_KEY_KP_0; break; case K_K1: key = VTERM_KEY_KP_1; break; case K_K2: key = VTERM_KEY_KP_2; break; case K_K3: key = VTERM_KEY_KP_3; break; case K_K4: key = VTERM_KEY_KP_4; break; case K_K5: key = VTERM_KEY_KP_5; break; case K_K6: key = VTERM_KEY_KP_6; break; case K_K7: key = VTERM_KEY_KP_7; break; case K_K8: key = VTERM_KEY_KP_8; break; case K_K9: key = VTERM_KEY_KP_9; break; case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */ case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break; case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */ case K_KENTER: key = VTERM_KEY_KP_ENTER; break; case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */ case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */ case K_KMINUS: key = VTERM_KEY_KP_MINUS; break; case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break; case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */ case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */ case K_KPLUS: key = VTERM_KEY_KP_PLUS; break; case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break; case K_LEFT: key = VTERM_KEY_LEFT; break; case K_S_LEFT: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_LEFT; break; case K_C_LEFT: mod = VTERM_MOD_CTRL; key = VTERM_KEY_LEFT; break; case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break; case K_PAGEUP: key = VTERM_KEY_PAGEUP; break; case K_RIGHT: key = VTERM_KEY_RIGHT; break; case K_S_RIGHT: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_RIGHT; break; case K_C_RIGHT: mod = VTERM_MOD_CTRL; key = VTERM_KEY_RIGHT; break; case K_UP: key = VTERM_KEY_UP; break; case K_S_UP: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_UP; break; case TAB: key = VTERM_KEY_TAB; break; case K_S_TAB: mod = VTERM_MOD_SHIFT; key = VTERM_KEY_TAB; break; case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break; case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break; case K_MOUSELEFT: /* TODO */ return 0; case K_MOUSERIGHT: /* TODO */ return 0; case K_LEFTMOUSE: case K_LEFTMOUSE_NM: case K_LEFTDRAG: case K_LEFTRELEASE: case K_LEFTRELEASE_NM: case K_MOUSEMOVE: case K_MIDDLEMOUSE: case K_MIDDLEDRAG: case K_MIDDLERELEASE: case K_RIGHTMOUSE: case K_RIGHTDRAG: case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c)) return 0; other = TRUE; break; case K_X1MOUSE: /* TODO */ return 0; case K_X1DRAG: /* TODO */ return 0; case K_X1RELEASE: /* TODO */ return 0; case K_X2MOUSE: /* TODO */ return 0; case K_X2DRAG: /* TODO */ return 0; case K_X2RELEASE: /* TODO */ return 0; case K_IGNORE: return 0; case K_NOP: return 0; case K_UNDO: return 0; case K_HELP: return 0; case K_XF1: key = VTERM_KEY_FUNCTION(1); break; case K_XF2: key = VTERM_KEY_FUNCTION(2); break; case K_XF3: key = VTERM_KEY_FUNCTION(3); break; case K_XF4: key = VTERM_KEY_FUNCTION(4); break; case K_SELECT: return 0; #ifdef FEAT_GUI case K_VER_SCROLLBAR: return 0; case K_HOR_SCROLLBAR: return 0; #endif #ifdef FEAT_GUI_TABLINE case K_TABLINE: return 0; case K_TABMENU: return 0; #endif #ifdef FEAT_NETBEANS_INTG case K_F21: key = VTERM_KEY_FUNCTION(21); break; #endif #ifdef FEAT_DND case K_DROP: return 0; #endif case K_CURSORHOLD: return 0; case K_PS: vterm_keyboard_start_paste(vterm); other = TRUE; break; case K_PE: vterm_keyboard_end_paste(vterm); other = TRUE; break; } /* * Convert special keys to vterm keys: * - Write keys to vterm: vterm_keyboard_key() * - Write output to channel. * TODO: use mod_mask */ if (key != VTERM_KEY_NONE) /* Special key, let vterm convert it. */ vterm_keyboard_key(vterm, key, mod); else if (!other) /* Normal character, let vterm convert it. */ vterm_keyboard_unichar(vterm, c, mod); /* Read back the converted escape sequence. */ return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN); } /* * Return TRUE if the job for "term" is still running. * If "check_job_status" is TRUE update the job status. */ static int term_job_running_check(term_T *term, int check_job_status) { /* Also consider the job finished when the channel is closed, to avoid a * race condition when updating the title. */ if (term != NULL && term->tl_job != NULL && channel_is_open(term->tl_job->jv_channel)) { if (check_job_status) job_status(term->tl_job); return (term->tl_job->jv_status == JOB_STARTED || term->tl_job->jv_channel->ch_keep_open); } return FALSE; } /* * Return TRUE if the job for "term" is still running. */ int term_job_running(term_T *term) { return term_job_running_check(term, FALSE); } /* * Return TRUE if "term" has an active channel and used ":term NONE". */ int term_none_open(term_T *term) { /* Also consider the job finished when the channel is closed, to avoid a * race condition when updating the title. */ return term != NULL && term->tl_job != NULL && channel_is_open(term->tl_job->jv_channel) && term->tl_job->jv_channel->ch_keep_open; } /* * Used when exiting: kill the job in "buf" if so desired. * Return OK when the job finished. * Return FAIL when the job is still running. */ int term_try_stop_job(buf_T *buf) { int count; char *how = (char *)buf->b_term->tl_kill; #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm)) { char_u buff[DIALOG_MSG_SIZE]; int ret; dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname); ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1); if (ret == VIM_YES) how = "kill"; else if (ret == VIM_CANCEL) return FAIL; } #endif if (how == NULL || *how == NUL) return FAIL; job_stop(buf->b_term->tl_job, NULL, how); /* wait for up to a second for the job to die */ for (count = 0; count < 100; ++count) { /* buffer, terminal and job may be cleaned up while waiting */ if (!buf_valid(buf) || buf->b_term == NULL || buf->b_term->tl_job == NULL) return OK; /* call job_status() to update jv_status */ job_status(buf->b_term->tl_job); if (buf->b_term->tl_job->jv_status >= JOB_ENDED) return OK; ui_delay(10L, FALSE); mch_check_messages(); parse_queued_messages(); } return FAIL; } /* * Add the last line of the scrollback buffer to the buffer in the window. */ static void add_scrollback_line_to_buffer(term_T *term, char_u *text, int len) { buf_T *buf = term->tl_buffer; int empty = (buf->b_ml.ml_flags & ML_EMPTY); linenr_T lnum = buf->b_ml.ml_line_count; #ifdef WIN3264 if (!enc_utf8 && enc_codepage > 0) { WCHAR *ret = NULL; int length = 0; MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1, &ret, &length); if (ret != NULL) { WideCharToMultiByte_alloc(enc_codepage, 0, ret, length, (char **)&text, &len, 0, 0); vim_free(ret); ml_append_buf(term->tl_buffer, lnum, text, len, FALSE); vim_free(text); } } else #endif ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE); if (empty) { /* Delete the empty line that was in the empty buffer. */ curbuf = buf; ml_delete(1, FALSE); curbuf = curwin->w_buffer; } } static void cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr) { attr->width = cell->width; attr->attrs = cell->attrs; attr->fg = cell->fg; attr->bg = cell->bg; } static int equal_celattr(cellattr_T *a, cellattr_T *b) { /* Comparing the colors should be sufficient. */ return a->fg.red == b->fg.red && a->fg.green == b->fg.green && a->fg.blue == b->fg.blue && a->bg.red == b->bg.red && a->bg.green == b->bg.green && a->bg.blue == b->bg.blue; } /* * Add an empty scrollback line to "term". When "lnum" is not zero, add the * line at this position. Otherwise at the end. */ static int add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum) { if (ga_grow(&term->tl_scrollback, 1) == OK) { sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data + term->tl_scrollback.ga_len; if (lnum > 0) { int i; for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i) { *line = *(line - 1); --line; } } line->sb_cols = 0; line->sb_cells = NULL; line->sb_fill_attr = *fill_attr; ++term->tl_scrollback.ga_len; return OK; } return FALSE; } /* * Remove the terminal contents from the scrollback and the buffer. * Used before adding a new scrollback line or updating the buffer for lines * displayed in the terminal. */ static void cleanup_scrollback(term_T *term) { sb_line_T *line; garray_T *gap; curbuf = term->tl_buffer; gap = &term->tl_scrollback; while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled && gap->ga_len > 0) { ml_delete(curbuf->b_ml.ml_line_count, FALSE); line = (sb_line_T *)gap->ga_data + gap->ga_len - 1; vim_free(line->sb_cells); --gap->ga_len; } curbuf = curwin->w_buffer; if (curbuf == term->tl_buffer) check_cursor(); } /* * Add the current lines of the terminal to scrollback and to the buffer. */ static void update_snapshot(term_T *term) { VTermScreen *screen; int len; int lines_skipped = 0; VTermPos pos; VTermScreenCell cell; cellattr_T fill_attr, new_fill_attr; cellattr_T *p; ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel, "Adding terminal window snapshot to buffer"); /* First remove the lines that were appended before, they might be * outdated. */ cleanup_scrollback(term); screen = vterm_obtain_screen(term->tl_vterm); fill_attr = new_fill_attr = term->tl_default_color; for (pos.row = 0; pos.row < term->tl_rows; ++pos.row) { len = 0; for (pos.col = 0; pos.col < term->tl_cols; ++pos.col) if (vterm_screen_get_cell(screen, pos, &cell) != 0 && cell.chars[0] != NUL) { len = pos.col + 1; new_fill_attr = term->tl_default_color; } else /* Assume the last attr is the filler attr. */ cell2cellattr(&cell, &new_fill_attr); if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr)) ++lines_skipped; else { while (lines_skipped > 0) { /* Line was skipped, add an empty line. */ --lines_skipped; if (add_empty_scrollback(term, &fill_attr, 0) == OK) add_scrollback_line_to_buffer(term, (char_u *)"", 0); } if (len == 0) p = NULL; else p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len); if ((p != NULL || len == 0) && ga_grow(&term->tl_scrollback, 1) == OK) { garray_T ga; int width; sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data + term->tl_scrollback.ga_len; ga_init2(&ga, 1, 100); for (pos.col = 0; pos.col < len; pos.col += width) { if (vterm_screen_get_cell(screen, pos, &cell) == 0) { width = 1; vim_memset(p + pos.col, 0, sizeof(cellattr_T)); if (ga_grow(&ga, 1) == OK) ga.ga_len += utf_char2bytes(' ', (char_u *)ga.ga_data + ga.ga_len); } else { width = cell.width; cell2cellattr(&cell, &p[pos.col]); // Each character can be up to 6 bytes. if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK) { int i; int c; for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i) ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c, (char_u *)ga.ga_data + ga.ga_len); } } } line->sb_cols = len; line->sb_cells = p; line->sb_fill_attr = new_fill_attr; fill_attr = new_fill_attr; ++term->tl_scrollback.ga_len; if (ga_grow(&ga, 1) == FAIL) add_scrollback_line_to_buffer(term, (char_u *)"", 0); else { *((char_u *)ga.ga_data + ga.ga_len) = NUL; add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len); } ga_clear(&ga); } else vim_free(p); } } // Add trailing empty lines. for (pos.row = term->tl_scrollback.ga_len; pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row; ++pos.row) { if (add_empty_scrollback(term, &fill_attr, 0) == OK) add_scrollback_line_to_buffer(term, (char_u *)"", 0); } term->tl_dirty_snapshot = FALSE; #ifdef FEAT_TIMERS term->tl_timer_set = FALSE; #endif } /* * If needed, add the current lines of the terminal to scrollback and to the * buffer. Called after the job has ended and when switching to * Terminal-Normal mode. * When "redraw" is TRUE redraw the windows that show the terminal. */ static void may_move_terminal_to_buffer(term_T *term, int redraw) { win_T *wp; if (term->tl_vterm == NULL) return; /* Update the snapshot only if something changes or the buffer does not * have all the lines. */ if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count <= term->tl_scrollback_scrolled) update_snapshot(term); /* Obtain the current background color. */ vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm), &term->tl_default_color.fg, &term->tl_default_color.bg); if (redraw) FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == term->tl_buffer) { wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count; wp->w_cursor.col = 0; wp->w_valid = 0; if (wp->w_cursor.lnum >= wp->w_height) { linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1; if (wp->w_topline < min_topline) wp->w_topline = min_topline; } redraw_win_later(wp, NOT_VALID); } } } #if defined(FEAT_TIMERS) || defined(PROTO) /* * Check if any terminal timer expired. If so, copy text from the terminal to * the buffer. * Return the time until the next timer will expire. */ int term_check_timers(int next_due_arg, proftime_T *now) { term_T *term; int next_due = next_due_arg; for (term = first_term; term != NULL; term = term->tl_next) { if (term->tl_timer_set && !term->tl_normal_mode) { long this_due = proftime_time_left(&term->tl_timer_due, now); if (this_due <= 1) { term->tl_timer_set = FALSE; may_move_terminal_to_buffer(term, FALSE); } else if (next_due == -1 || next_due > this_due) next_due = this_due; } } return next_due; } #endif static void set_terminal_mode(term_T *term, int normal_mode) { term->tl_normal_mode = normal_mode; VIM_CLEAR(term->tl_status_text); if (term->tl_buffer == curbuf) maketitle(); } /* * Called after the job if finished and Terminal mode is not active: * Move the vterm contents into the scrollback buffer and free the vterm. */ static void cleanup_vterm(term_T *term) { if (term->tl_finish != TL_FINISH_CLOSE) may_move_terminal_to_buffer(term, TRUE); term_free_vterm(term); set_terminal_mode(term, FALSE); } /* * Switch from Terminal-Job mode to Terminal-Normal mode. * Suspends updating the terminal window. */ static void term_enter_normal_mode(void) { term_T *term = curbuf->b_term; set_terminal_mode(term, TRUE); /* Append the current terminal contents to the buffer. */ may_move_terminal_to_buffer(term, TRUE); /* Move the window cursor to the position of the cursor in the * terminal. */ curwin->w_cursor.lnum = term->tl_scrollback_scrolled + term->tl_cursor_pos.row + 1; check_cursor(); if (coladvance(term->tl_cursor_pos.col) == FAIL) coladvance(MAXCOL); /* Display the same lines as in the terminal. */ curwin->w_topline = term->tl_scrollback_scrolled + 1; } /* * Returns TRUE if the current window contains a terminal and we are in * Terminal-Normal mode. */ int term_in_normal_mode(void) { term_T *term = curbuf->b_term; return term != NULL && term->tl_normal_mode; } /* * Switch from Terminal-Normal mode to Terminal-Job mode. * Restores updating the terminal window. */ void term_enter_job_mode() { term_T *term = curbuf->b_term; set_terminal_mode(term, FALSE); if (term->tl_channel_closed) cleanup_vterm(term); redraw_buf_and_status_later(curbuf, NOT_VALID); } /* * Get a key from the user with terminal mode mappings. * Note: while waiting a terminal may be closed and freed if the channel is * closed and ++close was used. */ static int term_vgetc() { int c; int save_State = State; State = TERMINAL; got_int = FALSE; #ifdef WIN3264 ctrl_break_was_pressed = FALSE; #endif c = vgetc(); got_int = FALSE; State = save_State; return c; } static int mouse_was_outside = FALSE; /* * Send keys to terminal. * Return FAIL when the key needs to be handled in Normal mode. * Return OK when the key was dropped or sent to the terminal. */ int send_keys_to_term(term_T *term, int c, int typed) { char msg[KEY_BUF_LEN]; size_t len; int dragging_outside = FALSE; /* Catch keys that need to be handled as in Normal mode. */ switch (c) { case NUL: case K_ZERO: if (typed) stuffcharReadbuff(c); return FAIL; case K_TABLINE: stuffcharReadbuff(c); return FAIL; case K_IGNORE: case K_CANCEL: // used for :normal when running out of chars return FAIL; case K_LEFTDRAG: case K_MIDDLEDRAG: case K_RIGHTDRAG: case K_X1DRAG: case K_X2DRAG: dragging_outside = mouse_was_outside; /* FALLTHROUGH */ case K_LEFTMOUSE: case K_LEFTMOUSE_NM: case K_LEFTRELEASE: case K_LEFTRELEASE_NM: case K_MOUSEMOVE: case K_MIDDLEMOUSE: case K_MIDDLERELEASE: case K_RIGHTMOUSE: case K_RIGHTRELEASE: case K_X1MOUSE: case K_X1RELEASE: case K_X2MOUSE: case K_X2RELEASE: case K_MOUSEUP: case K_MOUSEDOWN: case K_MOUSELEFT: case K_MOUSERIGHT: if (mouse_row < W_WINROW(curwin) || mouse_row >= (W_WINROW(curwin) + curwin->w_height) || mouse_col < curwin->w_wincol || mouse_col >= W_ENDCOL(curwin) || dragging_outside) { /* click or scroll outside the current window or on status line * or vertical separator */ if (typed) { stuffcharReadbuff(c); mouse_was_outside = TRUE; } return FAIL; } } if (typed) mouse_was_outside = FALSE; /* Convert the typed key to a sequence of bytes for the job. */ len = term_convert_key(term, c, msg); if (len > 0) /* TODO: if FAIL is returned, stop? */ channel_send(term->tl_job->jv_channel, get_tty_part(term), (char_u *)msg, (int)len, NULL); return OK; } static void position_cursor(win_T *wp, VTermPos *pos) { wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1)); wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1)); wp->w_valid |= (VALID_WCOL|VALID_WROW); } /* * Handle CTRL-W "": send register contents to the job. */ static void term_paste_register(int prev_c UNUSED) { int c; list_T *l; listitem_T *item; long reglen = 0; int type; #ifdef FEAT_CMDL_INFO if (add_to_showcmd(prev_c)) if (add_to_showcmd('"')) out_flush(); #endif c = term_vgetc(); #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif if (!term_use_loop()) /* job finished while waiting for a character */ return; /* CTRL-W "= prompt for expression to evaluate. */ if (c == '=' && get_expr_register() != '=') return; if (!term_use_loop()) /* job finished while waiting for a character */ return; l = (list_T *)get_reg_contents(c, GREG_LIST); if (l != NULL) { type = get_reg_type(c, &reglen); for (item = l->lv_first; item != NULL; item = item->li_next) { char_u *s = tv_get_string(&item->li_tv); #ifdef WIN3264 char_u *tmp = s; if (!enc_utf8 && enc_codepage > 0) { WCHAR *ret = NULL; int length = 0; MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s, (int)STRLEN(s), &ret, &length); if (ret != NULL) { WideCharToMultiByte_alloc(CP_UTF8, 0, ret, length, (char **)&s, &length, 0, 0); vim_free(ret); } } #endif channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN, s, (int)STRLEN(s), NULL); #ifdef WIN3264 if (tmp != s) vim_free(s); #endif if (item->li_next != NULL || type == MLINE) channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN, (char_u *)"\r", 1, NULL); } list_free(l); } } /* * Return TRUE when waiting for a character in the terminal, the cursor of the * terminal should be displayed. */ int terminal_is_active() { return in_terminal_loop != NULL; } #if defined(FEAT_GUI) || defined(PROTO) cursorentry_T * term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg) { term_T *term = in_terminal_loop; static cursorentry_T entry; int id; guicolor_T term_fg, term_bg; vim_memset(&entry, 0, sizeof(entry)); entry.shape = entry.mshape = term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR : term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER : SHAPE_BLOCK; entry.percentage = 20; if (term->tl_cursor_blink) { entry.blinkwait = 700; entry.blinkon = 400; entry.blinkoff = 250; } /* The "Terminal" highlight group overrules the defaults. */ id = syn_name2id((char_u *)"Terminal"); if (id != 0) { syn_id2colors(id, &term_fg, &term_bg); *fg = term_bg; } else *fg = gui.back_pixel; if (term->tl_cursor_color == NULL) { if (id != 0) *bg = term_fg; else *bg = gui.norm_pixel; } else *bg = color_name2handle(term->tl_cursor_color); entry.name = "n"; entry.used_for = SHAPE_CURSOR; return &entry; } #endif static void may_output_cursor_props(void) { if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color) || last_set_cursor_shape != desired_cursor_shape || last_set_cursor_blink != desired_cursor_blink) { cursor_color_copy(&last_set_cursor_color, desired_cursor_color); last_set_cursor_shape = desired_cursor_shape; last_set_cursor_blink = desired_cursor_blink; term_cursor_color(cursor_color_get(desired_cursor_color)); if (desired_cursor_shape == -1 || desired_cursor_blink == -1) /* this will restore the initial cursor style, if possible */ ui_cursor_shape_forced(TRUE); else term_cursor_shape(desired_cursor_shape, desired_cursor_blink); } } /* * Set the cursor color and shape, if not last set to these. */ static void may_set_cursor_props(term_T *term) { #ifdef FEAT_GUI /* For the GUI the cursor properties are obtained with * term_get_cursor_shape(). */ if (gui.in_use) return; #endif if (in_terminal_loop == term) { cursor_color_copy(&desired_cursor_color, term->tl_cursor_color); desired_cursor_shape = term->tl_cursor_shape; desired_cursor_blink = term->tl_cursor_blink; may_output_cursor_props(); } } /* * Reset the desired cursor properties and restore them when needed. */ static void prepare_restore_cursor_props(void) { #ifdef FEAT_GUI if (gui.in_use) return; #endif cursor_color_copy(&desired_cursor_color, NULL); desired_cursor_shape = -1; desired_cursor_blink = -1; may_output_cursor_props(); } /* * Returns TRUE if the current window contains a terminal and we are sending * keys to the job. * If "check_job_status" is TRUE update the job status. */ static int term_use_loop_check(int check_job_status) { term_T *term = curbuf->b_term; return term != NULL && !term->tl_normal_mode && term->tl_vterm != NULL && term_job_running_check(term, check_job_status); } /* * Returns TRUE if the current window contains a terminal and we are sending * keys to the job. */ int term_use_loop(void) { return term_use_loop_check(FALSE); } /* * Called when entering a window with the mouse. If this is a terminal window * we may want to change state. */ void term_win_entered() { term_T *term = curbuf->b_term; if (term != NULL) { if (term_use_loop_check(TRUE)) { reset_VIsual_and_resel(); if (State & INSERT) stop_insert_mode = TRUE; } mouse_was_outside = FALSE; enter_mouse_col = mouse_col; enter_mouse_row = mouse_row; } } /* * Wait for input and send it to the job. * When "blocking" is TRUE wait for a character to be typed. Otherwise return * when there is no more typahead. * Return when the start of a CTRL-W command is typed or anything else that * should be handled as a Normal mode command. * Returns OK if a typed character is to be handled in Normal mode, FAIL if * the terminal was closed. */ int terminal_loop(int blocking) { int c; int termwinkey = 0; int ret; #ifdef UNIX int tty_fd = curbuf->b_term->tl_job->jv_channel ->ch_part[get_tty_part(curbuf->b_term)].ch_fd; #endif int restore_cursor = FALSE; /* Remember the terminal we are sending keys to. However, the terminal * might be closed while waiting for a character, e.g. typing "exit" in a * shell and ++close was used. Therefore use curbuf->b_term instead of a * stored reference. */ in_terminal_loop = curbuf->b_term; if (*curwin->w_p_twk != NUL) { termwinkey = string_to_key(curwin->w_p_twk, TRUE); if (termwinkey == Ctrl_W) termwinkey = 0; } position_cursor(curwin, &curbuf->b_term->tl_cursor_pos); may_set_cursor_props(curbuf->b_term); while (blocking || vpeekc_nomap() != NUL) { #ifdef FEAT_GUI if (!curbuf->b_term->tl_system) #endif /* TODO: skip screen update when handling a sequence of keys. */ /* Repeat redrawing in case a message is received while redrawing. */ while (must_redraw != 0) if (update_screen(0) == FAIL) break; if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term) /* job finished while redrawing */ break; update_cursor(curbuf->b_term, FALSE); restore_cursor = TRUE; c = term_vgetc(); if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term) { /* Job finished while waiting for a character. Push back the * received character. */ if (c != K_IGNORE) vungetc(c); break; } if (c == K_IGNORE) continue; #ifdef UNIX /* * The shell or another program may change the tty settings. Getting * them for every typed character is a bit of overhead, but it's needed * for the first character typed, e.g. when Vim starts in a shell. */ if (isatty(tty_fd)) { ttyinfo_T info; /* Get the current backspace character of the pty. */ if (get_tty_info(tty_fd, &info) == OK) term_backspace_char = info.backspace; } #endif #ifdef WIN3264 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT. * Use CTRL-BREAK to kill the job. */ if (ctrl_break_was_pressed) mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill"); #endif /* Was either CTRL-W (termwinkey) or CTRL-\ pressed? * Not in a system terminal. */ if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL) #ifdef FEAT_GUI && !curbuf->b_term->tl_system #endif ) { int prev_c = c; #ifdef FEAT_CMDL_INFO if (add_to_showcmd(c)) out_flush(); #endif c = term_vgetc(); #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term) /* job finished while waiting for a character */ break; if (prev_c == Ctrl_BSL) { if (c == Ctrl_N) { /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */ term_enter_normal_mode(); ret = FAIL; goto theend; } /* Send both keys to the terminal. */ send_keys_to_term(curbuf->b_term, prev_c, TRUE); } else if (c == Ctrl_C) { /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */ mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill"); } else if (c == '.') { /* "CTRL-W .": send CTRL-W to the job */ /* "'termwinkey' .": send 'termwinkey' to the job */ c = termwinkey == 0 ? Ctrl_W : termwinkey; } else if (c == Ctrl_BSL) { /* "CTRL-W CTRL-\": send CTRL-\ to the job */ c = Ctrl_BSL; } else if (c == 'N') { /* CTRL-W N : go to Terminal-Normal mode. */ term_enter_normal_mode(); ret = FAIL; goto theend; } else if (c == '"') { term_paste_register(prev_c); continue; } else if (termwinkey == 0 || c != termwinkey) { stuffcharReadbuff(Ctrl_W); stuffcharReadbuff(c); ret = OK; goto theend; } } # ifdef WIN3264 if (!enc_utf8 && has_mbyte && c >= 0x80) { WCHAR wc; char_u mb[3]; mb[0] = (unsigned)c >> 8; mb[1] = c; if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0) c = wc; } # endif if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK) { if (c == K_MOUSEMOVE) /* We are sure to come back here, don't reset the cursor color * and shape to avoid flickering. */ restore_cursor = FALSE; ret = OK; goto theend; } } ret = FAIL; theend: in_terminal_loop = NULL; if (restore_cursor) prepare_restore_cursor_props(); /* Move a snapshot of the screen contents to the buffer, so that completion * works in other buffers. */ if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode) may_move_terminal_to_buffer(curbuf->b_term, FALSE); return ret; } /* * Called when a job has finished. * This updates the title and status, but does not close the vterm, because * there might still be pending output in the channel. */ void term_job_ended(job_T *job) { term_T *term; int did_one = FALSE; for (term = first_term; term != NULL; term = term->tl_next) if (term->tl_job == job) { VIM_CLEAR(term->tl_title); VIM_CLEAR(term->tl_status_text); redraw_buf_and_status_later(term->tl_buffer, VALID); did_one = TRUE; } if (did_one) redraw_statuslines(); if (curbuf->b_term != NULL) { if (curbuf->b_term->tl_job == job) maketitle(); update_cursor(curbuf->b_term, TRUE); } } static void may_toggle_cursor(term_T *term) { if (in_terminal_loop == term) { if (term->tl_cursor_visible) cursor_on(); else cursor_off(); } } /* * Reverse engineer the RGB value into a cterm color index. * First color is 1. Return 0 if no match found (default color). */ static int color2index(VTermColor *color, int fg, int *boldp) { int red = color->red; int blue = color->blue; int green = color->green; if (color->ansi_index != VTERM_ANSI_INDEX_NONE) { /* First 16 colors and default: use the ANSI index, because these * colors can be redefined. */ if (t_colors >= 16) return color->ansi_index; switch (color->ansi_index) { case 0: return 0; case 1: return lookup_color( 0, fg, boldp) + 1; /* black */ case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */ case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */ case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */ case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */ case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */ case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */ case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */ case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */ case 10: return lookup_color(20, fg, boldp) + 1; /* red */ case 11: return lookup_color(16, fg, boldp) + 1; /* green */ case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */ case 13: return lookup_color(14, fg, boldp) + 1; /* blue */ case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */ case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */ case 16: return lookup_color(26, fg, boldp) + 1; /* white */ } } if (t_colors >= 256) { if (red == blue && red == green) { /* 24-color greyscale plus white and black */ static int cutoff[23] = { 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67, 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB, 0xD5, 0xDF, 0xE9}; int i; if (red < 5) return 17; /* 00/00/00 */ if (red > 245) /* ff/ff/ff */ return 232; for (i = 0; i < 23; ++i) if (red < cutoff[i]) return i + 233; return 256; } { static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB}; int ri, gi, bi; /* 216-color cube */ for (ri = 0; ri < 5; ++ri) if (red < cutoff[ri]) break; for (gi = 0; gi < 5; ++gi) if (green < cutoff[gi]) break; for (bi = 0; bi < 5; ++bi) if (blue < cutoff[bi]) break; return 17 + ri * 36 + gi * 6 + bi; } } return 0; } /* * Convert Vterm attributes to highlight flags. */ static int vtermAttr2hl(VTermScreenCellAttrs cellattrs) { int attr = 0; if (cellattrs.bold) attr |= HL_BOLD; if (cellattrs.underline) attr |= HL_UNDERLINE; if (cellattrs.italic) attr |= HL_ITALIC; if (cellattrs.strike) attr |= HL_STRIKETHROUGH; if (cellattrs.reverse) attr |= HL_INVERSE; return attr; } /* * Store Vterm attributes in "cell" from highlight flags. */ static void hl2vtermAttr(int attr, cellattr_T *cell) { vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs)); if (attr & HL_BOLD) cell->attrs.bold = 1; if (attr & HL_UNDERLINE) cell->attrs.underline = 1; if (attr & HL_ITALIC) cell->attrs.italic = 1; if (attr & HL_STRIKETHROUGH) cell->attrs.strike = 1; if (attr & HL_INVERSE) cell->attrs.reverse = 1; } /* * Convert the attributes of a vterm cell into an attribute index. */ static int cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg) { int attr = vtermAttr2hl(cellattrs); #ifdef FEAT_GUI if (gui.in_use) { guicolor_T fg, bg; fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue); bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue); return get_gui_attr_idx(attr, fg, bg); } else #endif #ifdef FEAT_TERMGUICOLORS if (p_tgc) { guicolor_T fg, bg; fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue); bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue); return get_tgc_attr_idx(attr, fg, bg); } else #endif { int bold = MAYBE; int fg = color2index(&cellfg, TRUE, &bold); int bg = color2index(&cellbg, FALSE, &bold); /* Use the "Terminal" highlighting for the default colors. */ if ((fg == 0 || bg == 0) && t_colors >= 16) { if (fg == 0 && term_default_cterm_fg >= 0) fg = term_default_cterm_fg + 1; if (bg == 0 && term_default_cterm_bg >= 0) bg = term_default_cterm_bg + 1; } /* with 8 colors set the bold attribute to get a bright foreground */ if (bold == TRUE) attr |= HL_BOLD; return get_cterm_attr_idx(attr, fg, bg); } return 0; } static void set_dirty_snapshot(term_T *term) { term->tl_dirty_snapshot = TRUE; #ifdef FEAT_TIMERS if (!term->tl_normal_mode) { /* Update the snapshot after 100 msec of not getting updates. */ profile_setlimit(100L, &term->tl_timer_due); term->tl_timer_set = TRUE; } #endif } static int handle_damage(VTermRect rect, void *user) { term_T *term = (term_T *)user; term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row); term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row); set_dirty_snapshot(term); redraw_buf_later(term->tl_buffer, SOME_VALID); return 1; } static void term_scroll_up(term_T *term, int start_row, int count) { win_T *wp; VTermColor fg, bg; VTermScreenCellAttrs attr; int clear_attr; /* Set the color to clear lines with. */ vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm), &fg, &bg); vim_memset(&attr, 0, sizeof(attr)); clear_attr = cell2attr(attr, fg, bg); FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == term->tl_buffer) win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr); } } static int handle_moverect(VTermRect dest, VTermRect src, void *user) { term_T *term = (term_T *)user; int count = src.start_row - dest.start_row; /* Scrolling up is done much more efficiently by deleting lines instead of * redrawing the text. But avoid doing this multiple times, postpone until * the redraw happens. */ if (dest.start_col == src.start_col && dest.end_col == src.end_col && dest.start_row < src.start_row) { if (dest.start_row == 0) term->tl_postponed_scroll += count; else term_scroll_up(term, dest.start_row, count); } term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row); term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row); set_dirty_snapshot(term); /* Note sure if the scrolling will work correctly, let's do a complete * redraw later. */ redraw_buf_later(term->tl_buffer, NOT_VALID); return 1; } static int handle_movecursor( VTermPos pos, VTermPos oldpos UNUSED, int visible, void *user) { term_T *term = (term_T *)user; win_T *wp; term->tl_cursor_pos = pos; term->tl_cursor_visible = visible; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == term->tl_buffer) position_cursor(wp, &pos); } if (term->tl_buffer == curbuf && !term->tl_normal_mode) { may_toggle_cursor(term); update_cursor(term, term->tl_cursor_visible); } return 1; } static int handle_settermprop( VTermProp prop, VTermValue *value, void *user) { term_T *term = (term_T *)user; switch (prop) { case VTERM_PROP_TITLE: vim_free(term->tl_title); /* a blank title isn't useful, make it empty, so that "running" is * displayed */ if (*skipwhite((char_u *)value->string) == NUL) term->tl_title = NULL; #ifdef WIN3264 else if (!enc_utf8 && enc_codepage > 0) { WCHAR *ret = NULL; int length = 0; MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)value->string, (int)STRLEN(value->string), &ret, &length); if (ret != NULL) { WideCharToMultiByte_alloc(enc_codepage, 0, ret, length, (char**)&term->tl_title, &length, 0, 0); vim_free(ret); } } #endif else term->tl_title = vim_strsave((char_u *)value->string); VIM_CLEAR(term->tl_status_text); if (term == curbuf->b_term) maketitle(); break; case VTERM_PROP_CURSORVISIBLE: term->tl_cursor_visible = value->boolean; may_toggle_cursor(term); out_flush(); break; case VTERM_PROP_CURSORBLINK: term->tl_cursor_blink = value->boolean; may_set_cursor_props(term); break; case VTERM_PROP_CURSORSHAPE: term->tl_cursor_shape = value->number; may_set_cursor_props(term); break; case VTERM_PROP_CURSORCOLOR: cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string); may_set_cursor_props(term); break; case VTERM_PROP_ALTSCREEN: /* TODO: do anything else? */ term->tl_using_altscreen = value->boolean; break; default: break; } /* Always return 1, otherwise vterm doesn't store the value internally. */ return 1; } /* * The job running in the terminal resized the terminal. */ static int handle_resize(int rows, int cols, void *user) { term_T *term = (term_T *)user; win_T *wp; term->tl_rows = rows; term->tl_cols = cols; if (term->tl_vterm_size_changed) /* Size was set by vterm_set_size(), don't set the window size. */ term->tl_vterm_size_changed = FALSE; else { FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == term->tl_buffer) { win_setheight_win(rows, wp); win_setwidth_win(cols, wp); } } redraw_buf_later(term->tl_buffer, NOT_VALID); } return 1; } /* * Handle a line that is pushed off the top of the screen. */ static int handle_pushline(int cols, const VTermScreenCell *cells, void *user) { term_T *term = (term_T *)user; /* First remove the lines that were appended before, the pushed line goes * above it. */ cleanup_scrollback(term); /* If the number of lines that are stored goes over 'termscrollback' then * delete the first 10%. */ if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl) { int todo = term->tl_buffer->b_p_twsl / 10; int i; curbuf = term->tl_buffer; for (i = 0; i < todo; ++i) { vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells); ml_delete(1, FALSE); } curbuf = curwin->w_buffer; term->tl_scrollback.ga_len -= todo; mch_memmove(term->tl_scrollback.ga_data, (sb_line_T *)term->tl_scrollback.ga_data + todo, sizeof(sb_line_T) * term->tl_scrollback.ga_len); term->tl_scrollback_scrolled -= todo; } if (ga_grow(&term->tl_scrollback, 1) == OK) { cellattr_T *p = NULL; int len = 0; int i; int c; int col; sb_line_T *line; garray_T ga; cellattr_T fill_attr = term->tl_default_color; /* do not store empty cells at the end */ for (i = 0; i < cols; ++i) if (cells[i].chars[0] != 0) len = i + 1; else cell2cellattr(&cells[i], &fill_attr); ga_init2(&ga, 1, 100); if (len > 0) p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len); if (p != NULL) { for (col = 0; col < len; col += cells[col].width) { if (ga_grow(&ga, MB_MAXBYTES) == FAIL) { ga.ga_len = 0; break; } for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i) ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c, (char_u *)ga.ga_data + ga.ga_len); cell2cellattr(&cells[col], &p[col]); } } if (ga_grow(&ga, 1) == FAIL) add_scrollback_line_to_buffer(term, (char_u *)"", 0); else { *((char_u *)ga.ga_data + ga.ga_len) = NUL; add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len); } ga_clear(&ga); line = (sb_line_T *)term->tl_scrollback.ga_data + term->tl_scrollback.ga_len; line->sb_cols = len; line->sb_cells = p; line->sb_fill_attr = fill_attr; ++term->tl_scrollback.ga_len; ++term->tl_scrollback_scrolled; } return 0; /* ignored */ } static VTermScreenCallbacks screen_callbacks = { handle_damage, /* damage */ handle_moverect, /* moverect */ handle_movecursor, /* movecursor */ handle_settermprop, /* settermprop */ NULL, /* bell */ handle_resize, /* resize */ handle_pushline, /* sb_pushline */ NULL /* sb_popline */ }; /* * Do the work after the channel of a terminal was closed. * Must be called only when updating_screen is FALSE. * Returns TRUE when a buffer was closed (list of terminals may have changed). */ static int term_after_channel_closed(term_T *term) { /* Unless in Terminal-Normal mode: clear the vterm. */ if (!term->tl_normal_mode) { int fnum = term->tl_buffer->b_fnum; cleanup_vterm(term); if (term->tl_finish == TL_FINISH_CLOSE) { aco_save_T aco; int do_set_w_closing = term->tl_buffer->b_nwindows == 0; // ++close or term_finish == "close" ch_log(NULL, "terminal job finished, closing window"); aucmd_prepbuf(&aco, term->tl_buffer); // Avoid closing the window if we temporarily use it. if (do_set_w_closing) curwin->w_closing = TRUE; do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE); if (do_set_w_closing) curwin->w_closing = FALSE; aucmd_restbuf(&aco); return TRUE; } if (term->tl_finish == TL_FINISH_OPEN && term->tl_buffer->b_nwindows == 0) { char buf[50]; /* TODO: use term_opencmd */ ch_log(NULL, "terminal job finished, opening window"); vim_snprintf(buf, sizeof(buf), term->tl_opencmd == NULL ? "botright sbuf %d" : (char *)term->tl_opencmd, fnum); do_cmdline_cmd((char_u *)buf); } else ch_log(NULL, "terminal job finished"); } redraw_buf_and_status_later(term->tl_buffer, NOT_VALID); return FALSE; } /* * Called when a channel has been closed. * If this was a channel for a terminal window then finish it up. */ void term_channel_closed(channel_T *ch) { term_T *term; term_T *next_term; int did_one = FALSE; for (term = first_term; term != NULL; term = next_term) { next_term = term->tl_next; if (term->tl_job == ch->ch_job) { term->tl_channel_closed = TRUE; did_one = TRUE; VIM_CLEAR(term->tl_title); VIM_CLEAR(term->tl_status_text); #ifdef WIN3264 if (term->tl_out_fd != NULL) { fclose(term->tl_out_fd); term->tl_out_fd = NULL; } #endif if (updating_screen) { /* Cannot open or close windows now. Can happen when * 'lazyredraw' is set. */ term->tl_channel_recently_closed = TRUE; continue; } if (term_after_channel_closed(term)) next_term = first_term; } } if (did_one) { redraw_statuslines(); /* Need to break out of vgetc(). */ ins_char_typebuf(K_IGNORE); typebuf_was_filled = TRUE; term = curbuf->b_term; if (term != NULL) { if (term->tl_job == ch->ch_job) maketitle(); update_cursor(term, term->tl_cursor_visible); } } } /* * To be called after resetting updating_screen: handle any terminal where the * channel was closed. */ void term_check_channel_closed_recently() { term_T *term; term_T *next_term; for (term = first_term; term != NULL; term = next_term) { next_term = term->tl_next; if (term->tl_channel_recently_closed) { term->tl_channel_recently_closed = FALSE; if (term_after_channel_closed(term)) // start over, the list may have changed next_term = first_term; } } } /* * Fill one screen line from a line of the terminal. * Advances "pos" to past the last column. */ static void term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col) { int off = screen_get_current_line_off(); for (pos->col = 0; pos->col < max_col; ) { VTermScreenCell cell; int c; if (vterm_screen_get_cell(screen, *pos, &cell) == 0) vim_memset(&cell, 0, sizeof(cell)); c = cell.chars[0]; if (c == NUL) { ScreenLines[off] = ' '; if (enc_utf8) ScreenLinesUC[off] = NUL; } else { if (enc_utf8) { int i; /* composing chars */ for (i = 0; i < Screen_mco && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i) { ScreenLinesC[i][off] = cell.chars[i + 1]; if (cell.chars[i + 1] == 0) break; } if (c >= 0x80 || (Screen_mco > 0 && ScreenLinesC[0][off] != 0)) { ScreenLines[off] = ' '; ScreenLinesUC[off] = c; } else { ScreenLines[off] = c; ScreenLinesUC[off] = NUL; } } #ifdef WIN3264 else if (has_mbyte && c >= 0x80) { char_u mb[MB_MAXBYTES+1]; WCHAR wc = c; if (WideCharToMultiByte(GetACP(), 0, &wc, 1, (char*)mb, 2, 0, 0) > 1) { ScreenLines[off] = mb[0]; ScreenLines[off + 1] = mb[1]; cell.width = mb_ptr2cells(mb); } else ScreenLines[off] = c; } #endif else ScreenLines[off] = c; } ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg); ++pos->col; ++off; if (cell.width == 2) { if (enc_utf8) ScreenLinesUC[off] = NUL; /* don't set the second byte to NUL for a DBCS encoding, it * has been set above */ if (enc_utf8 || !has_mbyte) ScreenLines[off] = NUL; ++pos->col; ++off; } } } #if defined(FEAT_GUI) static void update_system_term(term_T *term) { VTermPos pos; VTermScreen *screen; if (term->tl_vterm == NULL) return; screen = vterm_obtain_screen(term->tl_vterm); /* Scroll up to make more room for terminal lines if needed. */ while (term->tl_toprow > 0 && (Rows - term->tl_toprow) < term->tl_dirty_row_end) { int save_p_more = p_more; p_more = FALSE; msg_row = Rows - 1; msg_puts((char_u *)"\n"); p_more = save_p_more; --term->tl_toprow; } for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end && pos.row < Rows; ++pos.row) { if (pos.row < term->tl_rows) { int max_col = MIN(Columns, term->tl_cols); term_line2screenline(screen, &pos, max_col); } else pos.col = 0; screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE); } term->tl_dirty_row_start = MAX_ROW; term->tl_dirty_row_end = 0; update_cursor(term, TRUE); } #endif /* * Return TRUE if window "wp" is to be redrawn with term_update_window(). * Returns FALSE when there is no terminal running in this window or it is in * Terminal-Normal mode. */ int term_do_update_window(win_T *wp) { term_T *term = wp->w_buffer->b_term; return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode; } /* * Called to update a window that contains an active terminal. */ void term_update_window(win_T *wp) { term_T *term = wp->w_buffer->b_term; VTerm *vterm; VTermScreen *screen; VTermState *state; VTermPos pos; int rows, cols; int newrows, newcols; int minsize; win_T *twp; vterm = term->tl_vterm; screen = vterm_obtain_screen(vterm); state = vterm_obtain_state(vterm); /* We use NOT_VALID on a resize or scroll, redraw everything then. With * SOME_VALID only redraw what was marked dirty. */ if (wp->w_redr_type > SOME_VALID) { term->tl_dirty_row_start = 0; term->tl_dirty_row_end = MAX_ROW; if (term->tl_postponed_scroll > 0 && term->tl_postponed_scroll < term->tl_rows / 3) /* Scrolling is usually faster than redrawing, when there are only * a few lines to scroll. */ term_scroll_up(term, 0, term->tl_postponed_scroll); term->tl_postponed_scroll = 0; } /* * If the window was resized a redraw will be triggered and we get here. * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size. */ minsize = parse_termwinsize(wp, &rows, &cols); newrows = 99999; newcols = 99999; FOR_ALL_WINDOWS(twp) { /* When more than one window shows the same terminal, use the * smallest size. */ if (twp->w_buffer == term->tl_buffer) { newrows = MIN(newrows, twp->w_height); newcols = MIN(newcols, twp->w_width); } } newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows; newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols; if (term->tl_rows != newrows || term->tl_cols != newcols) { term->tl_vterm_size_changed = TRUE; vterm_set_size(vterm, newrows, newcols); ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines", newrows); term_report_winsize(term, newrows, newcols); // Updating the terminal size will cause the snapshot to be cleared. // When not in terminal_loop() we need to restore it. if (term != in_terminal_loop) may_move_terminal_to_buffer(term, FALSE); } /* The cursor may have been moved when resizing. */ vterm_state_get_cursorpos(state, &pos); position_cursor(wp, &pos); for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end && pos.row < wp->w_height; ++pos.row) { if (pos.row < term->tl_rows) { int max_col = MIN(wp->w_width, term->tl_cols); term_line2screenline(screen, &pos, max_col); } else pos.col = 0; screen_line(wp->w_winrow + pos.row #ifdef FEAT_MENU + winbar_height(wp) #endif , wp->w_wincol, pos.col, wp->w_width, FALSE); } term->tl_dirty_row_start = MAX_ROW; term->tl_dirty_row_end = 0; } /* * Return TRUE if "wp" is a terminal window where the job has finished. */ int term_is_finished(buf_T *buf) { return buf->b_term != NULL && buf->b_term->tl_vterm == NULL; } /* * Return TRUE if "wp" is a terminal window where the job has finished or we * are in Terminal-Normal mode, thus we show the buffer contents. */ int term_show_buffer(buf_T *buf) { term_T *term = buf->b_term; return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode); } /* * The current buffer is going to be changed. If there is terminal * highlighting remove it now. */ void term_change_in_curbuf(void) { term_T *term = curbuf->b_term; if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0) { free_scrollback(term); redraw_buf_later(term->tl_buffer, NOT_VALID); /* The buffer is now like a normal buffer, it cannot be easily * abandoned when changed. */ set_string_option_direct((char_u *)"buftype", -1, (char_u *)"", OPT_FREE|OPT_LOCAL, 0); } } /* * Get the screen attribute for a position in the buffer. * Use a negative "col" to get the filler background color. */ int term_get_attr(buf_T *buf, linenr_T lnum, int col) { term_T *term = buf->b_term; sb_line_T *line; cellattr_T *cellattr; if (lnum > term->tl_scrollback.ga_len) cellattr = &term->tl_default_color; else { line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1; if (col < 0 || col >= line->sb_cols) cellattr = &line->sb_fill_attr; else cellattr = line->sb_cells + col; } return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg); } /* * Convert a cterm color number 0 - 255 to RGB. * This is compatible with xterm. */ static void cterm_color2vterm(int nr, VTermColor *rgb) { cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index); } /* * Initialize term->tl_default_color from the environment. */ static void init_default_colors(term_T *term) { VTermColor *fg, *bg; int fgval, bgval; int id; vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs)); term->tl_default_color.width = 1; fg = &term->tl_default_color.fg; bg = &term->tl_default_color.bg; /* Vterm uses a default black background. Set it to white when * 'background' is "light". */ if (*p_bg == 'l') { fgval = 0; bgval = 255; } else { fgval = 255; bgval = 0; } fg->red = fg->green = fg->blue = fgval; bg->red = bg->green = bg->blue = bgval; fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT; /* The "Terminal" highlight group overrules the defaults. */ id = syn_name2id((char_u *)"Terminal"); /* Use the actual color for the GUI and when 'termguicolors' is set. */ #if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) if (0 # ifdef FEAT_GUI || gui.in_use # endif # ifdef FEAT_TERMGUICOLORS || p_tgc # ifdef FEAT_VTP /* Finally get INVALCOLOR on this execution path */ || (!p_tgc && t_colors >= 256) # endif # endif ) { guicolor_T fg_rgb = INVALCOLOR; guicolor_T bg_rgb = INVALCOLOR; if (id != 0) syn_id2colors(id, &fg_rgb, &bg_rgb); # ifdef FEAT_GUI if (gui.in_use) { if (fg_rgb == INVALCOLOR) fg_rgb = gui.norm_pixel; if (bg_rgb == INVALCOLOR) bg_rgb = gui.back_pixel; } # ifdef FEAT_TERMGUICOLORS else # endif # endif # ifdef FEAT_TERMGUICOLORS { if (fg_rgb == INVALCOLOR) fg_rgb = cterm_normal_fg_gui_color; if (bg_rgb == INVALCOLOR) bg_rgb = cterm_normal_bg_gui_color; } # endif if (fg_rgb != INVALCOLOR) { long_u rgb = GUI_MCH_GET_RGB(fg_rgb); fg->red = (unsigned)(rgb >> 16); fg->green = (unsigned)(rgb >> 8) & 255; fg->blue = (unsigned)rgb & 255; } if (bg_rgb != INVALCOLOR) { long_u rgb = GUI_MCH_GET_RGB(bg_rgb); bg->red = (unsigned)(rgb >> 16); bg->green = (unsigned)(rgb >> 8) & 255; bg->blue = (unsigned)rgb & 255; } } else #endif if (id != 0 && t_colors >= 16) { if (term_default_cterm_fg >= 0) cterm_color2vterm(term_default_cterm_fg, fg); if (term_default_cterm_bg >= 0) cterm_color2vterm(term_default_cterm_bg, bg); } else { #if defined(WIN3264) && !defined(FEAT_GUI_W32) int tmp; #endif /* In an MS-Windows console we know the normal colors. */ if (cterm_normal_fg_color > 0) { cterm_color2vterm(cterm_normal_fg_color - 1, fg); # if defined(WIN3264) && !defined(FEAT_GUI_W32) tmp = fg->red; fg->red = fg->blue; fg->blue = tmp; # endif } # ifdef FEAT_TERMRESPONSE else term_get_fg_color(&fg->red, &fg->green, &fg->blue); # endif if (cterm_normal_bg_color > 0) { cterm_color2vterm(cterm_normal_bg_color - 1, bg); # if defined(WIN3264) && !defined(FEAT_GUI_W32) tmp = bg->red; bg->red = bg->blue; bg->blue = tmp; # endif } # ifdef FEAT_TERMRESPONSE else term_get_bg_color(&bg->red, &bg->green, &bg->blue); # endif } } #if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) /* * Set the 16 ANSI colors from array of RGB values */ static void set_vterm_palette(VTerm *vterm, long_u *rgb) { int index = 0; VTermState *state = vterm_obtain_state(vterm); for (; index < 16; index++) { VTermColor color; color.red = (unsigned)(rgb[index] >> 16); color.green = (unsigned)(rgb[index] >> 8) & 255; color.blue = (unsigned)rgb[index] & 255; vterm_state_set_palette_color(state, index, &color); } } /* * Set the ANSI color palette from a list of colors */ static int set_ansi_colors_list(VTerm *vterm, list_T *list) { int n = 0; long_u rgb[16]; listitem_T *li = list->lv_first; for (; li != NULL && n < 16; li = li->li_next, n++) { char_u *color_name; guicolor_T guicolor; color_name = tv_get_string_chk(&li->li_tv); if (color_name == NULL) return FAIL; guicolor = GUI_GET_COLOR(color_name); if (guicolor == INVALCOLOR) return FAIL; rgb[n] = GUI_MCH_GET_RGB(guicolor); } if (n != 16 || li != NULL) return FAIL; set_vterm_palette(vterm, rgb); return OK; } /* * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15] */ static void init_vterm_ansi_colors(VTerm *vterm) { dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE); if (var != NULL && (var->di_tv.v_type != VAR_LIST || var->di_tv.vval.v_list == NULL || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)) EMSG2(_(e_invarg2), "g:terminal_ansi_colors"); } #endif /* * Handles a "drop" command from the job in the terminal. * "item" is the file name, "item->li_next" may have options. */ static void handle_drop_command(listitem_T *item) { char_u *fname = tv_get_string(&item->li_tv); listitem_T *opt_item = item->li_next; int bufnr; win_T *wp; tabpage_T *tp; exarg_T ea; char_u *tofree = NULL; bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT); FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp->w_buffer->b_fnum == bufnr) { /* buffer is in a window already, go there */ goto_tabpage_win(tp, wp); return; } } vim_memset(&ea, 0, sizeof(ea)); if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT && opt_item->li_tv.vval.v_dict != NULL) { dict_T *dict = opt_item->li_tv.vval.v_dict; char_u *p; p = dict_get_string(dict, (char_u *)"ff", FALSE); if (p == NULL) p = dict_get_string(dict, (char_u *)"fileformat", FALSE); if (p != NULL) { if (check_ff_value(p) == FAIL) ch_log(NULL, "Invalid ff argument to drop: %s", p); else ea.force_ff = *p; } p = dict_get_string(dict, (char_u *)"enc", FALSE); if (p == NULL) p = dict_get_string(dict, (char_u *)"encoding", FALSE); if (p != NULL) { ea.cmd = alloc((int)STRLEN(p) + 12); if (ea.cmd != NULL) { sprintf((char *)ea.cmd, "sbuf ++enc=%s", p); ea.force_enc = 11; tofree = ea.cmd; } } p = dict_get_string(dict, (char_u *)"bad", FALSE); if (p != NULL) get_bad_opt(p, &ea); if (dict_find(dict, (char_u *)"bin", -1) != NULL) ea.force_bin = FORCE_BIN; if (dict_find(dict, (char_u *)"binary", -1) != NULL) ea.force_bin = FORCE_BIN; if (dict_find(dict, (char_u *)"nobin", -1) != NULL) ea.force_bin = FORCE_NOBIN; if (dict_find(dict, (char_u *)"nobinary", -1) != NULL) ea.force_bin = FORCE_NOBIN; } /* open in new window, like ":split fname" */ if (ea.cmd == NULL) ea.cmd = (char_u *)"split"; ea.arg = fname; ea.cmdidx = CMD_split; ex_splitview(&ea); vim_free(tofree); } /* * Handles a function call from the job running in a terminal. * "item" is the function name, "item->li_next" has the arguments. */ static void handle_call_command(term_T *term, channel_T *channel, listitem_T *item) { char_u *func; typval_T argvars[2]; typval_T rettv; int doesrange; if (item->li_next == NULL) { ch_log(channel, "Missing function arguments for call"); return; } func = tv_get_string(&item->li_tv); if (STRNCMP(func, "Tapi_", 5) != 0) { ch_log(channel, "Invalid function name: %s", func); return; } argvars[0].v_type = VAR_NUMBER; argvars[0].vval.v_number = term->tl_buffer->b_fnum; argvars[1] = item->li_next->li_tv; if (call_func(func, (int)STRLEN(func), &rettv, 2, argvars, /* argv_func */ NULL, /* firstline */ 1, /* lastline */ 1, &doesrange, /* evaluate */ TRUE, /* partial */ NULL, /* selfdict */ NULL) == OK) { clear_tv(&rettv); ch_log(channel, "Function %s called", func); } else ch_log(channel, "Calling function %s failed", func); } /* * Called by libvterm when it cannot recognize an OSC sequence. * We recognize a terminal API command. */ static int parse_osc(const char *command, size_t cmdlen, void *user) { term_T *term = (term_T *)user; js_read_T reader; typval_T tv; channel_T *channel = term->tl_job == NULL ? NULL : term->tl_job->jv_channel; /* We recognize only OSC 5 1 ; {command} */ if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0) return 0; /* not handled */ reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3)); if (reader.js_buf == NULL) return 1; reader.js_fill = NULL; reader.js_used = 0; if (json_decode(&reader, &tv, 0) == OK && tv.v_type == VAR_LIST && tv.vval.v_list != NULL) { listitem_T *item = tv.vval.v_list->lv_first; if (item == NULL) ch_log(channel, "Missing command"); else { char_u *cmd = tv_get_string(&item->li_tv); /* Make sure an invoked command doesn't delete the buffer (and the * terminal) under our fingers. */ ++term->tl_buffer->b_locked; item = item->li_next; if (item == NULL) ch_log(channel, "Missing argument for %s", cmd); else if (STRCMP(cmd, "drop") == 0) handle_drop_command(item); else if (STRCMP(cmd, "call") == 0) handle_call_command(term, channel, item); else ch_log(channel, "Invalid command received: %s", cmd); --term->tl_buffer->b_locked; } } else ch_log(channel, "Invalid JSON received"); vim_free(reader.js_buf); clear_tv(&tv); return 1; } static VTermParserCallbacks parser_fallbacks = { NULL, /* text */ NULL, /* control */ NULL, /* escape */ NULL, /* csi */ parse_osc, /* osc */ NULL, /* dcs */ NULL /* resize */ }; /* * Use Vim's allocation functions for vterm so profiling works. */ static void * vterm_malloc(size_t size, void *data UNUSED) { return alloc_clear((unsigned) size); } static void vterm_memfree(void *ptr, void *data UNUSED) { vim_free(ptr); } static VTermAllocatorFunctions vterm_allocator = { &vterm_malloc, &vterm_memfree }; /* * Create a new vterm and initialize it. */ static void create_vterm(term_T *term, int rows, int cols) { VTerm *vterm; VTermScreen *screen; VTermState *state; VTermValue value; vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL); term->tl_vterm = vterm; screen = vterm_obtain_screen(vterm); vterm_screen_set_callbacks(screen, &screen_callbacks, term); /* TODO: depends on 'encoding'. */ vterm_set_utf8(vterm, 1); init_default_colors(term); vterm_state_set_default_colors( vterm_obtain_state(vterm), &term->tl_default_color.fg, &term->tl_default_color.bg); if (t_colors >= 16) vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1); /* Required to initialize most things. */ vterm_screen_reset(screen, 1 /* hard */); /* Allow using alternate screen. */ vterm_screen_enable_altscreen(screen, 1); /* For unix do not use a blinking cursor. In an xterm this causes the * cursor to blink if it's blinking in the xterm. * For Windows we respect the system wide setting. */ #ifdef WIN3264 if (GetCaretBlinkTime() == INFINITE) value.boolean = 0; else value.boolean = 1; #else value.boolean = 0; #endif state = vterm_obtain_state(vterm); vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value); vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term); } /* * Return the text to show for the buffer name and status. */ char_u * term_get_status_text(term_T *term) { if (term->tl_status_text == NULL) { char_u *txt; size_t len; if (term->tl_normal_mode) { if (term_job_running(term)) txt = (char_u *)_("Terminal"); else txt = (char_u *)_("Terminal-finished"); } else if (term->tl_title != NULL) txt = term->tl_title; else if (term_none_open(term)) txt = (char_u *)_("active"); else if (term_job_running(term)) txt = (char_u *)_("running"); else txt = (char_u *)_("finished"); len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt); term->tl_status_text = alloc((int)len); if (term->tl_status_text != NULL) vim_snprintf((char *)term->tl_status_text, len, "%s [%s]", term->tl_buffer->b_fname, txt); } return term->tl_status_text; } /* * Mark references in jobs of terminals. */ int set_ref_in_term(int copyID) { int abort = FALSE; term_T *term; typval_T tv; for (term = first_term; term != NULL; term = term->tl_next) if (term->tl_job != NULL) { tv.v_type = VAR_JOB; tv.vval.v_job = term->tl_job; abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL); } return abort; } /* * Cache "Terminal" highlight group colors. */ void set_terminal_default_colors(int cterm_fg, int cterm_bg) { term_default_cterm_fg = cterm_fg - 1; term_default_cterm_bg = cterm_bg - 1; } /* * Get the buffer from the first argument in "argvars". * Returns NULL when the buffer is not for a terminal window and logs a message * with "where". */ static buf_T * term_get_buf(typval_T *argvars, char *where) { buf_T *buf; (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */ ++emsg_off; buf = get_buf_tv(&argvars[0], FALSE); --emsg_off; if (buf == NULL || buf->b_term == NULL) { ch_log(NULL, "%s: invalid buffer argument", where); return NULL; } return buf; } static int same_color(VTermColor *a, VTermColor *b) { return a->red == b->red && a->green == b->green && a->blue == b->blue && a->ansi_index == b->ansi_index; } static void dump_term_color(FILE *fd, VTermColor *color) { fprintf(fd, "%02x%02x%02x%d", (int)color->red, (int)color->green, (int)color->blue, (int)color->ansi_index); } /* * "term_dumpwrite(buf, filename, options)" function * * Each screen cell in full is: * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx} * {characters} is a space for an empty cell * For a double-width character "+" is changed to "*" and the next cell is * skipped. * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc. * when "&" use the same as the previous cell. * {fg-color} is hex RGB, when "&" use the same as the previous cell. * {bg-color} is hex RGB, when "&" use the same as the previous cell. * {color-idx} is a number from 0 to 255 * * Screen cell with same width, attributes and color as the previous one: * |{characters} * * To use the color of the previous cell, use "&" instead of {color}-{idx}. * * Repeating the previous screen cell: * @{count} */ void f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED) { buf_T *buf = term_get_buf(argvars, "term_dumpwrite()"); term_T *term; char_u *fname; int max_height = 0; int max_width = 0; stat_T st; FILE *fd; VTermPos pos; VTermScreen *screen; VTermScreenCell prev_cell; VTermState *state; VTermPos cursor_pos; if (check_restricted() || check_secure()) return; if (buf == NULL) return; term = buf->b_term; if (term->tl_vterm == NULL) { EMSG(_("E958: Job already finished")); return; } if (argvars[2].v_type != VAR_UNKNOWN) { dict_T *d; if (argvars[2].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } d = argvars[2].vval.v_dict; if (d != NULL) { max_height = dict_get_number(d, (char_u *)"rows"); max_width = dict_get_number(d, (char_u *)"columns"); } } fname = tv_get_string_chk(&argvars[1]); if (fname == NULL) return; if (mch_stat((char *)fname, &st) >= 0) { EMSG2(_("E953: File exists: %s"), fname); return; } if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL) { EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname); return; } vim_memset(&prev_cell, 0, sizeof(prev_cell)); screen = vterm_obtain_screen(term->tl_vterm); state = vterm_obtain_state(term->tl_vterm); vterm_state_get_cursorpos(state, &cursor_pos); for (pos.row = 0; (max_height == 0 || pos.row < max_height) && pos.row < term->tl_rows; ++pos.row) { int repeat = 0; for (pos.col = 0; (max_width == 0 || pos.col < max_width) && pos.col < term->tl_cols; ++pos.col) { VTermScreenCell cell; int same_attr; int same_chars = TRUE; int i; int is_cursor_pos = (pos.col == cursor_pos.col && pos.row == cursor_pos.row); if (vterm_screen_get_cell(screen, pos, &cell) == 0) vim_memset(&cell, 0, sizeof(cell)); for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i) { int c = cell.chars[i]; int pc = prev_cell.chars[i]; /* For the first character NUL is the same as space. */ if (i == 0) { c = (c == NUL) ? ' ' : c; pc = (pc == NUL) ? ' ' : pc; } if (c != pc) same_chars = FALSE; if (c == NUL || pc == NUL) break; } same_attr = vtermAttr2hl(cell.attrs) == vtermAttr2hl(prev_cell.attrs) && same_color(&cell.fg, &prev_cell.fg) && same_color(&cell.bg, &prev_cell.bg); if (same_chars && cell.width == prev_cell.width && same_attr && !is_cursor_pos) { ++repeat; } else { if (repeat > 0) { fprintf(fd, "@%d", repeat); repeat = 0; } fputs(is_cursor_pos ? ">" : "|", fd); if (cell.chars[0] == NUL) fputs(" ", fd); else { char_u charbuf[10]; int len; for (i = 0; i < VTERM_MAX_CHARS_PER_CELL && cell.chars[i] != NUL; ++i) { len = utf_char2bytes(cell.chars[i], charbuf); fwrite(charbuf, len, 1, fd); } } /* When only the characters differ we don't write anything, the * following "|", "@" or NL will indicate using the same * attributes. */ if (cell.width != prev_cell.width || !same_attr) { if (cell.width == 2) { fputs("*", fd); ++pos.col; } else fputs("+", fd); if (same_attr) { fputs("&", fd); } else { fprintf(fd, "%d", vtermAttr2hl(cell.attrs)); if (same_color(&cell.fg, &prev_cell.fg)) fputs("&", fd); else { fputs("#", fd); dump_term_color(fd, &cell.fg); } if (same_color(&cell.bg, &prev_cell.bg)) fputs("&", fd); else { fputs("#", fd); dump_term_color(fd, &cell.bg); } } } prev_cell = cell; } } if (repeat > 0) fprintf(fd, "@%d", repeat); fputs("\n", fd); } fclose(fd); } /* * Called when a dump is corrupted. Put a breakpoint here when debugging. */ static void dump_is_corrupt(garray_T *gap) { ga_concat(gap, (char_u *)"CORRUPT"); } static void append_cell(garray_T *gap, cellattr_T *cell) { if (ga_grow(gap, 1) == OK) { *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell; ++gap->ga_len; } } /* * Read the dump file from "fd" and append lines to the current buffer. * Return the cell width of the longest line. */ static int read_dump_file(FILE *fd, VTermPos *cursor_pos) { int c; garray_T ga_text; garray_T ga_cell; char_u *prev_char = NULL; int attr = 0; cellattr_T cell; term_T *term = curbuf->b_term; int max_cells = 0; int start_row = term->tl_scrollback.ga_len; ga_init2(&ga_text, 1, 90); ga_init2(&ga_cell, sizeof(cellattr_T), 90); vim_memset(&cell, 0, sizeof(cell)); cursor_pos->row = -1; cursor_pos->col = -1; c = fgetc(fd); for (;;) { if (c == EOF) break; if (c == '\r') { // DOS line endings? Ignore. c = fgetc(fd); } else if (c == '\n') { /* End of a line: append it to the buffer. */ if (ga_text.ga_data == NULL) dump_is_corrupt(&ga_text); if (ga_grow(&term->tl_scrollback, 1) == OK) { sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data + term->tl_scrollback.ga_len; if (max_cells < ga_cell.ga_len) max_cells = ga_cell.ga_len; line->sb_cols = ga_cell.ga_len; line->sb_cells = ga_cell.ga_data; line->sb_fill_attr = term->tl_default_color; ++term->tl_scrollback.ga_len; ga_init(&ga_cell); ga_append(&ga_text, NUL); ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data, ga_text.ga_len, FALSE); } else ga_clear(&ga_cell); ga_text.ga_len = 0; c = fgetc(fd); } else if (c == '|' || c == '>') { int prev_len = ga_text.ga_len; if (c == '>') { if (cursor_pos->row != -1) dump_is_corrupt(&ga_text); /* duplicate cursor */ cursor_pos->row = term->tl_scrollback.ga_len - start_row; cursor_pos->col = ga_cell.ga_len; } /* normal character(s) followed by "+", "*", "|", "@" or NL */ c = fgetc(fd); if (c != EOF) ga_append(&ga_text, c); for (;;) { c = fgetc(fd); if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@' || c == EOF || c == '\n') break; ga_append(&ga_text, c); } /* save the character for repeating it */ vim_free(prev_char); if (ga_text.ga_data != NULL) prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len, ga_text.ga_len - prev_len); if (c == '@' || c == '|' || c == '>' || c == '\n') { /* use all attributes from previous cell */ } else if (c == '+' || c == '*') { int is_bg; cell.width = c == '+' ? 1 : 2; c = fgetc(fd); if (c == '&') { /* use same attr as previous cell */ c = fgetc(fd); } else if (isdigit(c)) { /* get the decimal attribute */ attr = 0; while (isdigit(c)) { attr = attr * 10 + (c - '0'); c = fgetc(fd); } hl2vtermAttr(attr, &cell); } else dump_is_corrupt(&ga_text); /* is_bg == 0: fg, is_bg == 1: bg */ for (is_bg = 0; is_bg <= 1; ++is_bg) { if (c == '&') { /* use same color as previous cell */ c = fgetc(fd); } else if (c == '#') { int red, green, blue, index = 0; c = fgetc(fd); red = hex2nr(c); c = fgetc(fd); red = (red << 4) + hex2nr(c); c = fgetc(fd); green = hex2nr(c); c = fgetc(fd); green = (green << 4) + hex2nr(c); c = fgetc(fd); blue = hex2nr(c); c = fgetc(fd); blue = (blue << 4) + hex2nr(c); c = fgetc(fd); if (!isdigit(c)) dump_is_corrupt(&ga_text); while (isdigit(c)) { index = index * 10 + (c - '0'); c = fgetc(fd); } if (is_bg) { cell.bg.red = red; cell.bg.green = green; cell.bg.blue = blue; cell.bg.ansi_index = index; } else { cell.fg.red = red; cell.fg.green = green; cell.fg.blue = blue; cell.fg.ansi_index = index; } } else dump_is_corrupt(&ga_text); } } else dump_is_corrupt(&ga_text); append_cell(&ga_cell, &cell); } else if (c == '@') { if (prev_char == NULL) dump_is_corrupt(&ga_text); else { int count = 0; /* repeat previous character, get the count */ for (;;) { c = fgetc(fd); if (!isdigit(c)) break; count = count * 10 + (c - '0'); } while (count-- > 0) { ga_concat(&ga_text, prev_char); append_cell(&ga_cell, &cell); } } } else { dump_is_corrupt(&ga_text); c = fgetc(fd); } } if (ga_text.ga_len > 0) { /* trailing characters after last NL */ dump_is_corrupt(&ga_text); ga_append(&ga_text, NUL); ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data, ga_text.ga_len, FALSE); } ga_clear(&ga_text); vim_free(prev_char); return max_cells; } /* * Return an allocated string with at least "text_width" "=" characters and * "fname" inserted in the middle. */ static char_u * get_separator(int text_width, char_u *fname) { int width = MAX(text_width, curwin->w_width); char_u *textline; int fname_size; char_u *p = fname; int i; size_t off; textline = alloc(width + (int)STRLEN(fname) + 1); if (textline == NULL) return NULL; fname_size = vim_strsize(fname); if (fname_size < width - 8) { /* enough room, don't use the full window width */ width = MAX(text_width, fname_size + 8); } else if (fname_size > width - 8) { /* full name doesn't fit, use only the tail */ p = gettail(fname); fname_size = vim_strsize(p); } /* skip characters until the name fits */ while (fname_size > width - 8) { p += (*mb_ptr2len)(p); fname_size = vim_strsize(p); } for (i = 0; i < (width - fname_size) / 2 - 1; ++i) textline[i] = '='; textline[i++] = ' '; STRCPY(textline + i, p); off = STRLEN(textline); textline[off] = ' '; for (i = 1; i < (width - fname_size) / 2; ++i) textline[off + i] = '='; textline[off + i] = NUL; return textline; } /* * Common for "term_dumpdiff()" and "term_dumpload()". */ static void term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff) { jobopt_T opt; buf_T *buf; char_u buf1[NUMBUFLEN]; char_u buf2[NUMBUFLEN]; char_u *fname1; char_u *fname2 = NULL; char_u *fname_tofree = NULL; FILE *fd1; FILE *fd2 = NULL; char_u *textline = NULL; /* First open the files. If this fails bail out. */ fname1 = tv_get_string_buf_chk(&argvars[0], buf1); if (do_diff) fname2 = tv_get_string_buf_chk(&argvars[1], buf2); if (fname1 == NULL || (do_diff && fname2 == NULL)) { EMSG(_(e_invarg)); return; } fd1 = mch_fopen((char *)fname1, READBIN); if (fd1 == NULL) { EMSG2(_(e_notread), fname1); return; } if (do_diff) { fd2 = mch_fopen((char *)fname2, READBIN); if (fd2 == NULL) { fclose(fd1); EMSG2(_(e_notread), fname2); return; } } init_job_options(&opt); if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0, JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL) goto theend; if (opt.jo_term_name == NULL) { size_t len = STRLEN(fname1) + 12; fname_tofree = alloc((int)len); if (fname_tofree != NULL) { vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1); opt.jo_term_name = fname_tofree; } } buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB); if (buf != NULL && buf->b_term != NULL) { int i; linenr_T bot_lnum; linenr_T lnum; term_T *term = buf->b_term; int width; int width2; VTermPos cursor_pos1; VTermPos cursor_pos2; init_default_colors(term); rettv->vval.v_number = buf->b_fnum; /* read the files, fill the buffer with the diff */ width = read_dump_file(fd1, &cursor_pos1); /* position the cursor */ if (cursor_pos1.row >= 0) { curwin->w_cursor.lnum = cursor_pos1.row + 1; coladvance(cursor_pos1.col); } /* Delete the empty line that was in the empty buffer. */ ml_delete(1, FALSE); /* For term_dumpload() we are done here. */ if (!do_diff) goto theend; term->tl_top_diff_rows = curbuf->b_ml.ml_line_count; textline = get_separator(width, fname1); if (textline == NULL) goto theend; if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK) ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE); vim_free(textline); textline = get_separator(width, fname2); if (textline == NULL) goto theend; if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK) ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE); textline[width] = NUL; bot_lnum = curbuf->b_ml.ml_line_count; width2 = read_dump_file(fd2, &cursor_pos2); if (width2 > width) { vim_free(textline); textline = alloc(width2 + 1); if (textline == NULL) goto theend; width = width2; textline[width] = NUL; } term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum; for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum) { if (lnum + bot_lnum > curbuf->b_ml.ml_line_count) { /* bottom part has fewer rows, fill with "-" */ for (i = 0; i < width; ++i) textline[i] = '-'; } else { char_u *line1; char_u *line2; char_u *p1; char_u *p2; int col; sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data; cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells; cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1) ->sb_cells; /* Make a copy, getting the second line will invalidate it. */ line1 = vim_strsave(ml_get(lnum)); if (line1 == NULL) break; p1 = line1; line2 = ml_get(lnum + bot_lnum); p2 = line2; for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col) { int len1 = utfc_ptr2len(p1); int len2 = utfc_ptr2len(p2); textline[col] = ' '; if (len1 != len2 || STRNCMP(p1, p2, len1) != 0) /* text differs */ textline[col] = 'X'; else if (lnum == cursor_pos1.row + 1 && col == cursor_pos1.col && (cursor_pos1.row != cursor_pos2.row || cursor_pos1.col != cursor_pos2.col)) /* cursor in first but not in second */ textline[col] = '>'; else if (lnum == cursor_pos2.row + 1 && col == cursor_pos2.col && (cursor_pos1.row != cursor_pos2.row || cursor_pos1.col != cursor_pos2.col)) /* cursor in second but not in first */ textline[col] = '<'; else if (cellattr1 != NULL && cellattr2 != NULL) { if ((cellattr1 + col)->width != (cellattr2 + col)->width) textline[col] = 'w'; else if (!same_color(&(cellattr1 + col)->fg, &(cellattr2 + col)->fg)) textline[col] = 'f'; else if (!same_color(&(cellattr1 + col)->bg, &(cellattr2 + col)->bg)) textline[col] = 'b'; else if (vtermAttr2hl((cellattr1 + col)->attrs) != vtermAttr2hl(((cellattr2 + col)->attrs))) textline[col] = 'a'; } p1 += len1; p2 += len2; /* TODO: handle different width */ } vim_free(line1); while (col < width) { if (*p1 == NUL && *p2 == NUL) textline[col] = '?'; else if (*p1 == NUL) { textline[col] = '+'; p2 += utfc_ptr2len(p2); } else { textline[col] = '-'; p1 += utfc_ptr2len(p1); } ++col; } } if (add_empty_scrollback(term, &term->tl_default_color, term->tl_top_diff_rows) == OK) ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE); ++bot_lnum; } while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count) { /* bottom part has more rows, fill with "+" */ for (i = 0; i < width; ++i) textline[i] = '+'; if (add_empty_scrollback(term, &term->tl_default_color, term->tl_top_diff_rows) == OK) ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE); ++lnum; ++bot_lnum; } term->tl_cols = width; /* looks better without wrapping */ curwin->w_p_wrap = 0; } theend: vim_free(textline); vim_free(fname_tofree); fclose(fd1); if (fd2 != NULL) fclose(fd2); } /* * If the current buffer shows the output of term_dumpdiff(), swap the top and * bottom files. * Return FAIL when this is not possible. */ int term_swap_diff() { term_T *term = curbuf->b_term; linenr_T line_count; linenr_T top_rows; linenr_T bot_rows; linenr_T bot_start; linenr_T lnum; char_u *p; sb_line_T *sb_line; if (term == NULL || !term_is_finished(curbuf) || term->tl_top_diff_rows == 0 || term->tl_scrollback.ga_len == 0) return FAIL; line_count = curbuf->b_ml.ml_line_count; top_rows = term->tl_top_diff_rows; bot_rows = term->tl_bot_diff_rows; bot_start = line_count - bot_rows; sb_line = (sb_line_T *)term->tl_scrollback.ga_data; /* move lines from top to above the bottom part */ for (lnum = 1; lnum <= top_rows; ++lnum) { p = vim_strsave(ml_get(1)); if (p == NULL) return OK; ml_append(bot_start, p, 0, FALSE); ml_delete(1, FALSE); vim_free(p); } /* move lines from bottom to the top */ for (lnum = 1; lnum <= bot_rows; ++lnum) { p = vim_strsave(ml_get(bot_start + lnum)); if (p == NULL) return OK; ml_delete(bot_start + lnum, FALSE); ml_append(lnum - 1, p, 0, FALSE); vim_free(p); } if (top_rows == bot_rows) { /* rows counts are equal, can swap cell properties */ for (lnum = 0; lnum < top_rows; ++lnum) { sb_line_T temp; temp = *(sb_line + lnum); *(sb_line + lnum) = *(sb_line + bot_start + lnum); *(sb_line + bot_start + lnum) = temp; } } else { size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len; sb_line_T *temp = (sb_line_T *)alloc((int)size); /* need to copy cell properties into temp memory */ if (temp != NULL) { mch_memmove(temp, term->tl_scrollback.ga_data, size); mch_memmove(term->tl_scrollback.ga_data, temp + bot_start, sizeof(sb_line_T) * bot_rows); mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows, temp + top_rows, sizeof(sb_line_T) * (line_count - top_rows - bot_rows)); mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + line_count - top_rows, temp, sizeof(sb_line_T) * top_rows); vim_free(temp); } } term->tl_top_diff_rows = bot_rows; term->tl_bot_diff_rows = top_rows; update_screen(NOT_VALID); return OK; } /* * "term_dumpdiff(filename, filename, options)" function */ void f_term_dumpdiff(typval_T *argvars, typval_T *rettv) { term_load_dump(argvars, rettv, TRUE); } /* * "term_dumpload(filename, options)" function */ void f_term_dumpload(typval_T *argvars, typval_T *rettv) { term_load_dump(argvars, rettv, FALSE); } /* * "term_getaltscreen(buf)" function */ void f_term_getaltscreen(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getaltscreen()"); if (buf == NULL) return; rettv->vval.v_number = buf->b_term->tl_using_altscreen; } /* * "term_getattr(attr, name)" function */ void f_term_getattr(typval_T *argvars, typval_T *rettv) { int attr; size_t i; char_u *name; static struct { char *name; int attr; } attrs[] = { {"bold", HL_BOLD}, {"italic", HL_ITALIC}, {"underline", HL_UNDERLINE}, {"strike", HL_STRIKETHROUGH}, {"reverse", HL_INVERSE}, }; attr = tv_get_number(&argvars[0]); name = tv_get_string_chk(&argvars[1]); if (name == NULL) return; for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i) if (STRCMP(name, attrs[i].name) == 0) { rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0; break; } } /* * "term_getcursor(buf)" function */ void f_term_getcursor(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getcursor()"); term_T *term; list_T *l; dict_T *d; if (rettv_list_alloc(rettv) == FAIL) return; if (buf == NULL) return; term = buf->b_term; l = rettv->vval.v_list; list_append_number(l, term->tl_cursor_pos.row + 1); list_append_number(l, term->tl_cursor_pos.col + 1); d = dict_alloc(); if (d != NULL) { dict_add_number(d, "visible", term->tl_cursor_visible); dict_add_number(d, "blink", blink_state_is_inverted() ? !term->tl_cursor_blink : term->tl_cursor_blink); dict_add_number(d, "shape", term->tl_cursor_shape); dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color)); list_append_dict(l, d); } } /* * "term_getjob(buf)" function */ void f_term_getjob(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getjob()"); if (buf == NULL) { rettv->v_type = VAR_SPECIAL; rettv->vval.v_number = VVAL_NULL; return; } rettv->v_type = VAR_JOB; rettv->vval.v_job = buf->b_term->tl_job; if (rettv->vval.v_job != NULL) ++rettv->vval.v_job->jv_refcount; } static int get_row_number(typval_T *tv, term_T *term) { if (tv->v_type == VAR_STRING && tv->vval.v_string != NULL && STRCMP(tv->vval.v_string, ".") == 0) return term->tl_cursor_pos.row; return (int)tv_get_number(tv) - 1; } /* * "term_getline(buf, row)" function */ void f_term_getline(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getline()"); term_T *term; int row; rettv->v_type = VAR_STRING; if (buf == NULL) return; term = buf->b_term; row = get_row_number(&argvars[1], term); if (term->tl_vterm == NULL) { linenr_T lnum = row + term->tl_scrollback_scrolled + 1; /* vterm is finished, get the text from the buffer */ if (lnum > 0 && lnum <= buf->b_ml.ml_line_count) rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE)); } else { VTermScreen *screen = vterm_obtain_screen(term->tl_vterm); VTermRect rect; int len; char_u *p; if (row < 0 || row >= term->tl_rows) return; len = term->tl_cols * MB_MAXBYTES + 1; p = alloc(len); if (p == NULL) return; rettv->vval.v_string = p; rect.start_col = 0; rect.end_col = term->tl_cols; rect.start_row = row; rect.end_row = row + 1; p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL; } } /* * "term_getscrolled(buf)" function */ void f_term_getscrolled(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getscrolled()"); if (buf == NULL) return; rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled; } /* * "term_getsize(buf)" function */ void f_term_getsize(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getsize()"); list_T *l; if (rettv_list_alloc(rettv) == FAIL) return; if (buf == NULL) return; l = rettv->vval.v_list; list_append_number(l, buf->b_term->tl_rows); list_append_number(l, buf->b_term->tl_cols); } /* * "term_setsize(buf, rows, cols)" function */ void f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED) { buf_T *buf = term_get_buf(argvars, "term_setsize()"); term_T *term; varnumber_T rows, cols; if (buf == NULL) { EMSG(_("E955: Not a terminal buffer")); return; } if (buf->b_term->tl_vterm == NULL) return; term = buf->b_term; rows = tv_get_number(&argvars[1]); rows = rows <= 0 ? term->tl_rows : rows; cols = tv_get_number(&argvars[2]); cols = cols <= 0 ? term->tl_cols : cols; vterm_set_size(term->tl_vterm, rows, cols); /* handle_resize() will resize the windows */ /* Get and remember the size we ended up with. Update the pty. */ vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols); term_report_winsize(term, term->tl_rows, term->tl_cols); } /* * "term_getstatus(buf)" function */ void f_term_getstatus(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getstatus()"); term_T *term; char_u val[100]; rettv->v_type = VAR_STRING; if (buf == NULL) return; term = buf->b_term; if (term_job_running(term)) STRCPY(val, "running"); else STRCPY(val, "finished"); if (term->tl_normal_mode) STRCAT(val, ",normal"); rettv->vval.v_string = vim_strsave(val); } /* * "term_gettitle(buf)" function */ void f_term_gettitle(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_gettitle()"); rettv->v_type = VAR_STRING; if (buf == NULL) return; if (buf->b_term->tl_title != NULL) rettv->vval.v_string = vim_strsave(buf->b_term->tl_title); } /* * "term_gettty(buf)" function */ void f_term_gettty(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_gettty()"); char_u *p = NULL; int num = 0; rettv->v_type = VAR_STRING; if (buf == NULL) return; if (argvars[1].v_type != VAR_UNKNOWN) num = tv_get_number(&argvars[1]); switch (num) { case 0: if (buf->b_term->tl_job != NULL) p = buf->b_term->tl_job->jv_tty_out; break; case 1: if (buf->b_term->tl_job != NULL) p = buf->b_term->tl_job->jv_tty_in; break; default: EMSG2(_(e_invarg2), tv_get_string(&argvars[1])); return; } if (p != NULL) rettv->vval.v_string = vim_strsave(p); } /* * "term_list()" function */ void f_term_list(typval_T *argvars UNUSED, typval_T *rettv) { term_T *tp; list_T *l; if (rettv_list_alloc(rettv) == FAIL || first_term == NULL) return; l = rettv->vval.v_list; for (tp = first_term; tp != NULL; tp = tp->tl_next) if (tp != NULL && tp->tl_buffer != NULL) if (list_append_number(l, (varnumber_T)tp->tl_buffer->b_fnum) == FAIL) return; } /* * "term_scrape(buf, row)" function */ void f_term_scrape(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_scrape()"); VTermScreen *screen = NULL; VTermPos pos; list_T *l; term_T *term; char_u *p; sb_line_T *line; if (rettv_list_alloc(rettv) == FAIL) return; if (buf == NULL) return; term = buf->b_term; l = rettv->vval.v_list; pos.row = get_row_number(&argvars[1], term); if (term->tl_vterm != NULL) { screen = vterm_obtain_screen(term->tl_vterm); p = NULL; line = NULL; } else { linenr_T lnum = pos.row + term->tl_scrollback_scrolled; if (lnum < 0 || lnum >= term->tl_scrollback.ga_len) return; p = ml_get_buf(buf, lnum + 1, FALSE); line = (sb_line_T *)term->tl_scrollback.ga_data + lnum; } for (pos.col = 0; pos.col < term->tl_cols; ) { dict_T *dcell; int width; VTermScreenCellAttrs attrs; VTermColor fg, bg; char_u rgb[8]; char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1]; int off = 0; int i; if (screen == NULL) { cellattr_T *cellattr; int len; /* vterm has finished, get the cell from scrollback */ if (pos.col >= line->sb_cols) break; cellattr = line->sb_cells + pos.col; width = cellattr->width; attrs = cellattr->attrs; fg = cellattr->fg; bg = cellattr->bg; len = MB_PTR2LEN(p); mch_memmove(mbs, p, len); mbs[len] = NUL; p += len; } else { VTermScreenCell cell; if (vterm_screen_get_cell(screen, pos, &cell) == 0) break; for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i) { if (cell.chars[i] == 0) break; off += (*utf_char2bytes)((int)cell.chars[i], mbs + off); } mbs[off] = NUL; width = cell.width; attrs = cell.attrs; fg = cell.fg; bg = cell.bg; } dcell = dict_alloc(); if (dcell == NULL) break; list_append_dict(l, dcell); dict_add_string(dcell, "chars", mbs); vim_snprintf((char *)rgb, 8, "#%02x%02x%02x", fg.red, fg.green, fg.blue); dict_add_string(dcell, "fg", rgb); vim_snprintf((char *)rgb, 8, "#%02x%02x%02x", bg.red, bg.green, bg.blue); dict_add_string(dcell, "bg", rgb); dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg)); dict_add_number(dcell, "width", width); ++pos.col; if (width == 2) ++pos.col; } } /* * "term_sendkeys(buf, keys)" function */ void f_term_sendkeys(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_sendkeys()"); char_u *msg; term_T *term; rettv->v_type = VAR_UNKNOWN; if (buf == NULL) return; msg = tv_get_string_chk(&argvars[1]); if (msg == NULL) return; term = buf->b_term; if (term->tl_vterm == NULL) return; while (*msg != NUL) { int c; if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL) { c = TO_SPECIAL(msg[1], msg[2]); msg += 3; } else { c = PTR2CHAR(msg); msg += MB_CPTR2LEN(msg); } send_keys_to_term(term, c, FALSE); } } #if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO) /* * "term_getansicolors(buf)" function */ void f_term_getansicolors(typval_T *argvars, typval_T *rettv) { buf_T *buf = term_get_buf(argvars, "term_getansicolors()"); term_T *term; VTermState *state; VTermColor color; char_u hexbuf[10]; int index; list_T *list; if (rettv_list_alloc(rettv) == FAIL) return; if (buf == NULL) return; term = buf->b_term; if (term->tl_vterm == NULL) return; list = rettv->vval.v_list; state = vterm_obtain_state(term->tl_vterm); for (index = 0; index < 16; index++) { vterm_state_get_palette_color(state, index, &color); sprintf((char *)hexbuf, "#%02x%02x%02x", color.red, color.green, color.blue); if (list_append_string(list, hexbuf, 7) == FAIL) return; } } /* * "term_setansicolors(buf, list)" function */ void f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED) { buf_T *buf = term_get_buf(argvars, "term_setansicolors()"); term_T *term; if (buf == NULL) return; term = buf->b_term; if (term->tl_vterm == NULL) return; if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL) { EMSG(_(e_listreq)); return; } if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL) EMSG(_(e_invarg)); } #endif /* * "term_setrestore(buf, command)" function */ void f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED) { #if defined(FEAT_SESSION) buf_T *buf = term_get_buf(argvars, "term_setrestore()"); term_T *term; char_u *cmd; if (buf == NULL) return; term = buf->b_term; vim_free(term->tl_command); cmd = tv_get_string_chk(&argvars[1]); if (cmd != NULL) term->tl_command = vim_strsave(cmd); else term->tl_command = NULL; #endif } /* * "term_setkill(buf, how)" function */ void f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED) { buf_T *buf = term_get_buf(argvars, "term_setkill()"); term_T *term; char_u *how; if (buf == NULL) return; term = buf->b_term; vim_free(term->tl_kill); how = tv_get_string_chk(&argvars[1]); if (how != NULL) term->tl_kill = vim_strsave(how); else term->tl_kill = NULL; } /* * "term_start(command, options)" function */ void f_term_start(typval_T *argvars, typval_T *rettv) { jobopt_T opt; buf_T *buf; init_job_options(&opt); if (argvars[1].v_type != VAR_UNKNOWN && get_job_options(&argvars[1], &opt, JO_TIMEOUT_ALL + JO_STOPONEXIT + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO, JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN + JO2_CWD + JO2_ENV + JO2_EOF_CHARS + JO2_NORESTORE + JO2_TERM_KILL + JO2_ANSI_COLORS) == FAIL) return; buf = term_start(&argvars[0], NULL, &opt, 0); if (buf != NULL && buf->b_term != NULL) rettv->vval.v_number = buf->b_fnum; } /* * "term_wait" function */ void f_term_wait(typval_T *argvars, typval_T *rettv UNUSED) { buf_T *buf = term_get_buf(argvars, "term_wait()"); if (buf == NULL) return; if (buf->b_term->tl_job == NULL) { ch_log(NULL, "term_wait(): no job to wait for"); return; } if (buf->b_term->tl_job->jv_channel == NULL) /* channel is closed, nothing to do */ return; /* Get the job status, this will detect a job that finished. */ if (!buf->b_term->tl_job->jv_channel->ch_keep_open && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0) { /* The job is dead, keep reading channel I/O until the channel is * closed. buf->b_term may become NULL if the terminal was closed while * waiting. */ ch_log(NULL, "term_wait(): waiting for channel to close"); while (buf->b_term != NULL && !buf->b_term->tl_channel_closed) { mch_check_messages(); parse_queued_messages(); ui_delay(10L, FALSE); if (!buf_valid(buf)) /* If the terminal is closed when the channel is closed the * buffer disappears. */ break; } mch_check_messages(); parse_queued_messages(); } else { long wait = 10L; mch_check_messages(); parse_queued_messages(); /* Wait for some time for any channel I/O. */ if (argvars[1].v_type != VAR_UNKNOWN) wait = tv_get_number(&argvars[1]); ui_delay(wait, TRUE); mch_check_messages(); /* Flushing messages on channels is hopefully sufficient. * TODO: is there a better way? */ parse_queued_messages(); } } /* * Called when a channel has sent all the lines to a terminal. * Send a CTRL-D to mark the end of the text. */ void term_send_eof(channel_T *ch) { term_T *term; for (term = first_term; term != NULL; term = term->tl_next) if (term->tl_job == ch->ch_job) { if (term->tl_eof_chars != NULL) { channel_send(ch, PART_IN, term->tl_eof_chars, (int)STRLEN(term->tl_eof_chars), NULL); channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL); } # ifdef WIN3264 else /* Default: CTRL-D */ channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL); # endif } } job_T * term_getjob(term_T *term) { return term != NULL ? term->tl_job : NULL; } # if defined(WIN3264) || defined(PROTO) /************************************** * 2. MS-Windows implementation. */ # ifndef PROTO #define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul #define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull #define WINPTY_MOUSE_MODE_FORCE 2 void* (*winpty_config_new)(UINT64, void*); void* (*winpty_open)(void*, void*); void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*); BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*); void (*winpty_config_set_mouse_mode)(void*, int); void (*winpty_config_set_initial_size)(void*, int, int); LPCWSTR (*winpty_conin_name)(void*); LPCWSTR (*winpty_conout_name)(void*); LPCWSTR (*winpty_conerr_name)(void*); void (*winpty_free)(void*); void (*winpty_config_free)(void*); void (*winpty_spawn_config_free)(void*); void (*winpty_error_free)(void*); LPCWSTR (*winpty_error_msg)(void*); BOOL (*winpty_set_size)(void*, int, int, void*); HANDLE (*winpty_agent_process)(void*); #define WINPTY_DLL "winpty.dll" static HINSTANCE hWinPtyDLL = NULL; # endif static int dyn_winpty_init(int verbose) { int i; static struct { char *name; FARPROC *ptr; } winpty_entry[] = { {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name}, {"winpty_config_free", (FARPROC*)&winpty_config_free}, {"winpty_config_new", (FARPROC*)&winpty_config_new}, {"winpty_config_set_mouse_mode", (FARPROC*)&winpty_config_set_mouse_mode}, {"winpty_config_set_initial_size", (FARPROC*)&winpty_config_set_initial_size}, {"winpty_conin_name", (FARPROC*)&winpty_conin_name}, {"winpty_conout_name", (FARPROC*)&winpty_conout_name}, {"winpty_error_free", (FARPROC*)&winpty_error_free}, {"winpty_free", (FARPROC*)&winpty_free}, {"winpty_open", (FARPROC*)&winpty_open}, {"winpty_spawn", (FARPROC*)&winpty_spawn}, {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free}, {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new}, {"winpty_error_msg", (FARPROC*)&winpty_error_msg}, {"winpty_set_size", (FARPROC*)&winpty_set_size}, {"winpty_agent_process", (FARPROC*)&winpty_agent_process}, {NULL, NULL} }; /* No need to initialize twice. */ if (hWinPtyDLL) return OK; /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just * winpty.dll. */ if (*p_winptydll != NUL) hWinPtyDLL = vimLoadLib((char *)p_winptydll); if (!hWinPtyDLL) hWinPtyDLL = vimLoadLib(WINPTY_DLL); if (!hWinPtyDLL) { if (verbose) EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL); return FAIL; } for (i = 0; winpty_entry[i].name != NULL && winpty_entry[i].ptr != NULL; ++i) { if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL, winpty_entry[i].name)) == NULL) { if (verbose) EMSG2(_(e_loadfunc), winpty_entry[i].name); return FAIL; } } return OK; } /* * Create a new terminal of "rows" by "cols" cells. * Store a reference in "term". * Return OK or FAIL. */ static int term_and_job_init( term_T *term, typval_T *argvar, char **argv UNUSED, jobopt_T *opt, jobopt_T *orig_opt) { WCHAR *cmd_wchar = NULL; WCHAR *cwd_wchar = NULL; WCHAR *env_wchar = NULL; channel_T *channel = NULL; job_T *job = NULL; DWORD error; HANDLE jo = NULL; HANDLE child_process_handle; HANDLE child_thread_handle; void *winpty_err = NULL; void *spawn_config = NULL; garray_T ga_cmd, ga_env; char_u *cmd = NULL; if (dyn_winpty_init(TRUE) == FAIL) return FAIL; ga_init2(&ga_cmd, (int)sizeof(char*), 20); ga_init2(&ga_env, (int)sizeof(char*), 20); if (argvar->v_type == VAR_STRING) { cmd = argvar->vval.v_string; } else if (argvar->v_type == VAR_LIST) { if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL) goto failed; cmd = ga_cmd.ga_data; } if (cmd == NULL || *cmd == NUL) { EMSG(_(e_invarg)); goto failed; } cmd_wchar = enc_to_utf16(cmd, NULL); ga_clear(&ga_cmd); if (cmd_wchar == NULL) goto failed; if (opt->jo_cwd != NULL) cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL); win32_build_env(opt->jo_env, &ga_env, TRUE); env_wchar = ga_env.ga_data; term->tl_winpty_config = winpty_config_new(0, &winpty_err); if (term->tl_winpty_config == NULL) goto failed; winpty_config_set_mouse_mode(term->tl_winpty_config, WINPTY_MOUSE_MODE_FORCE); winpty_config_set_initial_size(term->tl_winpty_config, term->tl_cols, term->tl_rows); term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err); if (term->tl_winpty == NULL) goto failed; spawn_config = winpty_spawn_config_new( WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN | WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN, NULL, cmd_wchar, cwd_wchar, env_wchar, &winpty_err); if (spawn_config == NULL) goto failed; channel = add_channel(); if (channel == NULL) goto failed; job = job_alloc(); if (job == NULL) goto failed; if (argvar->v_type == VAR_STRING) { int argc; build_argv_from_string(cmd, &job->jv_argv, &argc); } else { int argc; build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc); } if (opt->jo_set & JO_IN_BUF) job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]); if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle, &child_thread_handle, &error, &winpty_err)) goto failed; channel_set_pipes(channel, (sock_T)CreateFileW( winpty_conin_name(term->tl_winpty), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL), (sock_T)CreateFileW( winpty_conout_name(term->tl_winpty), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL), (sock_T)CreateFileW( winpty_conerr_name(term->tl_winpty), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL)); /* Write lines with CR instead of NL. */ channel->ch_write_text_mode = TRUE; jo = CreateJobObject(NULL, NULL); if (jo == NULL) goto failed; if (!AssignProcessToJobObject(jo, child_process_handle)) { /* Failed, switch the way to terminate process with TerminateProcess. */ CloseHandle(jo); jo = NULL; } winpty_spawn_config_free(spawn_config); vim_free(cmd_wchar); vim_free(cwd_wchar); vim_free(env_wchar); create_vterm(term, term->tl_rows, term->tl_cols); #if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) if (opt->jo_set2 & JO2_ANSI_COLORS) set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors); else init_vterm_ansi_colors(term->tl_vterm); #endif channel_set_job(channel, job, opt); job_set_options(job, opt); job->jv_channel = channel; job->jv_proc_info.hProcess = child_process_handle; job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle); job->jv_job_object = jo; job->jv_status = JOB_STARTED; job->jv_tty_in = utf16_to_enc( (short_u*)winpty_conin_name(term->tl_winpty), NULL); job->jv_tty_out = utf16_to_enc( (short_u*)winpty_conout_name(term->tl_winpty), NULL); ++job->jv_refcount; term->tl_job = job; /* Redirecting stdout and stderr doesn't work at the job level. Instead * open the file here and handle it in. opt->jo_io was changed in * setup_job_options(), use the original flags here. */ if (orig_opt->jo_io[PART_OUT] == JIO_FILE) { char_u *fname = opt->jo_io_name[PART_OUT]; ch_log(channel, "Opening output file %s", fname); term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN); if (term->tl_out_fd == NULL) EMSG2(_(e_notopen), fname); } return OK; failed: ga_clear(&ga_cmd); ga_clear(&ga_env); vim_free(cmd_wchar); vim_free(cwd_wchar); if (spawn_config != NULL) winpty_spawn_config_free(spawn_config); if (channel != NULL) channel_clear(channel); if (job != NULL) { job->jv_channel = NULL; job_cleanup(job); } term->tl_job = NULL; if (jo != NULL) CloseHandle(jo); if (term->tl_winpty != NULL) winpty_free(term->tl_winpty); term->tl_winpty = NULL; if (term->tl_winpty_config != NULL) winpty_config_free(term->tl_winpty_config); term->tl_winpty_config = NULL; if (winpty_err != NULL) { char_u *msg = utf16_to_enc( (short_u *)winpty_error_msg(winpty_err), NULL); EMSG(msg); winpty_error_free(winpty_err); } return FAIL; } static int create_pty_only(term_T *term, jobopt_T *options) { HANDLE hPipeIn = INVALID_HANDLE_VALUE; HANDLE hPipeOut = INVALID_HANDLE_VALUE; char in_name[80], out_name[80]; channel_T *channel = NULL; create_vterm(term, term->tl_rows, term->tl_cols); vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d", GetCurrentProcessId(), curbuf->b_fnum); hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_MESSAGE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, NMPWAIT_NOWAIT, NULL); if (hPipeIn == INVALID_HANDLE_VALUE) goto failed; vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d", GetCurrentProcessId(), curbuf->b_fnum); hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND, PIPE_TYPE_MESSAGE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, 0, NULL); if (hPipeOut == INVALID_HANDLE_VALUE) goto failed; ConnectNamedPipe(hPipeIn, NULL); ConnectNamedPipe(hPipeOut, NULL); term->tl_job = job_alloc(); if (term->tl_job == NULL) goto failed; ++term->tl_job->jv_refcount; /* behave like the job is already finished */ term->tl_job->jv_status = JOB_FINISHED; channel = add_channel(); if (channel == NULL) goto failed; term->tl_job->jv_channel = channel; channel->ch_keep_open = TRUE; channel->ch_named_pipe = TRUE; channel_set_pipes(channel, (sock_T)hPipeIn, (sock_T)hPipeOut, (sock_T)hPipeOut); channel_set_job(channel, term->tl_job, options); term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name); term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name); return OK; failed: if (hPipeIn != NULL) CloseHandle(hPipeIn); if (hPipeOut != NULL) CloseHandle(hPipeOut); return FAIL; } /* * Free the terminal emulator part of "term". */ static void term_free_vterm(term_T *term) { if (term->tl_winpty != NULL) winpty_free(term->tl_winpty); term->tl_winpty = NULL; if (term->tl_winpty_config != NULL) winpty_config_free(term->tl_winpty_config); term->tl_winpty_config = NULL; if (term->tl_vterm != NULL) vterm_free(term->tl_vterm); term->tl_vterm = NULL; } /* * Report the size to the terminal. */ static void term_report_winsize(term_T *term, int rows, int cols) { if (term->tl_winpty) winpty_set_size(term->tl_winpty, cols, rows, NULL); } int terminal_enabled(void) { return dyn_winpty_init(FALSE) == OK; } # else /************************************** * 3. Unix-like implementation. */ /* * Create a new terminal of "rows" by "cols" cells. * Start job for "cmd". * Store the pointers in "term". * When "argv" is not NULL then "argvar" is not used. * Return OK or FAIL. */ static int term_and_job_init( term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt UNUSED) { create_vterm(term, term->tl_rows, term->tl_cols); #if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) if (opt->jo_set2 & JO2_ANSI_COLORS) set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors); else init_vterm_ansi_colors(term->tl_vterm); #endif /* This may change a string in "argvar". */ term->tl_job = job_start(argvar, argv, opt, TRUE); if (term->tl_job != NULL) ++term->tl_job->jv_refcount; return term->tl_job != NULL && term->tl_job->jv_channel != NULL && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL; } static int create_pty_only(term_T *term, jobopt_T *opt) { create_vterm(term, term->tl_rows, term->tl_cols); term->tl_job = job_alloc(); if (term->tl_job == NULL) return FAIL; ++term->tl_job->jv_refcount; /* behave like the job is already finished */ term->tl_job->jv_status = JOB_FINISHED; return mch_create_pty_channel(term->tl_job, opt); } /* * Free the terminal emulator part of "term". */ static void term_free_vterm(term_T *term) { if (term->tl_vterm != NULL) vterm_free(term->tl_vterm); term->tl_vterm = NULL; } /* * Report the size to the terminal. */ static void term_report_winsize(term_T *term, int rows, int cols) { /* Use an ioctl() to report the new window size to the job. */ if (term->tl_job != NULL && term->tl_job->jv_channel != NULL) { int fd = -1; int part; for (part = PART_OUT; part < PART_COUNT; ++part) { fd = term->tl_job->jv_channel->ch_part[part].ch_fd; if (isatty(fd)) break; } if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK) mch_signal_job(term->tl_job, (char_u *)"winch"); } } # endif #endif /* FEAT_TERMINAL */
./CrossVul/dataset_final_sorted/CWE-476/c/bad_528_3
crossvul-cpp_data_good_4849_2
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "jasper/jas_types.h" #include "jasper/jas_math.h" #include "jasper/jas_tvp.h" #include "jasper/jas_malloc.h" #include "jasper/jas_debug.h" #include "jpc_fix.h" #include "jpc_dec.h" #include "jpc_cs.h" #include "jpc_mct.h" #include "jpc_t2dec.h" #include "jpc_t1dec.h" #include "jpc_math.h" /******************************************************************************\ * \******************************************************************************/ #define JPC_MHSOC 0x0001 /* In the main header, expecting a SOC marker segment. */ #define JPC_MHSIZ 0x0002 /* In the main header, expecting a SIZ marker segment. */ #define JPC_MH 0x0004 /* In the main header, expecting "other" marker segments. */ #define JPC_TPHSOT 0x0008 /* In a tile-part header, expecting a SOT marker segment. */ #define JPC_TPH 0x0010 /* In a tile-part header, expecting "other" marker segments. */ #define JPC_MT 0x0020 /* In the main trailer. */ typedef struct { uint_fast16_t id; /* The marker segment type. */ int validstates; /* The states in which this type of marker segment can be validly encountered. */ int (*action)(jpc_dec_t *dec, jpc_ms_t *ms); /* The action to take upon encountering this type of marker segment. */ } jpc_dec_mstabent_t; /******************************************************************************\ * \******************************************************************************/ /* COD/COC parameters have been specified. */ #define JPC_CSET 0x0001 /* QCD/QCC parameters have been specified. */ #define JPC_QSET 0x0002 /* COD/COC parameters set from a COC marker segment. */ #define JPC_COC 0x0004 /* QCD/QCC parameters set from a QCC marker segment. */ #define JPC_QCC 0x0008 /******************************************************************************\ * Local function prototypes. \******************************************************************************/ static int jpc_dec_dump(jpc_dec_t *dec, FILE *out); jpc_ppxstab_t *jpc_ppxstab_create(void); void jpc_ppxstab_destroy(jpc_ppxstab_t *tab); int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents); int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent); jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab); int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab); jpc_ppxstabent_t *jpc_ppxstabent_create(void); void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent); int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist); jpc_streamlist_t *jpc_streamlist_create(void); int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, jas_stream_t *stream); jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno); void jpc_streamlist_destroy(jpc_streamlist_t *streamlist); jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno); static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp); static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps); static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp); static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp); static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod); static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc); static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_coxcp_t *compparms, int flags); static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd); static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc); static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_qcxcp_t *compparms, int flags); static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn); static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp); static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp); static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset); static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc); static int jpc_dec_decode(jpc_dec_t *dec); static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in); static void jpc_dec_destroy(jpc_dec_t *dec); static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize); static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps); static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits); static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts); static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id); /******************************************************************************\ * Global data. \******************************************************************************/ jpc_dec_mstabent_t jpc_dec_mstab[] = { {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc}, {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot}, {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod}, {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc}, {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz}, {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod}, {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc}, {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn}, {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd}, {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc}, {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc}, {JPC_MS_TLM, JPC_MH, 0}, {JPC_MS_PLM, JPC_MH, 0}, {JPC_MS_PLT, JPC_TPH, 0}, {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm}, {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt}, {JPC_MS_SOP, 0, 0}, {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg}, {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com}, {0, JPC_MH | JPC_TPH, jpc_dec_process_unk} }; /******************************************************************************\ * The main entry point for the JPEG-2000 decoder. \******************************************************************************/ jas_image_t *jpc_decode(jas_stream_t *in, char *optstr) { jpc_dec_importopts_t opts; jpc_dec_t *dec; jas_image_t *image; dec = 0; if (jpc_dec_parseopts(optstr, &opts)) { goto error; } jpc_initluts(); if (!(dec = jpc_dec_create(&opts, in))) { goto error; } /* Do most of the work. */ if (jpc_dec_decode(dec)) { goto error; } if (jas_image_numcmpts(dec->image) >= 3) { jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(dec->image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(dec->image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(dec->image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(dec->image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Save the return value. */ image = dec->image; /* Stop the image from being discarded. */ dec->image = 0; /* Destroy decoder. */ jpc_dec_destroy(dec); return image; error: if (dec) { jpc_dec_destroy(dec); } return 0; } typedef enum { OPT_MAXLYRS, OPT_MAXPKTS, OPT_DEBUG } optid_t; jas_taginfo_t decopts[] = { {OPT_MAXLYRS, "maxlyrs"}, {OPT_MAXPKTS, "maxpkts"}, {OPT_DEBUG, "debug"}, {-1, 0} }; static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts) { jas_tvparser_t *tvp; opts->debug = 0; opts->maxlyrs = JPC_MAXLYRS; opts->maxpkts = -1; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { return -1; } while (!jas_tvparser_next(tvp)) { switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts, jas_tvparser_gettag(tvp)))->id) { case OPT_MAXLYRS: opts->maxlyrs = atoi(jas_tvparser_getval(tvp)); break; case OPT_DEBUG: opts->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_MAXPKTS: opts->maxpkts = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); return 0; } /******************************************************************************\ * Code for table-driven code stream decoder. \******************************************************************************/ static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id) { jpc_dec_mstabent_t *mstabent; for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) { if (mstabent->id == id) { break; } } return mstabent; } static int jpc_dec_decode(jpc_dec_t *dec) { jpc_ms_t *ms; jpc_dec_mstabent_t *mstabent; int ret; jpc_cstate_t *cstate; if (!(cstate = jpc_cstate_create())) { return -1; } dec->cstate = cstate; /* Initially, we should expect to encounter a SOC marker segment. */ dec->state = JPC_MHSOC; for (;;) { /* Get the next marker segment in the code stream. */ if (!(ms = jpc_getms(dec->in, cstate))) { jas_eprintf("cannot get marker segment\n"); return -1; } mstabent = jpc_dec_mstab_lookup(ms->id); assert(mstabent); /* Ensure that this type of marker segment is permitted at this point in the code stream. */ if (!(dec->state & mstabent->validstates)) { jas_eprintf("unexpected marker segment type\n"); jpc_ms_destroy(ms); return -1; } /* Process the marker segment. */ if (mstabent->action) { ret = (*mstabent->action)(dec, ms); } else { /* No explicit action is required. */ ret = 0; } /* Destroy the marker segment. */ jpc_ms_destroy(ms); if (ret < 0) { return -1; } else if (ret > 0) { break; } } return 0; } static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms) { int cmptno; jpc_dec_cmpt_t *cmpt; jpc_crg_t *crg; crg = &ms->parms.crg; for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno, ++cmpt) { /* Ignore the information in the CRG marker segment for now. This information serves no useful purpose for decoding anyhow. Some other parts of the code need to be changed if these lines are uncommented. cmpt->hsubstep = crg->comps[cmptno].hoff; cmpt->vsubstep = crg->comps[cmptno].voff; */ } return 0; } static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate warnings about unused variables. */ ms = 0; /* We should expect to encounter a SIZ marker segment next. */ dec->state = JPC_MHSIZ; return 0; } static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; jpc_sot_t *sot = &ms->parms.sot; jas_image_cmptparm_t *compinfos; jas_image_cmptparm_t *compinfo; jpc_dec_cmpt_t *cmpt; int cmptno; if (dec->state == JPC_MH) { if (!(compinfos = jas_alloc2(dec->numcomps, sizeof(jas_image_cmptparm_t)))) { abort(); } for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos; cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) { compinfo->tlx = 0; compinfo->tly = 0; compinfo->prec = cmpt->prec; compinfo->sgnd = cmpt->sgnd; compinfo->width = cmpt->width; compinfo->height = cmpt->height; compinfo->hstep = cmpt->hstep; compinfo->vstep = cmpt->vstep; } if (!(dec->image = jas_image_create(dec->numcomps, compinfos, JAS_CLRSPC_UNKNOWN))) { jas_free(compinfos); return -1; } jas_free(compinfos); /* Is the packet header information stored in PPM marker segments in the main header? */ if (dec->ppmstab) { /* Convert the PPM marker segment data into a collection of streams (one stream per tile-part). */ if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) { abort(); } jpc_ppxstab_destroy(dec->ppmstab); dec->ppmstab = 0; } } if (sot->len > 0) { dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len - 4 + sot->len; } else { dec->curtileendoff = 0; } if (JAS_CAST(int, sot->tileno) >= dec->numtiles) { jas_eprintf("invalid tile number in SOT marker segment\n"); return -1; } /* Set the current tile. */ dec->curtile = &dec->tiles[sot->tileno]; tile = dec->curtile; /* Ensure that this is the expected part number. */ if (sot->partno != tile->partno) { return -1; } if (tile->numparts > 0 && sot->partno >= tile->numparts) { return -1; } if (!tile->numparts && sot->numparts > 0) { tile->numparts = sot->numparts; } tile->pptstab = 0; switch (tile->state) { case JPC_TILE_INIT: /* This is the first tile-part for this tile. */ tile->state = JPC_TILE_ACTIVE; assert(!tile->cp); if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) { return -1; } jpc_dec_cp_resetflags(dec->cp); break; default: if (sot->numparts == sot->partno - 1) { tile->state = JPC_TILE_ACTIVELAST; } break; } /* Note: We do not increment the expected tile-part number until all processing for this tile-part is complete. */ /* We should expect to encounter other tile-part header marker segments next. */ dec->state = JPC_TPH; return 0; } static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; int pos; /* Eliminate compiler warnings about unused variables. */ ms = 0; if (!(tile = dec->curtile)) { return -1; } if (!tile->partno) { if (!jpc_dec_cp_isvalid(tile->cp)) { return -1; } jpc_dec_cp_prepare(tile->cp); if (jpc_dec_tileinit(dec, tile)) { return -1; } } /* Are packet headers stored in the main header or tile-part header? */ if (dec->pkthdrstreams) { /* Get the stream containing the packet header data for this tile-part. */ if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) { return -1; } } if (tile->pptstab) { if (!tile->pkthdrstream) { if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) { return -1; } } pos = jas_stream_tell(tile->pkthdrstream); jas_stream_seek(tile->pkthdrstream, 0, SEEK_END); if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) { return -1; } jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET); jpc_ppxstab_destroy(tile->pptstab); tile->pptstab = 0; } if (jas_getdbglevel() >= 10) { jpc_dec_dump(dec, stderr); } if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream : dec->in, dec->in)) { jas_eprintf("jpc_dec_decodepkts failed\n"); return -1; } /* Gobble any unconsumed tile data. */ if (dec->curtileendoff > 0) { long curoff; uint_fast32_t n; curoff = jas_stream_getrwcount(dec->in); if (curoff < dec->curtileendoff) { n = dec->curtileendoff - curoff; jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n", (unsigned long) n); while (n-- > 0) { if (jas_stream_getc(dec->in) == EOF) { jas_eprintf("read error\n"); return -1; } } } else if (curoff > dec->curtileendoff) { jas_eprintf("warning: not enough tile data (%lu bytes)\n", (unsigned long) curoff - dec->curtileendoff); } } if (tile->numparts > 0 && tile->partno == tile->numparts - 1) { if (jpc_dec_tiledecode(dec, tile)) { return -1; } jpc_dec_tilefini(dec, tile); } dec->curtile = 0; /* Increment the expected tile-part number. */ ++tile->partno; /* We should expect to encounter a SOT marker segment next. */ dec->state = JPC_TPHSOT; return 0; } static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int rlvlno; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; jpc_dec_prc_t *prc; int bndno; jpc_tsfb_band_t *bnd; int bandno; jpc_dec_ccp_t *ccp; int prccnt; jpc_dec_cblk_t *cblk; int cblkcnt; uint_fast32_t tlprcxstart; uint_fast32_t tlprcystart; uint_fast32_t brprcxend; uint_fast32_t brprcyend; uint_fast32_t tlcbgxstart; uint_fast32_t tlcbgystart; uint_fast32_t brcbgxend; uint_fast32_t brcbgyend; uint_fast32_t cbgxstart; uint_fast32_t cbgystart; uint_fast32_t cbgxend; uint_fast32_t cbgyend; uint_fast32_t tlcblkxstart; uint_fast32_t tlcblkystart; uint_fast32_t brcblkxend; uint_fast32_t brcblkyend; uint_fast32_t cblkxstart; uint_fast32_t cblkystart; uint_fast32_t cblkxend; uint_fast32_t cblkyend; uint_fast32_t tmpxstart; uint_fast32_t tmpystart; uint_fast32_t tmpxend; uint_fast32_t tmpyend; jpc_dec_cp_t *cp; jpc_tsfb_band_t bnds[64]; jpc_pchg_t *pchg; int pchgno; jpc_dec_cmpt_t *cmpt; cp = tile->cp; tile->realmode = 0; if (cp->mctid == JPC_MCT_ICT) { tile->realmode = 1; } for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { ccp = &tile->cp->ccps[compno]; if (ccp->qmfbid == JPC_COX_INS) { tile->realmode = 1; } tcomp->numrlvls = ccp->numrlvls; if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls, sizeof(jpc_dec_rlvl_t)))) { return -1; } if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, cmpt->vstep)))) { return -1; } if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, tcomp->numrlvls - 1))) { return -1; } { jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds); } for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { rlvl->bands = 0; rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, tcomp->numrlvls - 1 - rlvlno); rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, tcomp->numrlvls - 1 - rlvlno); rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, tcomp->numrlvls - 1 - rlvlno); rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, tcomp->numrlvls - 1 - rlvlno); rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, rlvl->prcheightexpn) << rlvl->prcheightexpn; brprcxend = JPC_CEILDIVPOW2(rlvl->xend, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; brprcyend = JPC_CEILDIVPOW2(rlvl->yend, rlvl->prcheightexpn) << rlvl->prcheightexpn; rlvl->numhprcs = (brprcxend - tlprcxstart) >> rlvl->prcwidthexpn; rlvl->numvprcs = (brprcyend - tlprcystart) >> rlvl->prcheightexpn; rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { rlvl->bands = 0; rlvl->numprcs = 0; rlvl->numhprcs = 0; rlvl->numvprcs = 0; continue; } if (!rlvlno) { tlcbgxstart = tlprcxstart; tlcbgystart = tlprcystart; brcbgxend = brprcxend; brcbgyend = brprcyend; rlvl->cbgwidthexpn = rlvl->prcwidthexpn; rlvl->cbgheightexpn = rlvl->prcheightexpn; } else { tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; } rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, rlvl->cbgwidthexpn); rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, rlvl->cbgheightexpn); rlvl->numbands = (!rlvlno) ? 1 : 3; if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_dec_band_t)))) { return -1; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); bnd = &bnds[bndno]; band->orient = bnd->orient; band->stepsize = ccp->stepsizes[bndno]; band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, tcomp->numrlvls - 1, rlvlno, band->orient); band->absstepsize = jpc_calcabsstepsize(band->stepsize, cmpt->prec + band->analgain); band->numbps = ccp->numguardbits + JPC_QCX_GETEXPN(band->stepsize) - 1; band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? (JPC_PREC - 1 - band->numbps) : ccp->roishift; band->data = 0; band->prcs = 0; if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { continue; } if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend); jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); assert(rlvl->numprcs); if (!(band->prcs = jas_alloc2(rlvl->numprcs, sizeof(jpc_dec_prc_t)))) { return -1; } /************************************************/ cbgxstart = tlcbgxstart; cbgystart = tlcbgystart; for (prccnt = rlvl->numprcs, prc = band->prcs; prccnt > 0; --prccnt, ++prc) { cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data))); prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data))); prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data))); prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data))); if (prc->xend > prc->xstart && prc->yend > prc->ystart) { tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; brcblkxend = JPC_CEILDIVPOW2(prc->xend, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; brcblkyend = JPC_CEILDIVPOW2(prc->yend, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; prc->numhcblks = (brcblkxend - tlcblkxstart) >> rlvl->cblkwidthexpn; prc->numvcblks = (brcblkyend - tlcblkystart) >> rlvl->cblkheightexpn; prc->numcblks = prc->numhcblks * prc->numvcblks; assert(prc->numcblks > 0); if (!(prc->incltagtree = jpc_tagtree_create( prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->numimsbstagtree = jpc_tagtree_create( prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_dec_cblk_t)))) { return -1; } cblkxstart = cbgxstart; cblkystart = cbgystart; for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) { cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); tmpxstart = JAS_MAX(cblkxstart, prc->xstart); tmpystart = JAS_MAX(cblkystart, prc->ystart); tmpxend = JAS_MIN(cblkxend, prc->xend); tmpyend = JAS_MIN(cblkyend, prc->yend); if (tmpxend > tmpxstart && tmpyend > tmpystart) { cblk->firstpassno = -1; cblk->mqdec = 0; cblk->nulldec = 0; cblk->flags = 0; cblk->numpasses = 0; cblk->segs.head = 0; cblk->segs.tail = 0; cblk->curseg = 0; cblk->numimsbs = 0; cblk->numlenbits = 3; cblk->flags = 0; if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend); ++cblk; --cblkcnt; } cblkxstart += 1 << rlvl->cblkwidthexpn; if (cblkxstart >= cbgxend) { cblkxstart = cbgxstart; cblkystart += 1 << rlvl->cblkheightexpn; } } } else { prc->cblks = 0; prc->incltagtree = 0; prc->numimsbstagtree = 0; } cbgxstart += 1 << rlvl->cbgwidthexpn; if (cbgxstart >= brcbgxend) { cbgxstart = tlcbgxstart; cbgystart += 1 << rlvl->cbgheightexpn; } } /********************************************/ } } } if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { return -1; } for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); ++pchgno) { pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); assert(pchg); jpc_pi_addpchg(tile->pi, pchg); } jpc_pi_init(tile->pi); return 0; } static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int bandno; int rlvlno; jpc_dec_band_t *band; jpc_dec_rlvl_t *rlvl; int prcno; jpc_dec_prc_t *prc; jpc_dec_seg_t *seg; jpc_dec_cblk_t *cblk; int cblkno; if (tile->tcomps) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (band->prcs) { for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { if (!prc->cblks) { continue; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { while (cblk->segs.head) { seg = cblk->segs.head; jpc_seglist_remove(&cblk->segs, seg); jpc_seg_destroy(seg); } jas_matrix_destroy(cblk->data); if (cblk->mqdec) { jpc_mqdec_destroy(cblk->mqdec); } if (cblk->nulldec) { jpc_bitstream_close(cblk->nulldec); } if (cblk->flags) { jas_matrix_destroy(cblk->flags); } } if (prc->incltagtree) { jpc_tagtree_destroy(prc->incltagtree); } if (prc->numimsbstagtree) { jpc_tagtree_destroy(prc->numimsbstagtree); } if (prc->cblks) { jas_free(prc->cblks); } } } if (band->data) { jas_matrix_destroy(band->data); } if (band->prcs) { jas_free(band->prcs); } } if (rlvl->bands) { jas_free(rlvl->bands); } } if (tcomp->rlvls) { jas_free(tcomp->rlvls); } if (tcomp->data) { jas_matrix_destroy(tcomp->data); } if (tcomp->tsfb) { jpc_tsfb_destroy(tcomp->tsfb); } } } if (tile->cp) { jpc_dec_cp_destroy(tile->cp); //tile->cp = 0; } if (tile->tcomps) { jas_free(tile->tcomps); //tile->tcomps = 0; } if (tile->pi) { jpc_pi_destroy(tile->pi); //tile->pi = 0; } if (tile->pkthdrstream) { jas_stream_close(tile->pkthdrstream); //tile->pkthdrstream = 0; } if (tile->pptstab) { jpc_ppxstab_destroy(tile->pptstab); //tile->pptstab = 0; } tile->state = JPC_TILE_DONE; return 0; } static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile) { int i; int j; jpc_dec_tcomp_t *tcomp; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; int compno; int rlvlno; int bandno; int adjust; int v; jpc_dec_ccp_t *ccp; jpc_dec_cmpt_t *cmpt; if (jpc_dec_decodecblks(dec, tile)) { jas_eprintf("jpc_dec_decodecblks failed\n"); return -1; } /* Perform dequantization. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } jpc_undo_roi(band->data, band->roishift, ccp->roishift - band->roishift, band->numbps); if (tile->realmode) { jas_matrix_asl(band->data, JPC_FIX_FRACBITS); jpc_dequantize(band->data, band->absstepsize); } } } } /* Apply an inverse wavelet transform if necessary. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data); } /* Apply an inverse intercomponent transform if necessary. */ switch (tile->cp->mctid) { case JPC_MCT_RCT: if (dec->numcomps < 3) { jas_eprintf("RCT requires at least three components\n"); return -1; } jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; case JPC_MCT_ICT: if (dec->numcomps < 3) { jas_eprintf("ICT requires at least three components\n"); return -1; } jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; } /* Perform rounding and convert to integer values. */ if (tile->realmode) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { v = jas_matrix_get(tcomp->data, i, j); v = jpc_fix_round(v); jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v)); } } } } /* Perform level shift. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1)); for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { *jas_matrix_getref(tcomp->data, i, j) += adjust; } } } /* Perform clipping. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { jpc_fix_t mn; jpc_fix_t mx; mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0); mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 << cmpt->prec) - 1); jas_matrix_clip(tcomp->data, mn, mx); } /* XXX need to free tsfb struct */ /* Write the data for each component of the image. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { if (jas_image_writecmpt(dec->image, compno, tcomp->xstart - JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart - JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols( tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) { jas_eprintf("write component failed\n"); return -1; } } return 0; } static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms) { int tileno; jpc_dec_tile_t *tile; /* Eliminate compiler warnings about unused variables. */ ms = 0; for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { if (tile->state == JPC_TILE_ACTIVE) { if (jpc_dec_tiledecode(dec, tile)) { return -1; } } /* If the tile has not yet been finalized, finalize it. */ // OLD CODE: jpc_dec_tilefini(dec, tile); if (tile->state != JPC_TILE_DONE) { jpc_dec_tilefini(dec, tile); } } /* We are done processing the code stream. */ dec->state = JPC_MT; return 1; } static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); dec->numtiles = dec->numhtiles * dec->numvtiles; JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; } static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_cod_t *cod = &ms->parms.cod; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromcod(dec->cp, cod); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno != 0) { return -1; } jpc_dec_cp_setfromcod(tile->cp, cod); break; } return 0; } static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_coc_t *coc = &ms->parms.coc; jpc_dec_tile_t *tile; if (JAS_CAST(int, coc->compno) >= dec->numcomps) { jas_eprintf("invalid component number in COC marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromcoc(dec->cp, coc); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromcoc(tile->cp, coc); break; } return 0; } static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_rgn_t *rgn = &ms->parms.rgn; jpc_dec_tile_t *tile; if (JAS_CAST(int, rgn->compno) >= dec->numcomps) { jas_eprintf("invalid component number in RGN marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromrgn(dec->cp, rgn); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromrgn(tile->cp, rgn); break; } return 0; } static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_qcd_t *qcd = &ms->parms.qcd; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromqcd(dec->cp, qcd); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromqcd(tile->cp, qcd); break; } return 0; } static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_qcc_t *qcc = &ms->parms.qcc; jpc_dec_tile_t *tile; if (JAS_CAST(int, qcc->compno) >= dec->numcomps) { jas_eprintf("invalid component number in QCC marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromqcc(dec->cp, qcc); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromqcc(tile->cp, qcc); break; } return 0; } static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_poc_t *poc = &ms->parms.poc; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) { return -1; } break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (!tile->partno) { if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) { return -1; } } else { jpc_pi_addpchgfrompoc(tile->pi, poc); } break; } return 0; } static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_ppm_t *ppm = &ms->parms.ppm; jpc_ppxstabent_t *ppmstabent; if (!dec->ppmstab) { if (!(dec->ppmstab = jpc_ppxstab_create())) { return -1; } } if (!(ppmstabent = jpc_ppxstabent_create())) { return -1; } ppmstabent->ind = ppm->ind; ppmstabent->data = ppm->data; ppm->data = 0; ppmstabent->len = ppm->len; if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) { return -1; } return 0; } static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_ppt_t *ppt = &ms->parms.ppt; jpc_dec_tile_t *tile; jpc_ppxstabent_t *pptstabent; tile = dec->curtile; if (!tile->pptstab) { if (!(tile->pptstab = jpc_ppxstab_create())) { return -1; } } if (!(pptstabent = jpc_ppxstabent_create())) { return -1; } pptstabent->ind = ppt->ind; pptstabent->data = ppt->data; ppt->data = 0; pptstabent->len = ppt->len; if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) { return -1; } return 0; } static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate compiler warnings about unused variables. */ dec = 0; ms = 0; return 0; } static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate compiler warnings about unused variables. */ dec = 0; jas_eprintf("warning: ignoring unknown marker segment\n"); jpc_ms_dump(ms, stderr); return 0; } /******************************************************************************\ * \******************************************************************************/ static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps) { jpc_dec_cp_t *cp; jpc_dec_ccp_t *ccp; int compno; if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) { return 0; } cp->flags = 0; cp->numcomps = numcomps; cp->prgord = 0; cp->numlyrs = 0; cp->mctid = 0; cp->csty = 0; if (!(cp->ccps = jas_alloc2(cp->numcomps, sizeof(jpc_dec_ccp_t)))) { goto error; } if (!(cp->pchglist = jpc_pchglist_create())) { goto error; } for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; ccp->numrlvls = 0; ccp->cblkwidthexpn = 0; ccp->cblkheightexpn = 0; ccp->qmfbid = 0; ccp->numstepsizes = 0; ccp->numguardbits = 0; ccp->roishift = 0; ccp->cblkctx = 0; } return cp; error: if (cp) { jpc_dec_cp_destroy(cp); } return 0; } static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp) { jpc_dec_cp_t *newcp; jpc_dec_ccp_t *newccp; jpc_dec_ccp_t *ccp; int compno; if (!(newcp = jpc_dec_cp_create(cp->numcomps))) { return 0; } newcp->flags = cp->flags; newcp->prgord = cp->prgord; newcp->numlyrs = cp->numlyrs; newcp->mctid = cp->mctid; newcp->csty = cp->csty; jpc_pchglist_destroy(newcp->pchglist); newcp->pchglist = 0; if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) { jas_free(newcp); return 0; } for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++newccp, ++ccp) { *newccp = *ccp; } return newcp; } static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp) { int compno; jpc_dec_ccp_t *ccp; cp->flags &= (JPC_CSET | JPC_QSET); for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; } } static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp) { if (cp->ccps) { jas_free(cp->ccps); } if (cp->pchglist) { jpc_pchglist_destroy(cp->pchglist); } jas_free(cp); } static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp) { uint_fast16_t compcnt; jpc_dec_ccp_t *ccp; if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) { return 0; } for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt, ++ccp) { /* Is there enough step sizes for the number of bands? */ if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 * ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT && ccp->numstepsizes != 1)) { return 0; } } return 1; } static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp) { jpc_dec_ccp_t *ccp; int compno; int i; for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { if (!(ccp->csty & JPC_COX_PRT)) { for (i = 0; i < JPC_MAXRLVLS; ++i) { ccp->prcwidthexpns[i] = 15; ccp->prcheightexpns[i] = 15; } } if (ccp->qsty == JPC_QCX_SIQNT) { calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes); } } return 0; } static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod) { jpc_dec_ccp_t *ccp; int compno; cp->flags |= JPC_CSET; cp->prgord = cod->prg; if (cod->mctrans) { cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT); } else { cp->mctid = JPC_MCT_NONE; } cp->numlyrs = cod->numlyrs; cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH); for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0); } cp->flags |= JPC_CSET; return 0; } static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc) { jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC); return 0; } static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_coxcp_t *compparms, int flags) { int rlvlno; /* Eliminate compiler warnings about unused variables. */ cp = 0; if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) { ccp->numrlvls = compparms->numdlvls + 1; ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN( compparms->cblkwidthval); ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN( compparms->cblkheightval); ccp->qmfbid = compparms->qmfbid; ccp->cblkctx = compparms->cblksty; ccp->csty = compparms->csty & JPC_COX_PRT; for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) { ccp->prcwidthexpns[rlvlno] = compparms->rlvls[rlvlno].parwidthval; ccp->prcheightexpns[rlvlno] = compparms->rlvls[rlvlno].parheightval; } ccp->flags |= flags | JPC_CSET; } return 0; } static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd) { int compno; jpc_dec_ccp_t *ccp; for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0); } cp->flags |= JPC_QSET; return 0; } static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc) { return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC); } static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_qcxcp_t *compparms, int flags) { int bandno; /* Eliminate compiler warnings about unused variables. */ cp = 0; if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) { ccp->flags |= flags | JPC_QSET; for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) { ccp->stepsizes[bandno] = compparms->stepsizes[bandno]; } ccp->numstepsizes = compparms->numstepsizes; ccp->numguardbits = compparms->numguard; ccp->qsty = compparms->qntsty; } return 0; } static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn) { jpc_dec_ccp_t *ccp; ccp = &cp->ccps[rgn->compno]; ccp->roishift = rgn->roishift; return 0; } static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc) { int pchgno; jpc_pchg_t *pchg; for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { return -1; } if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) { return -1; } } return 0; } static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset) { int pchgno; jpc_pchg_t *pchg; if (reset) { while (jpc_pchglist_numpchgs(cp->pchglist) > 0) { pchg = jpc_pchglist_remove(cp->pchglist, 0); jpc_pchg_destroy(pchg); } } for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { return -1; } if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) { return -1; } } return 0; } static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits) { jpc_fix_t absstepsize; int n; absstepsize = jpc_inttofix(1); n = JPC_FIX_FRACBITS - 11; absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) : (JPC_QCX_GETMANT(stepsize) >> (-n)); n = numbits - JPC_QCX_GETEXPN(stepsize); absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n)); return absstepsize; } static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize) { int i; int j; int t; assert(absstepsize >= 0); if (absstepsize == jpc_inttofix(1)) { return; } for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { t = jas_matrix_get(x, i, j); if (t) { t = jpc_fix_mul(t, absstepsize); } else { t = 0; } jas_matrix_set(x, i, j, t); } } } static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) { int i; int j; int thresh; jpc_fix_t val; jpc_fix_t mag; bool warn; uint_fast32_t mask; if (roishift < 0) { /* We could instead return an error here. */ /* I do not think it matters much. */ jas_eprintf("warning: forcing negative ROI shift to zero " "(bitstream is probably corrupt)\n"); roishift = 0; } if (roishift == 0 && bgshift == 0) { return; } thresh = 1 << roishift; warn = false; for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { val = jas_matrix_get(x, i, j); mag = JAS_ABS(val); if (mag >= thresh) { /* We are dealing with ROI data. */ mag >>= roishift; val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } else { /* We are dealing with non-ROI (i.e., background) data. */ mag <<= bgshift; mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1; /* Perform a basic sanity check on the sample value. */ /* Some implementations write garbage in the unused most-significant bit planes introduced by ROI shifting. Here we ensure that any such bits are masked off. */ if (mag & (~mask)) { if (!warn) { jas_eprintf("warning: possibly corrupt code stream\n"); warn = true; } mag &= mask; } val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } } } } static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in) { jpc_dec_t *dec; if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) { return 0; } dec->image = 0; dec->xstart = 0; dec->ystart = 0; dec->xend = 0; dec->yend = 0; dec->tilewidth = 0; dec->tileheight = 0; dec->tilexoff = 0; dec->tileyoff = 0; dec->numhtiles = 0; dec->numvtiles = 0; dec->numtiles = 0; dec->tiles = 0; dec->curtile = 0; dec->numcomps = 0; dec->in = in; dec->cp = 0; dec->maxlyrs = impopts->maxlyrs; dec->maxpkts = impopts->maxpkts; dec->numpkts = 0; dec->ppmseqno = 0; dec->state = 0; dec->cmpts = 0; dec->pkthdrstreams = 0; dec->ppmstab = 0; dec->curtileendoff = 0; return dec; } static void jpc_dec_destroy(jpc_dec_t *dec) { if (dec->cstate) { jpc_cstate_destroy(dec->cstate); } if (dec->pkthdrstreams) { jpc_streamlist_destroy(dec->pkthdrstreams); } if (dec->image) { jas_image_destroy(dec->image); } if (dec->cp) { jpc_dec_cp_destroy(dec->cp); } if (dec->cmpts) { jas_free(dec->cmpts); } if (dec->tiles) { jas_free(dec->tiles); } jas_free(dec); } /******************************************************************************\ * \******************************************************************************/ void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node) { jpc_dec_seg_t *prev; jpc_dec_seg_t *next; prev = ins; node->prev = prev; next = prev ? (prev->next) : 0; node->prev = prev; node->next = next; if (prev) { prev->next = node; } else { list->head = node; } if (next) { next->prev = node; } else { list->tail = node; } } void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg) { jpc_dec_seg_t *prev; jpc_dec_seg_t *next; prev = seg->prev; next = seg->next; if (prev) { prev->next = next; } else { list->head = next; } if (next) { next->prev = prev; } else { list->tail = prev; } seg->prev = 0; seg->next = 0; } jpc_dec_seg_t *jpc_seg_alloc() { jpc_dec_seg_t *seg; if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) { return 0; } seg->prev = 0; seg->next = 0; seg->passno = -1; seg->numpasses = 0; seg->maxpasses = 0; seg->type = JPC_SEG_INVALID; seg->stream = 0; seg->cnt = 0; seg->complete = 0; seg->lyrno = -1; return seg; } void jpc_seg_destroy(jpc_dec_seg_t *seg) { if (seg->stream) { jas_stream_close(seg->stream); } jas_free(seg); } static int jpc_dec_dump(jpc_dec_t *dec, FILE *out) { jpc_dec_tile_t *tile; int tileno; jpc_dec_tcomp_t *tcomp; int compno; jpc_dec_rlvl_t *rlvl; int rlvlno; jpc_dec_band_t *band; int bandno; jpc_dec_prc_t *prc; int prcno; jpc_dec_cblk_t *cblk; int cblkno; for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend, rlvl->xend - rlvl->xstart, rlvl->yend - rlvl->ystart); for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { fprintf(out, "BAND %d\n", bandno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data), jas_seq2d_xend(band->data) - jas_seq2d_xstart(band->data), jas_seq2d_yend(band->data) - jas_seq2d_ystart(band->data)); for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { fprintf(out, "CODE BLOCK GROUP %d\n", prcno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", prc->xstart, prc->ystart, prc->xend, prc->yend, prc->xend - prc->xstart, prc->yend - prc->ystart); for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { fprintf(out, "CODE BLOCK %d\n", cblkno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data), jas_seq2d_xend(cblk->data) - jas_seq2d_xstart(cblk->data), jas_seq2d_yend(cblk->data) - jas_seq2d_ystart(cblk->data)); } } } } } } return 0; } jpc_streamlist_t *jpc_streamlist_create() { jpc_streamlist_t *streamlist; int i; if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) { return 0; } streamlist->numstreams = 0; streamlist->maxstreams = 100; if (!(streamlist->streams = jas_alloc2(streamlist->maxstreams, sizeof(jas_stream_t *)))) { jas_free(streamlist); return 0; } for (i = 0; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } return streamlist; } int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, jas_stream_t *stream) { jas_stream_t **newstreams; int newmaxstreams; int i; /* Grow the array of streams if necessary. */ if (streamlist->numstreams >= streamlist->maxstreams) { newmaxstreams = streamlist->maxstreams + 1024; if (!(newstreams = jas_realloc2(streamlist->streams, (newmaxstreams + 1024), sizeof(jas_stream_t *)))) { return -1; } for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } streamlist->maxstreams = newmaxstreams; streamlist->streams = newstreams; } if (streamno != streamlist->numstreams) { /* Can only handle insertion at start of list. */ return -1; } streamlist->streams[streamno] = stream; ++streamlist->numstreams; return 0; } jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno) { jas_stream_t *stream; int i; if (streamno >= streamlist->numstreams) { abort(); } stream = streamlist->streams[streamno]; for (i = streamno + 1; i < streamlist->numstreams; ++i) { streamlist->streams[i - 1] = streamlist->streams[i]; } --streamlist->numstreams; return stream; } void jpc_streamlist_destroy(jpc_streamlist_t *streamlist) { int streamno; if (streamlist->streams) { for (streamno = 0; streamno < streamlist->numstreams; ++streamno) { jas_stream_close(streamlist->streams[streamno]); } jas_free(streamlist->streams); } jas_free(streamlist); } jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno) { assert(streamno < streamlist->numstreams); return streamlist->streams[streamno]; } int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist) { return streamlist->numstreams; } jpc_ppxstab_t *jpc_ppxstab_create() { jpc_ppxstab_t *tab; if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) { return 0; } tab->numents = 0; tab->maxents = 0; tab->ents = 0; return tab; } void jpc_ppxstab_destroy(jpc_ppxstab_t *tab) { int i; for (i = 0; i < tab->numents; ++i) { jpc_ppxstabent_destroy(tab->ents[i]); } if (tab->ents) { jas_free(tab->ents); } jas_free(tab); } int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents) { jpc_ppxstabent_t **newents; if (tab->maxents < maxents) { newents = (tab->ents) ? jas_realloc2(tab->ents, maxents, sizeof(jpc_ppxstabent_t *)) : jas_alloc2(maxents, sizeof(jpc_ppxstabent_t *)); if (!newents) { return -1; } tab->ents = newents; tab->maxents = maxents; } return 0; } int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent) { int inspt; int i; for (i = 0; i < tab->numents; ++i) { if (tab->ents[i]->ind > ent->ind) { break; } } inspt = i; if (tab->numents >= tab->maxents) { if (jpc_ppxstab_grow(tab, tab->maxents + 128)) { return -1; } } for (i = tab->numents; i > inspt; --i) { tab->ents[i] = tab->ents[i - 1]; } tab->ents[i] = ent; ++tab->numents; return 0; } jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab) { jpc_streamlist_t *streams; uchar *dataptr; uint_fast32_t datacnt; uint_fast32_t tpcnt; jpc_ppxstabent_t *ent; int entno; jas_stream_t *stream; int n; if (!(streams = jpc_streamlist_create())) { goto error; } if (!tab->numents) { return streams; } entno = 0; ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; for (;;) { /* Get the length of the packet header data for the current tile-part. */ if (datacnt < 4) { goto error; } if (!(stream = jas_stream_memopen(0, 0))) { goto error; } if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams), stream)) { goto error; } tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8) | dataptr[3]; datacnt -= 4; dataptr += 4; /* Get the packet header data for the current tile-part. */ while (tpcnt) { if (!datacnt) { if (++entno >= tab->numents) { goto error; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } n = JAS_MIN(tpcnt, datacnt); if (jas_stream_write(stream, dataptr, n) != n) { goto error; } tpcnt -= n; dataptr += n; datacnt -= n; } jas_stream_rewind(stream); if (!datacnt) { if (++entno >= tab->numents) { break; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } } return streams; error: if (streams) { jpc_streamlist_destroy(streams); } return 0; } int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab) { int i; jpc_ppxstabent_t *ent; for (i = 0; i < tab->numents; ++i) { ent = tab->ents[i]; if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) { return -1; } } return 0; } jpc_ppxstabent_t *jpc_ppxstabent_create() { jpc_ppxstabent_t *ent; if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) { return 0; } ent->data = 0; ent->len = 0; ent->ind = 0; return ent; } void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent) { if (ent->data) { jas_free(ent->data); } jas_free(ent); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_4849_2
crossvul-cpp_data_good_5714_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Security * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "security.h" /* 0x36 repeated 40 times */ static const BYTE pad1[40] = { "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" }; /* 0x5C repeated 48 times */ static const BYTE pad2[48] = { "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" }; static const BYTE fips_reverse_table[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff }; static const BYTE fips_oddparity_table[256] = { 0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0b, 0x0b, 0x0d, 0x0d, 0x0e, 0x0e, 0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16, 0x19, 0x19, 0x1a, 0x1a, 0x1c, 0x1c, 0x1f, 0x1f, 0x20, 0x20, 0x23, 0x23, 0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2a, 0x2a, 0x2c, 0x2c, 0x2f, 0x2f, 0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3b, 0x3b, 0x3d, 0x3d, 0x3e, 0x3e, 0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49, 0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f, 0x51, 0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5b, 0x5b, 0x5d, 0x5d, 0x5e, 0x5e, 0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6b, 0x6b, 0x6d, 0x6d, 0x6e, 0x6e, 0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76, 0x79, 0x79, 0x7a, 0x7a, 0x7c, 0x7c, 0x7f, 0x7f, 0x80, 0x80, 0x83, 0x83, 0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8a, 0x8a, 0x8c, 0x8c, 0x8f, 0x8f, 0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9b, 0x9b, 0x9d, 0x9d, 0x9e, 0x9e, 0xa1, 0xa1, 0xa2, 0xa2, 0xa4, 0xa4, 0xa7, 0xa7, 0xa8, 0xa8, 0xab, 0xab, 0xad, 0xad, 0xae, 0xae, 0xb0, 0xb0, 0xb3, 0xb3, 0xb5, 0xb5, 0xb6, 0xb6, 0xb9, 0xb9, 0xba, 0xba, 0xbc, 0xbc, 0xbf, 0xbf, 0xc1, 0xc1, 0xc2, 0xc2, 0xc4, 0xc4, 0xc7, 0xc7, 0xc8, 0xc8, 0xcb, 0xcb, 0xcd, 0xcd, 0xce, 0xce, 0xd0, 0xd0, 0xd3, 0xd3, 0xd5, 0xd5, 0xd6, 0xd6, 0xd9, 0xd9, 0xda, 0xda, 0xdc, 0xdc, 0xdf, 0xdf, 0xe0, 0xe0, 0xe3, 0xe3, 0xe5, 0xe5, 0xe6, 0xe6, 0xe9, 0xe9, 0xea, 0xea, 0xec, 0xec, 0xef, 0xef, 0xf1, 0xf1, 0xf2, 0xf2, 0xf4, 0xf4, 0xf7, 0xf7, 0xf8, 0xf8, 0xfb, 0xfb, 0xfd, 0xfd, 0xfe, 0xfe }; static void security_salted_hash(const BYTE* salt, const BYTE* input, int length, const BYTE* salt1, const BYTE* salt2, BYTE* output) { CryptoMd5 md5; CryptoSha1 sha1; BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; /* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1(Input + Salt + Salt1 + Salt2)) */ /* SHA1_Digest = SHA1(Input + Salt + Salt1 + Salt2) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, input, length); /* Input */ crypto_sha1_update(sha1, salt, 48); /* Salt (48 bytes) */ crypto_sha1_update(sha1, salt1, 32); /* Salt1 (32 bytes) */ crypto_sha1_update(sha1, salt2, 32); /* Salt2 (32 bytes) */ crypto_sha1_final(sha1, sha1_digest); /* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1_Digest) */ md5 = crypto_md5_init(); crypto_md5_update(md5, salt, 48); /* Salt (48 bytes) */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, output); } static void security_premaster_hash(const char* input, int length, const BYTE* premaster_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* PremasterHash(Input) = SaltedHash(PremasterSecret, Input, ClientRandom, ServerRandom) */ security_salted_hash(premaster_secret, (BYTE*)input, length, client_random, server_random, output); } void security_master_secret(const BYTE* premaster_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MasterSecret = PremasterHash('A') + PremasterHash('BB') + PremasterHash('CCC') */ security_premaster_hash("A", 1, premaster_secret, client_random, server_random, &output[0]); security_premaster_hash("BB", 2, premaster_secret, client_random, server_random, &output[16]); security_premaster_hash("CCC", 3, premaster_secret, client_random, server_random, &output[32]); } static void security_master_hash(const char* input, int length, const BYTE* master_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MasterHash(Input) = SaltedHash(MasterSecret, Input, ServerRandom, ClientRandom) */ security_salted_hash(master_secret, (const BYTE*)input, length, server_random, client_random, output); } void security_session_key_blob(const BYTE* master_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MasterHash = MasterHash('A') + MasterHash('BB') + MasterHash('CCC') */ security_master_hash("A", 1, master_secret, client_random, server_random, &output[0]); security_master_hash("BB", 2, master_secret, client_random, server_random, &output[16]); security_master_hash("CCC", 3, master_secret, client_random, server_random, &output[32]); } void security_mac_salt_key(const BYTE* session_key_blob, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MacSaltKey = First128Bits(SessionKeyBlob) */ memcpy(output, session_key_blob, 16); } void security_md5_16_32_32(const BYTE* in0, const BYTE* in1, const BYTE* in2, BYTE* output) { CryptoMd5 md5; md5 = crypto_md5_init(); crypto_md5_update(md5, in0, 16); crypto_md5_update(md5, in1, 32); crypto_md5_update(md5, in2, 32); crypto_md5_final(md5, output); } void security_licensing_encryption_key(const BYTE* session_key_blob, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* LicensingEncryptionKey = MD5(Second128Bits(SessionKeyBlob) + ClientRandom + ServerRandom)) */ security_md5_16_32_32(&session_key_blob[16], client_random, server_random, output); } void security_UINT32_le(BYTE* output, UINT32 value) { output[0] = (value) & 0xFF; output[1] = (value >> 8) & 0xFF; output[2] = (value >> 16) & 0xFF; output[3] = (value >> 24) & 0xFF; } void security_mac_data(const BYTE* mac_salt_key, const BYTE* data, UINT32 length, BYTE* output) { CryptoMd5 md5; CryptoSha1 sha1; BYTE length_le[4]; BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; /* MacData = MD5(MacSaltKey + pad2 + SHA1(MacSaltKey + pad1 + length + data)) */ security_UINT32_le(length_le, length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MacSaltKey + pad1 + length + data) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, mac_salt_key, 16); /* MacSaltKey */ crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */ crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */ crypto_sha1_update(sha1, data, length); /* data */ crypto_sha1_final(sha1, sha1_digest); /* MacData = MD5(MacSaltKey + pad2 + SHA1_Digest) */ md5 = crypto_md5_init(); crypto_md5_update(md5, mac_salt_key, 16); /* MacSaltKey */ crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, output); } void security_mac_signature(rdpRdp *rdp, const BYTE* data, UINT32 length, BYTE* output) { CryptoMd5 md5; CryptoSha1 sha1; BYTE length_le[4]; BYTE md5_digest[CRYPTO_MD5_DIGEST_LENGTH]; BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; security_UINT32_le(length_le, length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */ crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */ crypto_sha1_update(sha1, data, length); /* data */ crypto_sha1_final(sha1, sha1_digest); /* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */ md5 = crypto_md5_init(); crypto_md5_update(md5, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, md5_digest); memcpy(output, md5_digest, 8); } void security_salted_mac_signature(rdpRdp *rdp, const BYTE* data, UINT32 length, BOOL encryption, BYTE* output) { CryptoMd5 md5; CryptoSha1 sha1; BYTE length_le[4]; BYTE use_count_le[4]; BYTE md5_digest[CRYPTO_MD5_DIGEST_LENGTH]; BYTE sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; security_UINT32_le(length_le, length); /* length must be little-endian */ if (encryption) { security_UINT32_le(use_count_le, rdp->encrypt_checksum_use_count); } else { /* * We calculate checksum on plain text, so we must have already * decrypt it, which means decrypt_checksum_use_count is off by one. */ security_UINT32_le(use_count_le, rdp->decrypt_checksum_use_count - 1); } /* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */ crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */ crypto_sha1_update(sha1, data, length); /* data */ crypto_sha1_update(sha1, use_count_le, sizeof(use_count_le)); /* encryptionCount */ crypto_sha1_final(sha1, sha1_digest); /* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */ md5 = crypto_md5_init(); crypto_md5_update(md5, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, md5_digest); memcpy(output, md5_digest, 8); } static void security_A(BYTE* master_secret, const BYTE* client_random, BYTE* server_random, BYTE* output) { security_premaster_hash("A", 1, master_secret, client_random, server_random, &output[0]); security_premaster_hash("BB", 2, master_secret, client_random, server_random, &output[16]); security_premaster_hash("CCC", 3, master_secret, client_random, server_random, &output[32]); } static void security_X(BYTE* master_secret, const BYTE* client_random, BYTE* server_random, BYTE* output) { security_premaster_hash("X", 1, master_secret, client_random, server_random, &output[0]); security_premaster_hash("YY", 2, master_secret, client_random, server_random, &output[16]); security_premaster_hash("ZZZ", 3, master_secret, client_random, server_random, &output[32]); } static void fips_expand_key_bits(BYTE* in, BYTE* out) { BYTE buf[21], c; int i, b, p, r; /* reverse every byte in the key */ for (i = 0; i < 21; i++) buf[i] = fips_reverse_table[in[i]]; /* insert a zero-bit after every 7th bit */ for (i = 0, b = 0; i < 24; i++, b += 7) { p = b / 8; r = b % 8; if (r == 0) { out[i] = buf[p] & 0xfe; } else { /* c is accumulator */ c = buf[p] << r; c |= buf[p + 1] >> (8 - r); out[i] = c & 0xfe; } } /* reverse every byte */ /* alter lsb so the byte has odd parity */ for (i = 0; i < 24; i++) out[i] = fips_oddparity_table[fips_reverse_table[out[i]]]; } BOOL security_establish_keys(const BYTE* client_random, rdpRdp* rdp) { BYTE pre_master_secret[48]; BYTE master_secret[48]; BYTE session_key_blob[48]; BYTE* server_random; BYTE salt40[] = { 0xD1, 0x26, 0x9E }; rdpSettings* settings; settings = rdp->settings; server_random = settings->ServerRandom; if (settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { CryptoSha1 sha1; BYTE client_encrypt_key_t[CRYPTO_SHA1_DIGEST_LENGTH + 1]; BYTE client_decrypt_key_t[CRYPTO_SHA1_DIGEST_LENGTH + 1]; printf("FIPS Compliant encryption level.\n"); /* disable fastpath input; it doesnt handle FIPS encryption yet */ rdp->settings->FastPathInput = FALSE; sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, client_random + 16, 16); crypto_sha1_update(sha1, server_random + 16, 16); crypto_sha1_final(sha1, client_encrypt_key_t); client_encrypt_key_t[20] = client_encrypt_key_t[0]; fips_expand_key_bits(client_encrypt_key_t, rdp->fips_encrypt_key); sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, client_random, 16); crypto_sha1_update(sha1, server_random, 16); crypto_sha1_final(sha1, client_decrypt_key_t); client_decrypt_key_t[20] = client_decrypt_key_t[0]; fips_expand_key_bits(client_decrypt_key_t, rdp->fips_decrypt_key); sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, client_decrypt_key_t, 20); crypto_sha1_update(sha1, client_encrypt_key_t, 20); crypto_sha1_final(sha1, rdp->fips_sign_key); } memcpy(pre_master_secret, client_random, 24); memcpy(pre_master_secret + 24, server_random, 24); security_A(pre_master_secret, client_random, server_random, master_secret); security_X(master_secret, client_random, server_random, session_key_blob); memcpy(rdp->sign_key, session_key_blob, 16); if (rdp->settings->ServerMode) { security_md5_16_32_32(&session_key_blob[16], client_random, server_random, rdp->encrypt_key); security_md5_16_32_32(&session_key_blob[32], client_random, server_random, rdp->decrypt_key); } else { security_md5_16_32_32(&session_key_blob[16], client_random, server_random, rdp->decrypt_key); security_md5_16_32_32(&session_key_blob[32], client_random, server_random, rdp->encrypt_key); } if (settings->EncryptionMethods == 1) /* 40 and 56 bit */ { memcpy(rdp->sign_key, salt40, 3); /* TODO 56 bit */ memcpy(rdp->decrypt_key, salt40, 3); /* TODO 56 bit */ memcpy(rdp->encrypt_key, salt40, 3); /* TODO 56 bit */ rdp->rc4_key_len = 8; } else if (settings->EncryptionMethods == 2) /* 128 bit */ { rdp->rc4_key_len = 16; } memcpy(rdp->decrypt_update_key, rdp->decrypt_key, 16); memcpy(rdp->encrypt_update_key, rdp->encrypt_key, 16); rdp->decrypt_use_count = 0; rdp->decrypt_checksum_use_count = 0; rdp->encrypt_use_count =0; rdp->encrypt_checksum_use_count =0; return TRUE; } BOOL security_key_update(BYTE* key, BYTE* update_key, int key_len) { BYTE sha1h[CRYPTO_SHA1_DIGEST_LENGTH]; CryptoMd5 md5; CryptoSha1 sha1; CryptoRc4 rc4; BYTE salt40[] = { 0xD1, 0x26, 0x9E }; sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, update_key, key_len); crypto_sha1_update(sha1, pad1, sizeof(pad1)); crypto_sha1_update(sha1, key, key_len); crypto_sha1_final(sha1, sha1h); md5 = crypto_md5_init(); crypto_md5_update(md5, update_key, key_len); crypto_md5_update(md5, pad2, sizeof(pad2)); crypto_md5_update(md5, sha1h, sizeof(sha1h)); crypto_md5_final(md5, key); rc4 = crypto_rc4_init(key, key_len); crypto_rc4(rc4, key_len, key, key); crypto_rc4_free(rc4); if (key_len == 8) memcpy(key, salt40, 3); /* TODO 56 bit */ return TRUE; } BOOL security_encrypt(BYTE* data, int length, rdpRdp* rdp) { if (rdp->encrypt_use_count >= 4096) { security_key_update(rdp->encrypt_key, rdp->encrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len); rdp->encrypt_use_count = 0; } crypto_rc4(rdp->rc4_encrypt_key, length, data, data); rdp->encrypt_use_count++; rdp->encrypt_checksum_use_count++; return TRUE; } BOOL security_decrypt(BYTE* data, int length, rdpRdp* rdp) { if (rdp->rc4_decrypt_key == NULL) return FALSE; if (rdp->decrypt_use_count >= 4096) { security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len); rdp->decrypt_use_count = 0; } crypto_rc4(rdp->rc4_decrypt_key, length, data, data); rdp->decrypt_use_count += 1; rdp->decrypt_checksum_use_count++; return TRUE; } void security_hmac_signature(const BYTE* data, int length, BYTE* output, rdpRdp* rdp) { BYTE buf[20]; BYTE use_count_le[4]; security_UINT32_le(use_count_le, rdp->encrypt_use_count); crypto_hmac_sha1_init(rdp->fips_hmac, rdp->fips_sign_key, 20); crypto_hmac_update(rdp->fips_hmac, data, length); crypto_hmac_update(rdp->fips_hmac, use_count_le, 4); crypto_hmac_final(rdp->fips_hmac, buf, 20); memmove(output, buf, 8); } BOOL security_fips_encrypt(BYTE* data, int length, rdpRdp* rdp) { crypto_des3_encrypt(rdp->fips_encrypt, length, data, data); rdp->encrypt_use_count++; return TRUE; } BOOL security_fips_decrypt(BYTE* data, int length, rdpRdp* rdp) { crypto_des3_decrypt(rdp->fips_decrypt, length, data, data); return TRUE; } BOOL security_fips_check_signature(const BYTE* data, int length, const BYTE* sig, rdpRdp* rdp) { BYTE buf[20]; BYTE use_count_le[4]; security_UINT32_le(use_count_le, rdp->decrypt_use_count); crypto_hmac_sha1_init(rdp->fips_hmac, rdp->fips_sign_key, 20); crypto_hmac_update(rdp->fips_hmac, data, length); crypto_hmac_update(rdp->fips_hmac, use_count_le, 4); crypto_hmac_final(rdp->fips_hmac, buf, 20); rdp->decrypt_use_count++; if (memcmp(sig, buf, 8)) return FALSE; return TRUE; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_5714_1
crossvul-cpp_data_good_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) { if(newspan && after) { newspan->_next = after->_next; newspan->_prev = after; after->_next->_prev = newspan; after->_next = newspan; } } static void sraSpanInsertBefore(sraSpan *newspan, sraSpan *before) { if(newspan && before) { newspan->_next = before; newspan->_prev = before->_prev; before->_prev->_next = newspan; before->_prev = newspan; } } static void sraSpanRemove(sraSpan *span) { if(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/good_4058_0
crossvul-cpp_data_bad_4271_0
/* ** $Id: ldebug.c $ ** Debug Interface ** See Copyright Notice in lua.h */ #define ldebug_c #define LUA_CORE #include "lprefix.h" #include <stdarg.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lapi.h" #include "lcode.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lobject.h" #include "lopcodes.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lvm.h" #define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_VCCL) /* inverse of 'pcRel' */ #define invpcRel(pc, p) ((p)->code + (pc) + 1) static const char *funcnamefromcode (lua_State *L, CallInfo *ci, const char **name); static int currentpc (CallInfo *ci) { lua_assert(isLua(ci)); return pcRel(ci->u.l.savedpc, ci_func(ci)->p); } /* ** Get a "base line" to find the line corresponding to an instruction. ** For that, search the array of absolute line info for the largest saved ** instruction smaller or equal to the wanted instruction. A special ** case is when there is no absolute info or the instruction is before ** the first absolute one. */ static int getbaseline (const Proto *f, int pc, int *basepc) { if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) { *basepc = -1; /* start from the beginning */ return f->linedefined; } else { unsigned int i; if (pc >= f->abslineinfo[f->sizeabslineinfo - 1].pc) i = f->sizeabslineinfo - 1; /* instruction is after last saved one */ else { /* binary search */ unsigned int j = f->sizeabslineinfo - 1; /* pc < anchorlines[j] */ i = 0; /* abslineinfo[i] <= pc */ while (i < j - 1) { unsigned int m = (j + i) / 2; if (pc >= f->abslineinfo[m].pc) i = m; else j = m; } } *basepc = f->abslineinfo[i].pc; return f->abslineinfo[i].line; } } /* ** Get the line corresponding to instruction 'pc' in function 'f'; ** first gets a base line and from there does the increments until ** the desired instruction. */ int luaG_getfuncline (const Proto *f, int pc) { if (f->lineinfo == NULL) /* no debug information? */ return -1; else { int basepc; int baseline = getbaseline(f, pc, &basepc); while (basepc++ < pc) { /* walk until given instruction */ lua_assert(f->lineinfo[basepc] != ABSLINEINFO); baseline += f->lineinfo[basepc]; /* correct line */ } return baseline; } } static int getcurrentline (CallInfo *ci) { return luaG_getfuncline(ci_func(ci)->p, currentpc(ci)); } /* ** Set 'trap' for all active Lua frames. ** This function can be called during a signal, under "reasonable" ** assumptions. A new 'ci' is completely linked in the list before it ** becomes part of the "active" list, and we assume that pointers are ** atomic; see comment in next function. ** (A compiler doing interprocedural optimizations could, theoretically, ** reorder memory writes in such a way that the list could be ** temporarily broken while inserting a new element. We simply assume it ** has no good reasons to do that.) */ static void settraps (CallInfo *ci) { for (; ci != NULL; ci = ci->previous) if (isLua(ci)) ci->u.l.trap = 1; } /* ** This function can be called during a signal, under "reasonable" ** assumptions. ** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount') ** are for debug only, and it is no problem if they get arbitrary ** values (causes at most one wrong hook call). 'hookmask' is an atomic ** value. We assume that pointers are atomic too (e.g., gcc ensures that ** for all platforms where it runs). Moreover, 'hook' is always checked ** before being called (see 'luaD_hook'). */ LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { if (func == NULL || mask == 0) { /* turn off hooks? */ mask = 0; func = NULL; } L->hook = func; L->basehookcount = count; resethookcount(L); L->hookmask = cast_byte(mask); if (mask) settraps(L->ci); /* to trace inside 'luaV_execute' */ } LUA_API lua_Hook lua_gethook (lua_State *L) { return L->hook; } LUA_API int lua_gethookmask (lua_State *L) { return L->hookmask; } LUA_API int lua_gethookcount (lua_State *L) { return L->basehookcount; } LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { int status; CallInfo *ci; if (level < 0) return 0; /* invalid (negative) level */ lua_lock(L); for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) level--; if (level == 0 && ci != &L->base_ci) { /* level found? */ status = 1; ar->i_ci = ci; } else status = 0; /* no such level */ lua_unlock(L); return status; } static const char *upvalname (const Proto *p, int uv) { TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); if (s == NULL) return "?"; else return getstr(s); } static const char *findvararg (CallInfo *ci, int n, StkId *pos) { if (clLvalue(s2v(ci->func))->p->is_vararg) { int nextra = ci->u.l.nextraargs; if (n >= -nextra) { /* 'n' is negative */ *pos = ci->func - nextra - (n + 1); return "(vararg)"; /* generic name for any vararg */ } } return NULL; /* no such vararg */ } const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) { StkId base = ci->func + 1; const char *name = NULL; if (isLua(ci)) { if (n < 0) /* access to vararg values? */ return findvararg(ci, n, pos); else name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); } if (name == NULL) { /* no 'standard' name? */ StkId limit = (ci == L->ci) ? L->top : ci->next->func; if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */ /* generic name for any valid slot */ name = isLua(ci) ? "(temporary)" : "(C temporary)"; } else return NULL; /* no name */ } if (pos) *pos = base + (n - 1); return name; } LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { const char *name; lua_lock(L); if (ar == NULL) { /* information about non-active function? */ if (!isLfunction(s2v(L->top - 1))) /* not a Lua function? */ name = NULL; else /* consider live variables at function start (parameters) */ name = luaF_getlocalname(clLvalue(s2v(L->top - 1))->p, n, 0); } else { /* active function; get information through 'ar' */ StkId pos = NULL; /* to avoid warnings */ name = luaG_findlocal(L, ar->i_ci, n, &pos); if (name) { setobjs2s(L, L->top, pos); api_incr_top(L); } } lua_unlock(L); return name; } LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { StkId pos = NULL; /* to avoid warnings */ const char *name; lua_lock(L); name = luaG_findlocal(L, ar->i_ci, n, &pos); if (name) { setobjs2s(L, pos, L->top - 1); L->top--; /* pop value */ } lua_unlock(L); return name; } static void funcinfo (lua_Debug *ar, Closure *cl) { if (noLuaClosure(cl)) { ar->source = "=[C]"; ar->srclen = LL("=[C]"); ar->linedefined = -1; ar->lastlinedefined = -1; ar->what = "C"; } else { const Proto *p = cl->l.p; if (p->source) { ar->source = getstr(p->source); ar->srclen = tsslen(p->source); } else { ar->source = "=?"; ar->srclen = LL("=?"); } ar->linedefined = p->linedefined; ar->lastlinedefined = p->lastlinedefined; ar->what = (ar->linedefined == 0) ? "main" : "Lua"; } luaO_chunkid(ar->short_src, ar->source, ar->srclen); } static int nextline (const Proto *p, int currentline, int pc) { if (p->lineinfo[pc] != ABSLINEINFO) return currentline + p->lineinfo[pc]; else return luaG_getfuncline(p, pc); } static void collectvalidlines (lua_State *L, Closure *f) { if (noLuaClosure(f)) { setnilvalue(s2v(L->top)); api_incr_top(L); } else { int i; TValue v; const Proto *p = f->l.p; int currentline = p->linedefined; Table *t = luaH_new(L); /* new table to store active lines */ sethvalue2s(L, L->top, t); /* push it on stack */ api_incr_top(L); setbtvalue(&v); /* boolean 'true' to be the value of all indices */ for (i = 0; i < p->sizelineinfo; i++) { /* for all lines with code */ currentline = nextline(p, currentline, i); luaH_setint(L, t, currentline, &v); /* table[line] = true */ } } } static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { if (ci == NULL) /* no 'ci'? */ return NULL; /* no info */ else if (ci->callstatus & CIST_FIN) { /* is this a finalizer? */ *name = "__gc"; return "metamethod"; /* report it as such */ } /* calling function is a known Lua function? */ else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) return funcnamefromcode(L, ci->previous, name); else return NULL; /* no way to find a name */ } static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, Closure *f, CallInfo *ci) { int status = 1; for (; *what; what++) { switch (*what) { case 'S': { funcinfo(ar, f); break; } case 'l': { ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1; break; } case 'u': { ar->nups = (f == NULL) ? 0 : f->c.nupvalues; if (noLuaClosure(f)) { ar->isvararg = 1; ar->nparams = 0; } else { ar->isvararg = f->l.p->is_vararg; ar->nparams = f->l.p->numparams; } break; } case 't': { ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; break; } case 'n': { ar->namewhat = getfuncname(L, ci, &ar->name); if (ar->namewhat == NULL) { ar->namewhat = ""; /* not found */ ar->name = NULL; } break; } case 'r': { if (ci == NULL || !(ci->callstatus & CIST_TRAN)) ar->ftransfer = ar->ntransfer = 0; else { ar->ftransfer = ci->u2.transferinfo.ftransfer; ar->ntransfer = ci->u2.transferinfo.ntransfer; } break; } case 'L': case 'f': /* handled by lua_getinfo */ break; default: status = 0; /* invalid option */ } } return status; } LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { int status; Closure *cl; CallInfo *ci; TValue *func; lua_lock(L); if (*what == '>') { ci = NULL; func = s2v(L->top - 1); api_check(L, ttisfunction(func), "function expected"); what++; /* skip the '>' */ L->top--; /* pop function */ } else { ci = ar->i_ci; func = s2v(ci->func); lua_assert(ttisfunction(func)); } cl = ttisclosure(func) ? clvalue(func) : NULL; status = auxgetinfo(L, what, ar, cl, ci); if (strchr(what, 'f')) { setobj2s(L, L->top, func); api_incr_top(L); } if (strchr(what, 'L')) collectvalidlines(L, cl); lua_unlock(L); return status; } /* ** {====================================================== ** Symbolic Execution ** ======================================================= */ static const char *getobjname (const Proto *p, int lastpc, int reg, const char **name); /* ** Find a "name" for the constant 'c'. */ static void kname (const Proto *p, int c, const char **name) { TValue *kvalue = &p->k[c]; *name = (ttisstring(kvalue)) ? svalue(kvalue) : "?"; } /* ** Find a "name" for the register 'c'. */ static void rname (const Proto *p, int pc, int c, const char **name) { const char *what = getobjname(p, pc, c, name); /* search for 'c' */ if (!(what && *what == 'c')) /* did not find a constant name? */ *name = "?"; } /* ** Find a "name" for a 'C' value in an RK instruction. */ static void rkname (const Proto *p, int pc, Instruction i, const char **name) { int c = GETARG_C(i); /* key index */ if (GETARG_k(i)) /* is 'c' a constant? */ kname(p, c, name); else /* 'c' is a register */ rname(p, pc, c, name); } static int filterpc (int pc, int jmptarget) { if (pc < jmptarget) /* is code conditional (inside a jump)? */ return -1; /* cannot know who sets that register */ else return pc; /* current position sets that register */ } /* ** Try to find last instruction before 'lastpc' that modified register 'reg'. */ static int findsetreg (const Proto *p, int lastpc, int reg) { int pc; int setreg = -1; /* keep last instruction that changed 'reg' */ int jmptarget = 0; /* any code before this address is conditional */ if (testMMMode(GET_OPCODE(p->code[lastpc]))) lastpc--; /* previous instruction was not actually executed */ for (pc = 0; pc < lastpc; pc++) { Instruction i = p->code[pc]; OpCode op = GET_OPCODE(i); int a = GETARG_A(i); int change; /* true if current instruction changed 'reg' */ switch (op) { case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */ int b = GETARG_B(i); change = (a <= reg && reg <= a + b); break; } case OP_TFORCALL: { /* affect all regs above its base */ change = (reg >= a + 2); break; } case OP_CALL: case OP_TAILCALL: { /* affect all registers above base */ change = (reg >= a); break; } case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */ int b = GETARG_sJ(i); int dest = pc + 1 + b; /* jump does not skip 'lastpc' and is larger than current one? */ if (dest <= lastpc && dest > jmptarget) jmptarget = dest; /* update 'jmptarget' */ change = 0; break; } default: /* any instruction that sets A */ change = (testAMode(op) && reg == a); break; } if (change) setreg = filterpc(pc, jmptarget); } return setreg; } /* ** Check whether table being indexed by instruction 'i' is the ** environment '_ENV' */ static const char *gxf (const Proto *p, int pc, Instruction i, int isup) { int t = GETARG_B(i); /* table index */ const char *name; /* name of indexed variable */ if (isup) /* is an upvalue? */ name = upvalname(p, t); else getobjname(p, pc, t, &name); return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field"; } static const char *getobjname (const Proto *p, int lastpc, int reg, const char **name) { int pc; *name = luaF_getlocalname(p, reg + 1, lastpc); if (*name) /* is a local? */ return "local"; /* else try symbolic execution */ pc = findsetreg(p, lastpc, reg); if (pc != -1) { /* could find instruction? */ Instruction i = p->code[pc]; OpCode op = GET_OPCODE(i); switch (op) { case OP_MOVE: { int b = GETARG_B(i); /* move from 'b' to 'a' */ if (b < GETARG_A(i)) return getobjname(p, pc, b, name); /* get name for 'b' */ break; } case OP_GETTABUP: { int k = GETARG_C(i); /* key index */ kname(p, k, name); return gxf(p, pc, i, 1); } case OP_GETTABLE: { int k = GETARG_C(i); /* key index */ rname(p, pc, k, name); return gxf(p, pc, i, 0); } case OP_GETI: { *name = "integer index"; return "field"; } case OP_GETFIELD: { int k = GETARG_C(i); /* key index */ kname(p, k, name); return gxf(p, pc, i, 0); } case OP_GETUPVAL: { *name = upvalname(p, GETARG_B(i)); return "upvalue"; } case OP_LOADK: case OP_LOADKX: { int b = (op == OP_LOADK) ? GETARG_Bx(i) : GETARG_Ax(p->code[pc + 1]); if (ttisstring(&p->k[b])) { *name = svalue(&p->k[b]); return "constant"; } break; } case OP_SELF: { rkname(p, pc, i, name); return "method"; } default: break; /* go through to return NULL */ } } return NULL; /* could not find reasonable name */ } /* ** Try to find a name for a function based on the code that called it. ** (Only works when function was called by a Lua function.) ** Returns what the name is (e.g., "for iterator", "method", ** "metamethod") and sets '*name' to point to the name. */ static const char *funcnamefromcode (lua_State *L, CallInfo *ci, const char **name) { TMS tm = (TMS)0; /* (initial value avoids warnings) */ const Proto *p = ci_func(ci)->p; /* calling function */ int pc = currentpc(ci); /* calling instruction index */ Instruction i = p->code[pc]; /* calling instruction */ if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ *name = "?"; return "hook"; } switch (GET_OPCODE(i)) { case OP_CALL: case OP_TAILCALL: return getobjname(p, pc, GETARG_A(i), name); /* get function name */ case OP_TFORCALL: { /* for iterator */ *name = "for iterator"; return "for iterator"; } /* other instructions can do calls through metamethods */ case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: case OP_GETI: case OP_GETFIELD: tm = TM_INDEX; break; case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD: tm = TM_NEWINDEX; break; case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { tm = cast(TMS, GETARG_C(i)); break; } case OP_UNM: tm = TM_UNM; break; case OP_BNOT: tm = TM_BNOT; break; case OP_LEN: tm = TM_LEN; break; case OP_CONCAT: tm = TM_CONCAT; break; case OP_EQ: tm = TM_EQ; break; case OP_LT: case OP_LE: case OP_LTI: case OP_LEI: *name = "order"; /* '<=' can call '__lt', etc. */ return "metamethod"; case OP_CLOSE: case OP_RETURN: *name = "close"; return "metamethod"; default: return NULL; /* cannot find a reasonable name */ } *name = getstr(G(L)->tmname[tm]) + 2; return "metamethod"; } /* }====================================================== */ /* ** The subtraction of two potentially unrelated pointers is ** not ISO C, but it should not crash a program; the subsequent ** checks are ISO C and ensure a correct result. */ static int isinstack (CallInfo *ci, const TValue *o) { StkId base = ci->func + 1; ptrdiff_t i = cast(StkId, o) - base; return (0 <= i && i < (ci->top - base) && s2v(base + i) == o); } /* ** Checks whether value 'o' came from an upvalue. (That can only happen ** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on ** upvalues.) */ static const char *getupvalname (CallInfo *ci, const TValue *o, const char **name) { LClosure *c = ci_func(ci); int i; for (i = 0; i < c->nupvalues; i++) { if (c->upvals[i]->v == o) { *name = upvalname(c->p, i); return "upvalue"; } } return NULL; } static const char *varinfo (lua_State *L, const TValue *o) { const char *name = NULL; /* to avoid warnings */ CallInfo *ci = L->ci; const char *kind = NULL; if (isLua(ci)) { kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ if (!kind && isinstack(ci, o)) /* no? try a register */ kind = getobjname(ci_func(ci)->p, currentpc(ci), cast_int(cast(StkId, o) - (ci->func + 1)), &name); } return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : ""; } l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { const char *t = luaT_objtypename(L, o); luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o)); } l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) { luaG_runerror(L, "bad 'for' %s (number expected, got %s)", what, luaT_objtypename(L, o)); } l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { if (ttisstring(p1) || cvt2str(p1)) p1 = p2; luaG_typeerror(L, p1, "concatenate"); } l_noret luaG_opinterror (lua_State *L, const TValue *p1, const TValue *p2, const char *msg) { if (!ttisnumber(p1)) /* first operand is wrong? */ p2 = p1; /* now second is wrong */ luaG_typeerror(L, p2, msg); } /* ** Error when both values are convertible to numbers, but not to integers */ l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) { lua_Integer temp; if (!tointegerns(p1, &temp)) p2 = p1; luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2)); } l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { const char *t1 = luaT_objtypename(L, p1); const char *t2 = luaT_objtypename(L, p2); if (strcmp(t1, t2) == 0) luaG_runerror(L, "attempt to compare two %s values", t1); else luaG_runerror(L, "attempt to compare %s with %s", t1, t2); } /* add src:line information to 'msg' */ const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, int line) { char buff[LUA_IDSIZE]; if (src) luaO_chunkid(buff, getstr(src), tsslen(src)); else { /* no source available; use "?" instead */ buff[0] = '?'; buff[1] = '\0'; } return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); } l_noret luaG_errormsg (lua_State *L) { if (L->errfunc != 0) { /* is there an error handling function? */ StkId errfunc = restorestack(L, L->errfunc); lua_assert(ttisfunction(s2v(errfunc))); setobjs2s(L, L->top, L->top - 1); /* move argument */ setobjs2s(L, L->top - 1, errfunc); /* push function */ L->top++; /* assume EXTRA_STACK */ luaD_callnoyield(L, L->top - 2, 1); /* call it */ } luaD_throw(L, LUA_ERRRUN); } l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { CallInfo *ci = L->ci; const char *msg; va_list argp; luaC_checkGC(L); /* error message uses memory */ va_start(argp, fmt); msg = luaO_pushvfstring(L, fmt, argp); /* format message */ va_end(argp); if (isLua(ci)) /* if Lua function, add source:line information */ luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci)); luaG_errormsg(L); } /* ** Check whether new instruction 'newpc' is in a different line from ** previous instruction 'oldpc'. */ static int changedline (const Proto *p, int oldpc, int newpc) { while (oldpc++ < newpc) { if (p->lineinfo[oldpc] != 0) return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc)); } return 0; /* no line changes in the way */ } /* ** Traces the execution of a Lua function. Called before the execution ** of each opcode, when debug is on. 'L->oldpc' stores the last ** instruction traced, to detect line changes. When entering a new ** function, 'npci' will be zero and will test as a new line without ** the need for 'oldpc'; so, 'oldpc' does not need to be initialized ** before. Some exceptional conditions may return to a function without ** updating 'oldpc'. In that case, 'oldpc' may be invalid; if so, it is ** reset to zero. (A wrong but valid 'oldpc' at most causes an extra ** call to a line hook.) */ int luaG_traceexec (lua_State *L, const Instruction *pc) { CallInfo *ci = L->ci; lu_byte mask = L->hookmask; const Proto *p = ci_func(ci)->p; int counthook; /* 'L->oldpc' may be invalid; reset it in this case */ int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0; if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */ ci->u.l.trap = 0; /* don't need to stop again */ return 0; /* turn off 'trap' */ } pc++; /* reference is always next instruction */ ci->u.l.savedpc = pc; /* save 'pc' */ counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT)); if (counthook) resethookcount(L); /* reset count */ else if (!(mask & LUA_MASKLINE)) return 1; /* no line hook and count != 0; nothing to be done now */ if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ return 1; /* do not call hook again (VM yielded, so it did not move) */ } if (!isIT(*(ci->u.l.savedpc - 1))) L->top = ci->top; /* prepare top */ if (counthook) luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */ if (mask & LUA_MASKLINE) { int npci = pcRel(pc, p); if (npci == 0 || /* call linehook when enter a new function, */ pc <= invpcRel(oldpc, p) || /* when jump back (loop), or when */ changedline(p, oldpc, npci)) { /* enter new line */ int newline = luaG_getfuncline(p, npci); luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */ } L->oldpc = npci; /* 'pc' of last call to line hook */ } if (L->status == LUA_YIELD) { /* did hook yield? */ if (counthook) L->hookcount = 1; /* undo decrement to zero */ ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ luaD_throw(L, LUA_YIELD); } return 1; /* keep 'trap' on */ }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_4271_0
crossvul-cpp_data_bad_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 & 0xffffff00) != 0x100) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer < 0x120) VO++; else if (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/bad_5358_0
crossvul-cpp_data_good_3060_7
#include <linux/ceph/ceph_debug.h> #include <linux/err.h> #include <linux/scatterlist.h> #include <linux/slab.h> #include <crypto/hash.h> #include <linux/key-type.h> #include <keys/ceph-type.h> #include <keys/user-type.h> #include <linux/ceph/decode.h> #include "crypto.h" int ceph_crypto_key_clone(struct ceph_crypto_key *dst, const struct ceph_crypto_key *src) { memcpy(dst, src, sizeof(struct ceph_crypto_key)); dst->key = kmemdup(src->key, src->len, GFP_NOFS); if (!dst->key) return -ENOMEM; return 0; } int ceph_crypto_key_encode(struct ceph_crypto_key *key, void **p, void *end) { if (*p + sizeof(u16) + sizeof(key->created) + sizeof(u16) + key->len > end) return -ERANGE; ceph_encode_16(p, key->type); ceph_encode_copy(p, &key->created, sizeof(key->created)); ceph_encode_16(p, key->len); ceph_encode_copy(p, key->key, key->len); return 0; } int ceph_crypto_key_decode(struct ceph_crypto_key *key, void **p, void *end) { ceph_decode_need(p, end, 2*sizeof(u16) + sizeof(key->created), bad); key->type = ceph_decode_16(p); ceph_decode_copy(p, &key->created, sizeof(key->created)); key->len = ceph_decode_16(p); ceph_decode_need(p, end, key->len, bad); key->key = kmalloc(key->len, GFP_NOFS); if (!key->key) return -ENOMEM; ceph_decode_copy(p, key->key, key->len); return 0; bad: dout("failed to decode crypto key\n"); return -EINVAL; } int ceph_crypto_key_unarmor(struct ceph_crypto_key *key, const char *inkey) { int inlen = strlen(inkey); int blen = inlen * 3 / 4; void *buf, *p; int ret; dout("crypto_key_unarmor %s\n", inkey); buf = kmalloc(blen, GFP_NOFS); if (!buf) return -ENOMEM; blen = ceph_unarmor(buf, inkey, inkey+inlen); if (blen < 0) { kfree(buf); return blen; } p = buf; ret = ceph_crypto_key_decode(key, &p, p + blen); kfree(buf); if (ret) return ret; dout("crypto_key_unarmor key %p type %d len %d\n", key, key->type, key->len); return 0; } #define AES_KEY_SIZE 16 static struct crypto_blkcipher *ceph_crypto_alloc_cipher(void) { return crypto_alloc_blkcipher("cbc(aes)", 0, CRYPTO_ALG_ASYNC); } static const u8 *aes_iv = (u8 *)CEPH_AES_IV; static int ceph_aes_encrypt(const void *key, int key_len, void *dst, size_t *dst_len, const void *src, size_t src_len) { struct scatterlist sg_in[2], sg_out[1]; struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher(); struct blkcipher_desc desc = { .tfm = tfm, .flags = 0 }; int ret; void *iv; int ivsize; size_t zero_padding = (0x10 - (src_len & 0x0f)); char pad[16]; if (IS_ERR(tfm)) return PTR_ERR(tfm); memset(pad, zero_padding, zero_padding); *dst_len = src_len + zero_padding; crypto_blkcipher_setkey((void *)tfm, key, key_len); sg_init_table(sg_in, 2); sg_set_buf(&sg_in[0], src, src_len); sg_set_buf(&sg_in[1], pad, zero_padding); sg_init_table(sg_out, 1); sg_set_buf(sg_out, dst, *dst_len); iv = crypto_blkcipher_crt(tfm)->iv; ivsize = crypto_blkcipher_ivsize(tfm); memcpy(iv, aes_iv, ivsize); /* print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1, key, key_len, 1); print_hex_dump(KERN_ERR, "enc src: ", DUMP_PREFIX_NONE, 16, 1, src, src_len, 1); print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1, pad, zero_padding, 1); */ ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in, src_len + zero_padding); crypto_free_blkcipher(tfm); if (ret < 0) pr_err("ceph_aes_crypt failed %d\n", ret); /* print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1, dst, *dst_len, 1); */ return 0; } static int ceph_aes_encrypt2(const void *key, int key_len, void *dst, size_t *dst_len, const void *src1, size_t src1_len, const void *src2, size_t src2_len) { struct scatterlist sg_in[3], sg_out[1]; struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher(); struct blkcipher_desc desc = { .tfm = tfm, .flags = 0 }; int ret; void *iv; int ivsize; size_t zero_padding = (0x10 - ((src1_len + src2_len) & 0x0f)); char pad[16]; if (IS_ERR(tfm)) return PTR_ERR(tfm); memset(pad, zero_padding, zero_padding); *dst_len = src1_len + src2_len + zero_padding; crypto_blkcipher_setkey((void *)tfm, key, key_len); sg_init_table(sg_in, 3); sg_set_buf(&sg_in[0], src1, src1_len); sg_set_buf(&sg_in[1], src2, src2_len); sg_set_buf(&sg_in[2], pad, zero_padding); sg_init_table(sg_out, 1); sg_set_buf(sg_out, dst, *dst_len); iv = crypto_blkcipher_crt(tfm)->iv; ivsize = crypto_blkcipher_ivsize(tfm); memcpy(iv, aes_iv, ivsize); /* print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1, key, key_len, 1); print_hex_dump(KERN_ERR, "enc src1: ", DUMP_PREFIX_NONE, 16, 1, src1, src1_len, 1); print_hex_dump(KERN_ERR, "enc src2: ", DUMP_PREFIX_NONE, 16, 1, src2, src2_len, 1); print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1, pad, zero_padding, 1); */ ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in, src1_len + src2_len + zero_padding); crypto_free_blkcipher(tfm); if (ret < 0) pr_err("ceph_aes_crypt2 failed %d\n", ret); /* print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1, dst, *dst_len, 1); */ return 0; } static int ceph_aes_decrypt(const void *key, int key_len, void *dst, size_t *dst_len, const void *src, size_t src_len) { struct scatterlist sg_in[1], sg_out[2]; struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher(); struct blkcipher_desc desc = { .tfm = tfm }; char pad[16]; void *iv; int ivsize; int ret; int last_byte; if (IS_ERR(tfm)) return PTR_ERR(tfm); crypto_blkcipher_setkey((void *)tfm, key, key_len); sg_init_table(sg_in, 1); sg_init_table(sg_out, 2); sg_set_buf(sg_in, src, src_len); sg_set_buf(&sg_out[0], dst, *dst_len); sg_set_buf(&sg_out[1], pad, sizeof(pad)); iv = crypto_blkcipher_crt(tfm)->iv; ivsize = crypto_blkcipher_ivsize(tfm); memcpy(iv, aes_iv, ivsize); /* print_hex_dump(KERN_ERR, "dec key: ", DUMP_PREFIX_NONE, 16, 1, key, key_len, 1); print_hex_dump(KERN_ERR, "dec in: ", DUMP_PREFIX_NONE, 16, 1, src, src_len, 1); */ ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, src_len); crypto_free_blkcipher(tfm); if (ret < 0) { pr_err("ceph_aes_decrypt failed %d\n", ret); return ret; } if (src_len <= *dst_len) last_byte = ((char *)dst)[src_len - 1]; else last_byte = pad[src_len - *dst_len - 1]; if (last_byte <= 16 && src_len >= last_byte) { *dst_len = src_len - last_byte; } else { pr_err("ceph_aes_decrypt got bad padding %d on src len %d\n", last_byte, (int)src_len); return -EPERM; /* bad padding */ } /* print_hex_dump(KERN_ERR, "dec out: ", DUMP_PREFIX_NONE, 16, 1, dst, *dst_len, 1); */ return 0; } static int ceph_aes_decrypt2(const void *key, int key_len, void *dst1, size_t *dst1_len, void *dst2, size_t *dst2_len, const void *src, size_t src_len) { struct scatterlist sg_in[1], sg_out[3]; struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher(); struct blkcipher_desc desc = { .tfm = tfm }; char pad[16]; void *iv; int ivsize; int ret; int last_byte; if (IS_ERR(tfm)) return PTR_ERR(tfm); sg_init_table(sg_in, 1); sg_set_buf(sg_in, src, src_len); sg_init_table(sg_out, 3); sg_set_buf(&sg_out[0], dst1, *dst1_len); sg_set_buf(&sg_out[1], dst2, *dst2_len); sg_set_buf(&sg_out[2], pad, sizeof(pad)); crypto_blkcipher_setkey((void *)tfm, key, key_len); iv = crypto_blkcipher_crt(tfm)->iv; ivsize = crypto_blkcipher_ivsize(tfm); memcpy(iv, aes_iv, ivsize); /* print_hex_dump(KERN_ERR, "dec key: ", DUMP_PREFIX_NONE, 16, 1, key, key_len, 1); print_hex_dump(KERN_ERR, "dec in: ", DUMP_PREFIX_NONE, 16, 1, src, src_len, 1); */ ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, src_len); crypto_free_blkcipher(tfm); if (ret < 0) { pr_err("ceph_aes_decrypt failed %d\n", ret); return ret; } if (src_len <= *dst1_len) last_byte = ((char *)dst1)[src_len - 1]; else if (src_len <= *dst1_len + *dst2_len) last_byte = ((char *)dst2)[src_len - *dst1_len - 1]; else last_byte = pad[src_len - *dst1_len - *dst2_len - 1]; if (last_byte <= 16 && src_len >= last_byte) { src_len -= last_byte; } else { pr_err("ceph_aes_decrypt got bad padding %d on src len %d\n", last_byte, (int)src_len); return -EPERM; /* bad padding */ } if (src_len < *dst1_len) { *dst1_len = src_len; *dst2_len = 0; } else { *dst2_len = src_len - *dst1_len; } /* print_hex_dump(KERN_ERR, "dec out1: ", DUMP_PREFIX_NONE, 16, 1, dst1, *dst1_len, 1); print_hex_dump(KERN_ERR, "dec out2: ", DUMP_PREFIX_NONE, 16, 1, dst2, *dst2_len, 1); */ return 0; } int ceph_decrypt(struct ceph_crypto_key *secret, void *dst, size_t *dst_len, const void *src, size_t src_len) { switch (secret->type) { case CEPH_CRYPTO_NONE: if (*dst_len < src_len) return -ERANGE; memcpy(dst, src, src_len); *dst_len = src_len; return 0; case CEPH_CRYPTO_AES: return ceph_aes_decrypt(secret->key, secret->len, dst, dst_len, src, src_len); default: return -EINVAL; } } int ceph_decrypt2(struct ceph_crypto_key *secret, void *dst1, size_t *dst1_len, void *dst2, size_t *dst2_len, const void *src, size_t src_len) { size_t t; switch (secret->type) { case CEPH_CRYPTO_NONE: if (*dst1_len + *dst2_len < src_len) return -ERANGE; t = min(*dst1_len, src_len); memcpy(dst1, src, t); *dst1_len = t; src += t; src_len -= t; if (src_len) { t = min(*dst2_len, src_len); memcpy(dst2, src, t); *dst2_len = t; } return 0; case CEPH_CRYPTO_AES: return ceph_aes_decrypt2(secret->key, secret->len, dst1, dst1_len, dst2, dst2_len, src, src_len); default: return -EINVAL; } } int ceph_encrypt(struct ceph_crypto_key *secret, void *dst, size_t *dst_len, const void *src, size_t src_len) { switch (secret->type) { case CEPH_CRYPTO_NONE: if (*dst_len < src_len) return -ERANGE; memcpy(dst, src, src_len); *dst_len = src_len; return 0; case CEPH_CRYPTO_AES: return ceph_aes_encrypt(secret->key, secret->len, dst, dst_len, src, src_len); default: return -EINVAL; } } int ceph_encrypt2(struct ceph_crypto_key *secret, void *dst, size_t *dst_len, const void *src1, size_t src1_len, const void *src2, size_t src2_len) { switch (secret->type) { case CEPH_CRYPTO_NONE: if (*dst_len < src1_len + src2_len) return -ERANGE; memcpy(dst, src1, src1_len); memcpy(dst + src1_len, src2, src2_len); *dst_len = src1_len + src2_len; return 0; case CEPH_CRYPTO_AES: return ceph_aes_encrypt2(secret->key, secret->len, dst, dst_len, src1, src1_len, src2, src2_len); default: return -EINVAL; } } static int ceph_key_preparse(struct key_preparsed_payload *prep) { struct ceph_crypto_key *ckey; size_t datalen = prep->datalen; int ret; void *p; ret = -EINVAL; if (datalen <= 0 || datalen > 32767 || !prep->data) goto err; ret = -ENOMEM; ckey = kmalloc(sizeof(*ckey), GFP_KERNEL); if (!ckey) goto err; /* TODO ceph_crypto_key_decode should really take const input */ p = (void *)prep->data; ret = ceph_crypto_key_decode(ckey, &p, (char*)prep->data+datalen); if (ret < 0) goto err_ckey; prep->payload[0] = ckey; prep->quotalen = datalen; return 0; err_ckey: kfree(ckey); err: return ret; } static void ceph_key_free_preparse(struct key_preparsed_payload *prep) { struct ceph_crypto_key *ckey = prep->payload[0]; ceph_crypto_key_destroy(ckey); kfree(ckey); } static void ceph_key_destroy(struct key *key) { struct ceph_crypto_key *ckey = key->payload.data; ceph_crypto_key_destroy(ckey); kfree(ckey); } struct key_type key_type_ceph = { .name = "ceph", .preparse = ceph_key_preparse, .free_preparse = ceph_key_free_preparse, .instantiate = generic_key_instantiate, .destroy = ceph_key_destroy, }; int ceph_crypto_init(void) { return register_key_type(&key_type_ceph); } void ceph_crypto_shutdown(void) { unregister_key_type(&key_type_ceph); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_3060_7
crossvul-cpp_data_good_831_0
/* * Linux MegaRAID driver for SAS based RAID controllers * * Copyright (c) 2003-2013 LSI Corporation * Copyright (c) 2013-2016 Avago Technologies * Copyright (c) 2016-2018 Broadcom Inc. * * 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/>. * * Authors: Broadcom Inc. * Sreenivas Bagalkote * Sumant Patro * Bo Yang * Adam Radford * Kashyap Desai <kashyap.desai@broadcom.com> * Sumit Saxena <sumit.saxena@broadcom.com> * * Send feedback to: megaraidlinux.pdl@broadcom.com */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/pci.h> #include <linux/list.h> #include <linux/moduleparam.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/uio.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <asm/unaligned.h> #include <linux/fs.h> #include <linux/compat.h> #include <linux/blkdev.h> #include <linux/mutex.h> #include <linux/poll.h> #include <linux/vmalloc.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_tcq.h> #include "megaraid_sas_fusion.h" #include "megaraid_sas.h" /* * Number of sectors per IO command * Will be set in megasas_init_mfi if user does not provide */ static unsigned int max_sectors; module_param_named(max_sectors, max_sectors, int, 0); MODULE_PARM_DESC(max_sectors, "Maximum number of sectors per IO command"); static int msix_disable; module_param(msix_disable, int, S_IRUGO); MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0"); static unsigned int msix_vectors; module_param(msix_vectors, int, S_IRUGO); MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW"); static int allow_vf_ioctls; module_param(allow_vf_ioctls, int, S_IRUGO); MODULE_PARM_DESC(allow_vf_ioctls, "Allow ioctls in SR-IOV VF mode. Default: 0"); static unsigned int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH; module_param(throttlequeuedepth, int, S_IRUGO); MODULE_PARM_DESC(throttlequeuedepth, "Adapter queue depth when throttled due to I/O timeout. Default: 16"); unsigned int resetwaittime = MEGASAS_RESET_WAIT_TIME; module_param(resetwaittime, int, S_IRUGO); MODULE_PARM_DESC(resetwaittime, "Wait time in (1-180s) after I/O timeout before resetting adapter. Default: 180s"); int smp_affinity_enable = 1; module_param(smp_affinity_enable, int, S_IRUGO); MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disable Default: enable(1)"); int rdpq_enable = 1; module_param(rdpq_enable, int, S_IRUGO); MODULE_PARM_DESC(rdpq_enable, "Allocate reply queue in chunks for large queue depth enable/disable Default: enable(1)"); unsigned int dual_qdepth_disable; module_param(dual_qdepth_disable, int, S_IRUGO); MODULE_PARM_DESC(dual_qdepth_disable, "Disable dual queue depth feature. Default: 0"); unsigned int scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT; module_param(scmd_timeout, int, S_IRUGO); MODULE_PARM_DESC(scmd_timeout, "scsi command timeout (10-90s), default 90s. See megasas_reset_timer."); MODULE_LICENSE("GPL"); MODULE_VERSION(MEGASAS_VERSION); MODULE_AUTHOR("megaraidlinux.pdl@broadcom.com"); MODULE_DESCRIPTION("Broadcom MegaRAID SAS Driver"); int megasas_transition_to_ready(struct megasas_instance *instance, int ocr); static int megasas_get_pd_list(struct megasas_instance *instance); static int megasas_ld_list_query(struct megasas_instance *instance, u8 query_type); static int megasas_issue_init_mfi(struct megasas_instance *instance); static int megasas_register_aen(struct megasas_instance *instance, u32 seq_num, u32 class_locale_word); static void megasas_get_pd_info(struct megasas_instance *instance, struct scsi_device *sdev); /* * PCI ID table for all supported controllers */ static struct pci_device_id megasas_pci_table[] = { {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)}, /* xscale IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)}, /* ppc IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)}, /* ppc IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)}, /* gen2*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)}, /* gen2*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)}, /* skinny*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)}, /* skinny*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)}, /* xscale IOP, vega */ {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)}, /* xscale IOP */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)}, /* Fusion */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_PLASMA)}, /* Plasma */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)}, /* Invader */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FURY)}, /* Fury */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER)}, /* Intruder */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER_24)}, /* Intruder 24 port*/ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_52)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_53)}, /* VENTURA */ {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_HARPOON)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_TOMCAT)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA_4PORT)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER_4PORT)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E1)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E2)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E5)}, {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E6)}, {} }; MODULE_DEVICE_TABLE(pci, megasas_pci_table); static int megasas_mgmt_majorno; struct megasas_mgmt_info megasas_mgmt_info; static struct fasync_struct *megasas_async_queue; static DEFINE_MUTEX(megasas_async_queue_mutex); static int megasas_poll_wait_aen; static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait); static u32 support_poll_for_event; u32 megasas_dbg_lvl; static u32 support_device_change; static bool support_nvme_encapsulation; /* define lock for aen poll */ spinlock_t poll_aen_lock; void megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd, u8 alt_status); static u32 megasas_read_fw_status_reg_gen2(struct megasas_instance *instance); static int megasas_adp_reset_gen2(struct megasas_instance *instance, struct megasas_register_set __iomem *reg_set); static irqreturn_t megasas_isr(int irq, void *devp); static u32 megasas_init_adapter_mfi(struct megasas_instance *instance); u32 megasas_build_and_issue_cmd(struct megasas_instance *instance, struct scsi_cmnd *scmd); static void megasas_complete_cmd_dpc(unsigned long instance_addr); int wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd, int seconds); void megasas_fusion_ocr_wq(struct work_struct *work); static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance, int initial); static int megasas_set_dma_mask(struct megasas_instance *instance); static int megasas_alloc_ctrl_mem(struct megasas_instance *instance); static inline void megasas_free_ctrl_mem(struct megasas_instance *instance); static inline int megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance); static inline void megasas_free_ctrl_dma_buffers(struct megasas_instance *instance); static inline void megasas_init_ctrl_params(struct megasas_instance *instance); u32 megasas_readl(struct megasas_instance *instance, const volatile void __iomem *addr) { u32 i = 0, ret_val; /* * Due to a HW errata in Aero controllers, reads to certain * Fusion registers could intermittently return all zeroes. * This behavior is transient in nature and subsequent reads will * return valid value. As a workaround in driver, retry readl for * upto three times until a non-zero value is read. */ if (instance->adapter_type == AERO_SERIES) { do { ret_val = readl(addr); i++; } while (ret_val == 0 && i < 3); return ret_val; } else { return readl(addr); } } /** * megasas_set_dma_settings - Populate DMA address, length and flags for DCMDs * @instance: Adapter soft state * @dcmd: DCMD frame inside MFI command * @dma_addr: DMA address of buffer to be passed to FW * @dma_len: Length of DMA buffer to be passed to FW * @return: void */ void megasas_set_dma_settings(struct megasas_instance *instance, struct megasas_dcmd_frame *dcmd, dma_addr_t dma_addr, u32 dma_len) { if (instance->consistent_mask_64bit) { dcmd->sgl.sge64[0].phys_addr = cpu_to_le64(dma_addr); dcmd->sgl.sge64[0].length = cpu_to_le32(dma_len); dcmd->flags = cpu_to_le16(dcmd->flags | MFI_FRAME_SGL64); } else { dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(lower_32_bits(dma_addr)); dcmd->sgl.sge32[0].length = cpu_to_le32(dma_len); dcmd->flags = cpu_to_le16(dcmd->flags); } } void megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, 0, instance->reg_set); return; } /** * megasas_get_cmd - Get a command from the free pool * @instance: Adapter soft state * * Returns a free command from the pool */ struct megasas_cmd *megasas_get_cmd(struct megasas_instance *instance) { unsigned long flags; struct megasas_cmd *cmd = NULL; spin_lock_irqsave(&instance->mfi_pool_lock, flags); if (!list_empty(&instance->cmd_pool)) { cmd = list_entry((&instance->cmd_pool)->next, struct megasas_cmd, list); list_del_init(&cmd->list); } else { dev_err(&instance->pdev->dev, "Command pool empty!\n"); } spin_unlock_irqrestore(&instance->mfi_pool_lock, flags); return cmd; } /** * megasas_return_cmd - Return a cmd to free command pool * @instance: Adapter soft state * @cmd: Command packet to be returned to free command pool */ void megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { unsigned long flags; u32 blk_tags; struct megasas_cmd_fusion *cmd_fusion; struct fusion_context *fusion = instance->ctrl_context; /* This flag is used only for fusion adapter. * Wait for Interrupt for Polled mode DCMD */ if (cmd->flags & DRV_DCMD_POLLED_MODE) return; spin_lock_irqsave(&instance->mfi_pool_lock, flags); if (fusion) { blk_tags = instance->max_scsi_cmds + cmd->index; cmd_fusion = fusion->cmd_list[blk_tags]; megasas_return_cmd_fusion(instance, cmd_fusion); } cmd->scmd = NULL; cmd->frame_count = 0; cmd->flags = 0; memset(cmd->frame, 0, instance->mfi_frame_size); cmd->frame->io.context = cpu_to_le32(cmd->index); if (!fusion && reset_devices) cmd->frame->hdr.cmd = MFI_CMD_INVALID; list_add(&cmd->list, (&instance->cmd_pool)->next); spin_unlock_irqrestore(&instance->mfi_pool_lock, flags); } static const char * format_timestamp(uint32_t timestamp) { static char buffer[32]; if ((timestamp & 0xff000000) == 0xff000000) snprintf(buffer, sizeof(buffer), "boot + %us", timestamp & 0x00ffffff); else snprintf(buffer, sizeof(buffer), "%us", timestamp); return buffer; } static const char * format_class(int8_t class) { static char buffer[6]; switch (class) { case MFI_EVT_CLASS_DEBUG: return "debug"; case MFI_EVT_CLASS_PROGRESS: return "progress"; case MFI_EVT_CLASS_INFO: return "info"; case MFI_EVT_CLASS_WARNING: return "WARN"; case MFI_EVT_CLASS_CRITICAL: return "CRIT"; case MFI_EVT_CLASS_FATAL: return "FATAL"; case MFI_EVT_CLASS_DEAD: return "DEAD"; default: snprintf(buffer, sizeof(buffer), "%d", class); return buffer; } } /** * megasas_decode_evt: Decode FW AEN event and print critical event * for information. * @instance: Adapter soft state */ static void megasas_decode_evt(struct megasas_instance *instance) { struct megasas_evt_detail *evt_detail = instance->evt_detail; union megasas_evt_class_locale class_locale; class_locale.word = le32_to_cpu(evt_detail->cl.word); if (class_locale.members.class >= MFI_EVT_CLASS_CRITICAL) dev_info(&instance->pdev->dev, "%d (%s/0x%04x/%s) - %s\n", le32_to_cpu(evt_detail->seq_num), format_timestamp(le32_to_cpu(evt_detail->time_stamp)), (class_locale.members.locale), format_class(class_locale.members.class), evt_detail->description); } /** * The following functions are defined for xscale * (deviceid : 1064R, PERC5) controllers */ /** * megasas_enable_intr_xscale - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_xscale(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; regs = instance->reg_set; writel(0, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_xscale -Disables interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_xscale(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; u32 mask = 0x1f; regs = instance->reg_set; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_xscale - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_xscale(struct megasas_instance *instance) { return readl(&instance->reg_set->outbound_msg_0); } /** * megasas_clear_interrupt_xscale - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_xscale(struct megasas_instance *instance) { u32 status; u32 mfiStatus = 0; struct megasas_register_set __iomem *regs; regs = instance->reg_set; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (status & MFI_OB_INTR_STATUS_MASK) mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT) mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; /* * Clear the interrupt by writing back the same value */ if (mfiStatus) writel(status, &regs->outbound_intr_status); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_status); return mfiStatus; } /** * megasas_fire_cmd_xscale - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_xscale(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel((frame_phys_addr >> 3)|(frame_count), &(regs)->inbound_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_adp_reset_xscale - For controller reset * @regs: MFI register set */ static int megasas_adp_reset_xscale(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { u32 i; u32 pcidata; writel(MFI_ADP_RESET, &regs->inbound_doorbell); for (i = 0; i < 3; i++) msleep(1000); /* sleep for 3 secs */ pcidata = 0; pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata); dev_notice(&instance->pdev->dev, "pcidata = %x\n", pcidata); if (pcidata & 0x2) { dev_notice(&instance->pdev->dev, "mfi 1068 offset read=%x\n", pcidata); pcidata &= ~0x2; pci_write_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, pcidata); for (i = 0; i < 2; i++) msleep(1000); /* need to wait 2 secs again */ pcidata = 0; pci_read_config_dword(instance->pdev, MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata); dev_notice(&instance->pdev->dev, "1068 offset handshake read=%x\n", pcidata); if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) { dev_notice(&instance->pdev->dev, "1068 offset pcidt=%x\n", pcidata); pcidata = 0; pci_write_config_dword(instance->pdev, MFI_1068_FW_HANDSHAKE_OFFSET, pcidata); } } return 0; } /** * megasas_check_reset_xscale - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_xscale(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if ((atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) && (le32_to_cpu(*instance->consumer) == MEGASAS_ADPRESET_INPROG_SIGN)) return 1; return 0; } static struct megasas_instance_template megasas_instance_template_xscale = { .fire_cmd = megasas_fire_cmd_xscale, .enable_intr = megasas_enable_intr_xscale, .disable_intr = megasas_disable_intr_xscale, .clear_intr = megasas_clear_intr_xscale, .read_fw_status_reg = megasas_read_fw_status_reg_xscale, .adp_reset = megasas_adp_reset_xscale, .check_reset = megasas_check_reset_xscale, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * This is the end of set of functions & definitions specific * to xscale (deviceid : 1064R, PERC5) controllers */ /** * The following functions are defined for ppc (deviceid : 0x60) * controllers */ /** * megasas_enable_intr_ppc - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_ppc(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; regs = instance->reg_set; writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear); writel(~0x80000000, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_ppc - Disable interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_ppc(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; u32 mask = 0xFFFFFFFF; regs = instance->reg_set; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_ppc - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_ppc(struct megasas_instance *instance) { return readl(&instance->reg_set->outbound_scratch_pad_0); } /** * megasas_clear_interrupt_ppc - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_ppc(struct megasas_instance *instance) { u32 status, mfiStatus = 0; struct megasas_register_set __iomem *regs; regs = instance->reg_set; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT) mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; /* * Clear the interrupt by writing back the same value */ writel(status, &regs->outbound_doorbell_clear); /* Dummy readl to force pci flush */ readl(&regs->outbound_doorbell_clear); return mfiStatus; } /** * megasas_fire_cmd_ppc - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_ppc(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel((frame_phys_addr | (frame_count<<1))|1, &(regs)->inbound_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_check_reset_ppc - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_ppc(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) return 1; return 0; } static struct megasas_instance_template megasas_instance_template_ppc = { .fire_cmd = megasas_fire_cmd_ppc, .enable_intr = megasas_enable_intr_ppc, .disable_intr = megasas_disable_intr_ppc, .clear_intr = megasas_clear_intr_ppc, .read_fw_status_reg = megasas_read_fw_status_reg_ppc, .adp_reset = megasas_adp_reset_xscale, .check_reset = megasas_check_reset_ppc, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * megasas_enable_intr_skinny - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_skinny(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; regs = instance->reg_set; writel(0xFFFFFFFF, &(regs)->outbound_intr_mask); writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_skinny - Disables interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_skinny(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; u32 mask = 0xFFFFFFFF; regs = instance->reg_set; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_skinny - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_skinny(struct megasas_instance *instance) { return readl(&instance->reg_set->outbound_scratch_pad_0); } /** * megasas_clear_interrupt_skinny - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_skinny(struct megasas_instance *instance) { u32 status; u32 mfiStatus = 0; struct megasas_register_set __iomem *regs; regs = instance->reg_set; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) { return 0; } /* * Check if it is our interrupt */ if ((megasas_read_fw_status_reg_skinny(instance) & MFI_STATE_MASK) == MFI_STATE_FAULT) { mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; } else mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; /* * Clear the interrupt by writing back the same value */ writel(status, &regs->outbound_intr_status); /* * dummy read to flush PCI */ readl(&regs->outbound_intr_status); return mfiStatus; } /** * megasas_fire_cmd_skinny - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_skinny(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel(upper_32_bits(frame_phys_addr), &(regs)->inbound_high_queue_port); writel((lower_32_bits(frame_phys_addr) | (frame_count<<1))|1, &(regs)->inbound_low_queue_port); mmiowb(); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_check_reset_skinny - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_skinny(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) return 1; return 0; } static struct megasas_instance_template megasas_instance_template_skinny = { .fire_cmd = megasas_fire_cmd_skinny, .enable_intr = megasas_enable_intr_skinny, .disable_intr = megasas_disable_intr_skinny, .clear_intr = megasas_clear_intr_skinny, .read_fw_status_reg = megasas_read_fw_status_reg_skinny, .adp_reset = megasas_adp_reset_gen2, .check_reset = megasas_check_reset_skinny, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * The following functions are defined for gen2 (deviceid : 0x78 0x79) * controllers */ /** * megasas_enable_intr_gen2 - Enables interrupts * @regs: MFI register set */ static inline void megasas_enable_intr_gen2(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; regs = instance->reg_set; writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear); /* write ~0x00000005 (4 & 1) to the intr mask*/ writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_disable_intr_gen2 - Disables interrupt * @regs: MFI register set */ static inline void megasas_disable_intr_gen2(struct megasas_instance *instance) { struct megasas_register_set __iomem *regs; u32 mask = 0xFFFFFFFF; regs = instance->reg_set; writel(mask, &regs->outbound_intr_mask); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_mask); } /** * megasas_read_fw_status_reg_gen2 - returns the current FW status value * @regs: MFI register set */ static u32 megasas_read_fw_status_reg_gen2(struct megasas_instance *instance) { return readl(&instance->reg_set->outbound_scratch_pad_0); } /** * megasas_clear_interrupt_gen2 - Check & clear interrupt * @regs: MFI register set */ static int megasas_clear_intr_gen2(struct megasas_instance *instance) { u32 status; u32 mfiStatus = 0; struct megasas_register_set __iomem *regs; regs = instance->reg_set; /* * Check if it is our interrupt */ status = readl(&regs->outbound_intr_status); if (status & MFI_INTR_FLAG_REPLY_MESSAGE) { mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE; } if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) { mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE; } /* * Clear the interrupt by writing back the same value */ if (mfiStatus) writel(status, &regs->outbound_doorbell_clear); /* Dummy readl to force pci flush */ readl(&regs->outbound_intr_status); return mfiStatus; } /** * megasas_fire_cmd_gen2 - Sends command to the FW * @frame_phys_addr : Physical address of cmd * @frame_count : Number of frames for the command * @regs : MFI register set */ static inline void megasas_fire_cmd_gen2(struct megasas_instance *instance, dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs) { unsigned long flags; spin_lock_irqsave(&instance->hba_lock, flags); writel((frame_phys_addr | (frame_count<<1))|1, &(regs)->inbound_queue_port); spin_unlock_irqrestore(&instance->hba_lock, flags); } /** * megasas_adp_reset_gen2 - For controller reset * @regs: MFI register set */ static int megasas_adp_reset_gen2(struct megasas_instance *instance, struct megasas_register_set __iomem *reg_set) { u32 retry = 0 ; u32 HostDiag; u32 __iomem *seq_offset = &reg_set->seq_offset; u32 __iomem *hostdiag_offset = &reg_set->host_diag; if (instance->instancet == &megasas_instance_template_skinny) { seq_offset = &reg_set->fusion_seq_offset; hostdiag_offset = &reg_set->fusion_host_diag; } writel(0, seq_offset); writel(4, seq_offset); writel(0xb, seq_offset); writel(2, seq_offset); writel(7, seq_offset); writel(0xd, seq_offset); msleep(1000); HostDiag = (u32)readl(hostdiag_offset); while (!(HostDiag & DIAG_WRITE_ENABLE)) { msleep(100); HostDiag = (u32)readl(hostdiag_offset); dev_notice(&instance->pdev->dev, "RESETGEN2: retry=%x, hostdiag=%x\n", retry, HostDiag); if (retry++ >= 100) return 1; } dev_notice(&instance->pdev->dev, "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag); writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset); ssleep(10); HostDiag = (u32)readl(hostdiag_offset); while (HostDiag & DIAG_RESET_ADAPTER) { msleep(100); HostDiag = (u32)readl(hostdiag_offset); dev_notice(&instance->pdev->dev, "RESET_GEN2: retry=%x, hostdiag=%x\n", retry, HostDiag); if (retry++ >= 1000) return 1; } return 0; } /** * megasas_check_reset_gen2 - For controller reset check * @regs: MFI register set */ static int megasas_check_reset_gen2(struct megasas_instance *instance, struct megasas_register_set __iomem *regs) { if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) return 1; return 0; } static struct megasas_instance_template megasas_instance_template_gen2 = { .fire_cmd = megasas_fire_cmd_gen2, .enable_intr = megasas_enable_intr_gen2, .disable_intr = megasas_disable_intr_gen2, .clear_intr = megasas_clear_intr_gen2, .read_fw_status_reg = megasas_read_fw_status_reg_gen2, .adp_reset = megasas_adp_reset_gen2, .check_reset = megasas_check_reset_gen2, .service_isr = megasas_isr, .tasklet = megasas_complete_cmd_dpc, .init_adapter = megasas_init_adapter_mfi, .build_and_issue_cmd = megasas_build_and_issue_cmd, .issue_dcmd = megasas_issue_dcmd, }; /** * This is the end of set of functions & definitions * specific to gen2 (deviceid : 0x78, 0x79) controllers */ /* * Template added for TB (Fusion) */ extern struct megasas_instance_template megasas_instance_template_fusion; /** * megasas_issue_polled - Issues a polling command * @instance: Adapter soft state * @cmd: Command packet to be issued * * For polling, MFI requires the cmd_status to be set to MFI_STAT_INVALID_STATUS before posting. */ int megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd) { struct megasas_header *frame_hdr = &cmd->frame->hdr; frame_hdr->cmd_status = MFI_STAT_INVALID_STATUS; frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE); if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_err(&instance->pdev->dev, "Failed from %s %d\n", __func__, __LINE__); return DCMD_NOT_FIRED; } instance->instancet->issue_dcmd(instance, cmd); return wait_and_poll(instance, cmd, instance->requestorId ? MEGASAS_ROUTINE_WAIT_TIME_VF : MFI_IO_TIMEOUT_SECS); } /** * megasas_issue_blocked_cmd - Synchronous wrapper around regular FW cmds * @instance: Adapter soft state * @cmd: Command to be issued * @timeout: Timeout in seconds * * This function waits on an event for the command to be returned from ISR. * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs * Used to issue ioctl commands. */ int megasas_issue_blocked_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd, int timeout) { int ret = 0; cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_err(&instance->pdev->dev, "Failed from %s %d\n", __func__, __LINE__); return DCMD_NOT_FIRED; } instance->instancet->issue_dcmd(instance, cmd); if (timeout) { ret = wait_event_timeout(instance->int_cmd_wait_q, cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS, timeout * HZ); if (!ret) { dev_err(&instance->pdev->dev, "Failed from %s %d DCMD Timed out\n", __func__, __LINE__); return DCMD_TIMEOUT; } } else wait_event(instance->int_cmd_wait_q, cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS); return (cmd->cmd_status_drv == MFI_STAT_OK) ? DCMD_SUCCESS : DCMD_FAILED; } /** * megasas_issue_blocked_abort_cmd - Aborts previously issued cmd * @instance: Adapter soft state * @cmd_to_abort: Previously issued cmd to be aborted * @timeout: Timeout in seconds * * MFI firmware can abort previously issued AEN comamnd (automatic event * notification). The megasas_issue_blocked_abort_cmd() issues such abort * cmd and waits for return status. * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs */ static int megasas_issue_blocked_abort_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd_to_abort, int timeout) { struct megasas_cmd *cmd; struct megasas_abort_frame *abort_fr; int ret = 0; cmd = megasas_get_cmd(instance); if (!cmd) return -1; abort_fr = &cmd->frame->abort; /* * Prepare and issue the abort frame */ abort_fr->cmd = MFI_CMD_ABORT; abort_fr->cmd_status = MFI_STAT_INVALID_STATUS; abort_fr->flags = cpu_to_le16(0); abort_fr->abort_context = cpu_to_le32(cmd_to_abort->index); abort_fr->abort_mfi_phys_addr_lo = cpu_to_le32(lower_32_bits(cmd_to_abort->frame_phys_addr)); abort_fr->abort_mfi_phys_addr_hi = cpu_to_le32(upper_32_bits(cmd_to_abort->frame_phys_addr)); cmd->sync_cmd = 1; cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_err(&instance->pdev->dev, "Failed from %s %d\n", __func__, __LINE__); return DCMD_NOT_FIRED; } instance->instancet->issue_dcmd(instance, cmd); if (timeout) { ret = wait_event_timeout(instance->abort_cmd_wait_q, cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS, timeout * HZ); if (!ret) { dev_err(&instance->pdev->dev, "Failed from %s %d Abort Timed out\n", __func__, __LINE__); return DCMD_TIMEOUT; } } else wait_event(instance->abort_cmd_wait_q, cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS); cmd->sync_cmd = 0; megasas_return_cmd(instance, cmd); return (cmd->cmd_status_drv == MFI_STAT_OK) ? DCMD_SUCCESS : DCMD_FAILED; } /** * megasas_make_sgl32 - Prepares 32-bit SGL * @instance: Adapter soft state * @scp: SCSI command from the mid-layer * @mfi_sgl: SGL to be filled in * * If successful, this function returns the number of SG elements. Otherwise, * it returnes -1. */ static int megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl) { int i; int sge_count; struct scatterlist *os_sgl; sge_count = scsi_dma_map(scp); BUG_ON(sge_count < 0); if (sge_count) { scsi_for_each_sg(scp, os_sgl, sge_count, i) { mfi_sgl->sge32[i].length = cpu_to_le32(sg_dma_len(os_sgl)); mfi_sgl->sge32[i].phys_addr = cpu_to_le32(sg_dma_address(os_sgl)); } } return sge_count; } /** * megasas_make_sgl64 - Prepares 64-bit SGL * @instance: Adapter soft state * @scp: SCSI command from the mid-layer * @mfi_sgl: SGL to be filled in * * If successful, this function returns the number of SG elements. Otherwise, * it returnes -1. */ static int megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl) { int i; int sge_count; struct scatterlist *os_sgl; sge_count = scsi_dma_map(scp); BUG_ON(sge_count < 0); if (sge_count) { scsi_for_each_sg(scp, os_sgl, sge_count, i) { mfi_sgl->sge64[i].length = cpu_to_le32(sg_dma_len(os_sgl)); mfi_sgl->sge64[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl)); } } return sge_count; } /** * megasas_make_sgl_skinny - Prepares IEEE SGL * @instance: Adapter soft state * @scp: SCSI command from the mid-layer * @mfi_sgl: SGL to be filled in * * If successful, this function returns the number of SG elements. Otherwise, * it returnes -1. */ static int megasas_make_sgl_skinny(struct megasas_instance *instance, struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl) { int i; int sge_count; struct scatterlist *os_sgl; sge_count = scsi_dma_map(scp); if (sge_count) { scsi_for_each_sg(scp, os_sgl, sge_count, i) { mfi_sgl->sge_skinny[i].length = cpu_to_le32(sg_dma_len(os_sgl)); mfi_sgl->sge_skinny[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl)); mfi_sgl->sge_skinny[i].flag = cpu_to_le32(0); } } return sge_count; } /** * megasas_get_frame_count - Computes the number of frames * @frame_type : type of frame- io or pthru frame * @sge_count : number of sg elements * * Returns the number of frames required for numnber of sge's (sge_count) */ static u32 megasas_get_frame_count(struct megasas_instance *instance, u8 sge_count, u8 frame_type) { int num_cnt; int sge_bytes; u32 sge_sz; u32 frame_count = 0; sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) : sizeof(struct megasas_sge32); if (instance->flag_ieee) { sge_sz = sizeof(struct megasas_sge_skinny); } /* * Main frame can contain 2 SGEs for 64-bit SGLs and * 3 SGEs for 32-bit SGLs for ldio & * 1 SGEs for 64-bit SGLs and * 2 SGEs for 32-bit SGLs for pthru frame */ if (unlikely(frame_type == PTHRU_FRAME)) { if (instance->flag_ieee == 1) { num_cnt = sge_count - 1; } else if (IS_DMA64) num_cnt = sge_count - 1; else num_cnt = sge_count - 2; } else { if (instance->flag_ieee == 1) { num_cnt = sge_count - 1; } else if (IS_DMA64) num_cnt = sge_count - 2; else num_cnt = sge_count - 3; } if (num_cnt > 0) { sge_bytes = sge_sz * num_cnt; frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) + ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ; } /* Main frame */ frame_count += 1; if (frame_count > 7) frame_count = 8; return frame_count; } /** * megasas_build_dcdb - Prepares a direct cdb (DCDB) command * @instance: Adapter soft state * @scp: SCSI command * @cmd: Command to be prepared in * * This function prepares CDB commands. These are typcially pass-through * commands to the devices. */ static int megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp, struct megasas_cmd *cmd) { u32 is_logical; u32 device_id; u16 flags = 0; struct megasas_pthru_frame *pthru; is_logical = MEGASAS_IS_LOGICAL(scp->device); device_id = MEGASAS_DEV_INDEX(scp); pthru = (struct megasas_pthru_frame *)cmd->frame; if (scp->sc_data_direction == DMA_TO_DEVICE) flags = MFI_FRAME_DIR_WRITE; else if (scp->sc_data_direction == DMA_FROM_DEVICE) flags = MFI_FRAME_DIR_READ; else if (scp->sc_data_direction == DMA_NONE) flags = MFI_FRAME_DIR_NONE; if (instance->flag_ieee == 1) { flags |= MFI_FRAME_IEEE; } /* * Prepare the DCDB frame */ pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO; pthru->cmd_status = 0x0; pthru->scsi_status = 0x0; pthru->target_id = device_id; pthru->lun = scp->device->lun; pthru->cdb_len = scp->cmd_len; pthru->timeout = 0; pthru->pad_0 = 0; pthru->flags = cpu_to_le16(flags); pthru->data_xfer_len = cpu_to_le32(scsi_bufflen(scp)); memcpy(pthru->cdb, scp->cmnd, scp->cmd_len); /* * If the command is for the tape device, set the * pthru timeout to the os layer timeout value. */ if (scp->device->type == TYPE_TAPE) { if ((scp->request->timeout / HZ) > 0xFFFF) pthru->timeout = cpu_to_le16(0xFFFF); else pthru->timeout = cpu_to_le16(scp->request->timeout / HZ); } /* * Construct SGL */ if (instance->flag_ieee == 1) { pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64); pthru->sge_count = megasas_make_sgl_skinny(instance, scp, &pthru->sgl); } else if (IS_DMA64) { pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64); pthru->sge_count = megasas_make_sgl64(instance, scp, &pthru->sgl); } else pthru->sge_count = megasas_make_sgl32(instance, scp, &pthru->sgl); if (pthru->sge_count > instance->max_num_sge) { dev_err(&instance->pdev->dev, "DCDB too many SGE NUM=%x\n", pthru->sge_count); return 0; } /* * Sense info specific */ pthru->sense_len = SCSI_SENSE_BUFFERSIZE; pthru->sense_buf_phys_addr_hi = cpu_to_le32(upper_32_bits(cmd->sense_phys_addr)); pthru->sense_buf_phys_addr_lo = cpu_to_le32(lower_32_bits(cmd->sense_phys_addr)); /* * Compute the total number of frames this command consumes. FW uses * this number to pull sufficient number of frames from host memory. */ cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count, PTHRU_FRAME); return cmd->frame_count; } /** * megasas_build_ldio - Prepares IOs to logical devices * @instance: Adapter soft state * @scp: SCSI command * @cmd: Command to be prepared * * Frames (and accompanying SGLs) for regular SCSI IOs use this function. */ static int megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp, struct megasas_cmd *cmd) { u32 device_id; u8 sc = scp->cmnd[0]; u16 flags = 0; struct megasas_io_frame *ldio; device_id = MEGASAS_DEV_INDEX(scp); ldio = (struct megasas_io_frame *)cmd->frame; if (scp->sc_data_direction == DMA_TO_DEVICE) flags = MFI_FRAME_DIR_WRITE; else if (scp->sc_data_direction == DMA_FROM_DEVICE) flags = MFI_FRAME_DIR_READ; if (instance->flag_ieee == 1) { flags |= MFI_FRAME_IEEE; } /* * Prepare the Logical IO frame: 2nd bit is zero for all read cmds */ ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ; ldio->cmd_status = 0x0; ldio->scsi_status = 0x0; ldio->target_id = device_id; ldio->timeout = 0; ldio->reserved_0 = 0; ldio->pad_0 = 0; ldio->flags = cpu_to_le16(flags); ldio->start_lba_hi = 0; ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0; /* * 6-byte READ(0x08) or WRITE(0x0A) cdb */ if (scp->cmd_len == 6) { ldio->lba_count = cpu_to_le32((u32) scp->cmnd[4]); ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[1] << 16) | ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3]); ldio->start_lba_lo &= cpu_to_le32(0x1FFFFF); } /* * 10-byte READ(0x28) or WRITE(0x2A) cdb */ else if (scp->cmd_len == 10) { ldio->lba_count = cpu_to_le32((u32) scp->cmnd[8] | ((u32) scp->cmnd[7] << 8)); ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) | ((u32) scp->cmnd[3] << 16) | ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5]); } /* * 12-byte READ(0xA8) or WRITE(0xAA) cdb */ else if (scp->cmd_len == 12) { ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[6] << 24) | ((u32) scp->cmnd[7] << 16) | ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9]); ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) | ((u32) scp->cmnd[3] << 16) | ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5]); } /* * 16-byte READ(0x88) or WRITE(0x8A) cdb */ else if (scp->cmd_len == 16) { ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[10] << 24) | ((u32) scp->cmnd[11] << 16) | ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13]); ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[6] << 24) | ((u32) scp->cmnd[7] << 16) | ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9]); ldio->start_lba_hi = cpu_to_le32(((u32) scp->cmnd[2] << 24) | ((u32) scp->cmnd[3] << 16) | ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5]); } /* * Construct SGL */ if (instance->flag_ieee) { ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64); ldio->sge_count = megasas_make_sgl_skinny(instance, scp, &ldio->sgl); } else if (IS_DMA64) { ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64); ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl); } else ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl); if (ldio->sge_count > instance->max_num_sge) { dev_err(&instance->pdev->dev, "build_ld_io: sge_count = %x\n", ldio->sge_count); return 0; } /* * Sense info specific */ ldio->sense_len = SCSI_SENSE_BUFFERSIZE; ldio->sense_buf_phys_addr_hi = 0; ldio->sense_buf_phys_addr_lo = cpu_to_le32(cmd->sense_phys_addr); /* * Compute the total number of frames this command consumes. FW uses * this number to pull sufficient number of frames from host memory. */ cmd->frame_count = megasas_get_frame_count(instance, ldio->sge_count, IO_FRAME); return cmd->frame_count; } /** * megasas_cmd_type - Checks if the cmd is for logical drive/sysPD * and whether it's RW or non RW * @scmd: SCSI command * */ inline int megasas_cmd_type(struct scsi_cmnd *cmd) { int ret; switch (cmd->cmnd[0]) { case READ_10: case WRITE_10: case READ_12: case WRITE_12: case READ_6: case WRITE_6: case READ_16: case WRITE_16: ret = (MEGASAS_IS_LOGICAL(cmd->device)) ? READ_WRITE_LDIO : READ_WRITE_SYSPDIO; break; default: ret = (MEGASAS_IS_LOGICAL(cmd->device)) ? NON_READ_WRITE_LDIO : NON_READ_WRITE_SYSPDIO; } return ret; } /** * megasas_dump_pending_frames - Dumps the frame address of all pending cmds * in FW * @instance: Adapter soft state */ static inline void megasas_dump_pending_frames(struct megasas_instance *instance) { struct megasas_cmd *cmd; int i,n; union megasas_sgl *mfi_sgl; struct megasas_io_frame *ldio; struct megasas_pthru_frame *pthru; u32 sgcount; u16 max_cmd = instance->max_fw_cmds; dev_err(&instance->pdev->dev, "[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no); dev_err(&instance->pdev->dev, "[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding)); if (IS_DMA64) dev_err(&instance->pdev->dev, "[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no); else dev_err(&instance->pdev->dev, "[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no); dev_err(&instance->pdev->dev, "[%d]: Pending OS cmds in FW : \n",instance->host->host_no); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (!cmd->scmd) continue; dev_err(&instance->pdev->dev, "[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr); if (megasas_cmd_type(cmd->scmd) == READ_WRITE_LDIO) { ldio = (struct megasas_io_frame *)cmd->frame; mfi_sgl = &ldio->sgl; sgcount = ldio->sge_count; dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x," " lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n", instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id, le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi), le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount); } else { pthru = (struct megasas_pthru_frame *) cmd->frame; mfi_sgl = &pthru->sgl; sgcount = pthru->sge_count; dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, " "lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n", instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id, pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len), le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount); } if (megasas_dbg_lvl & MEGASAS_DBG_LVL) { for (n = 0; n < sgcount; n++) { if (IS_DMA64) dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%llx\n", le32_to_cpu(mfi_sgl->sge64[n].length), le64_to_cpu(mfi_sgl->sge64[n].phys_addr)); else dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%x\n", le32_to_cpu(mfi_sgl->sge32[n].length), le32_to_cpu(mfi_sgl->sge32[n].phys_addr)); } } } /*for max_cmd*/ dev_err(&instance->pdev->dev, "[%d]: Pending Internal cmds in FW : \n",instance->host->host_no); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (cmd->sync_cmd == 1) dev_err(&instance->pdev->dev, "0x%08lx : ", (unsigned long)cmd->frame_phys_addr); } dev_err(&instance->pdev->dev, "[%d]: Dumping Done\n\n",instance->host->host_no); } u32 megasas_build_and_issue_cmd(struct megasas_instance *instance, struct scsi_cmnd *scmd) { struct megasas_cmd *cmd; u32 frame_count; cmd = megasas_get_cmd(instance); if (!cmd) return SCSI_MLQUEUE_HOST_BUSY; /* * Logical drive command */ if (megasas_cmd_type(scmd) == READ_WRITE_LDIO) frame_count = megasas_build_ldio(instance, scmd, cmd); else frame_count = megasas_build_dcdb(instance, scmd, cmd); if (!frame_count) goto out_return_cmd; cmd->scmd = scmd; scmd->SCp.ptr = (char *)cmd; /* * Issue the command to the FW */ atomic_inc(&instance->fw_outstanding); instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, cmd->frame_count-1, instance->reg_set); return 0; out_return_cmd: megasas_return_cmd(instance, cmd); return SCSI_MLQUEUE_HOST_BUSY; } /** * megasas_queue_command - Queue entry point * @scmd: SCSI command to be queued * @done: Callback entry point */ static int megasas_queue_command(struct Scsi_Host *shost, struct scsi_cmnd *scmd) { struct megasas_instance *instance; struct MR_PRIV_DEVICE *mr_device_priv_data; instance = (struct megasas_instance *) scmd->device->host->hostdata; if (instance->unload == 1) { scmd->result = DID_NO_CONNECT << 16; scmd->scsi_done(scmd); return 0; } if (instance->issuepend_done == 0) return SCSI_MLQUEUE_HOST_BUSY; /* Check for an mpio path and adjust behavior */ if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) { if (megasas_check_mpio_paths(instance, scmd) == (DID_REQUEUE << 16)) { return SCSI_MLQUEUE_HOST_BUSY; } else { scmd->result = DID_NO_CONNECT << 16; scmd->scsi_done(scmd); return 0; } } if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { scmd->result = DID_NO_CONNECT << 16; scmd->scsi_done(scmd); return 0; } mr_device_priv_data = scmd->device->hostdata; if (!mr_device_priv_data) { scmd->result = DID_NO_CONNECT << 16; scmd->scsi_done(scmd); return 0; } if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) return SCSI_MLQUEUE_HOST_BUSY; if (mr_device_priv_data->tm_busy) return SCSI_MLQUEUE_DEVICE_BUSY; scmd->result = 0; if (MEGASAS_IS_LOGICAL(scmd->device) && (scmd->device->id >= instance->fw_supported_vd_count || scmd->device->lun)) { scmd->result = DID_BAD_TARGET << 16; goto out_done; } if ((scmd->cmnd[0] == SYNCHRONIZE_CACHE) && MEGASAS_IS_LOGICAL(scmd->device) && (!instance->fw_sync_cache_support)) { scmd->result = DID_OK << 16; goto out_done; } return instance->instancet->build_and_issue_cmd(instance, scmd); out_done: scmd->scsi_done(scmd); return 0; } static struct megasas_instance *megasas_lookup_instance(u16 host_no) { int i; for (i = 0; i < megasas_mgmt_info.max_index; i++) { if ((megasas_mgmt_info.instance[i]) && (megasas_mgmt_info.instance[i]->host->host_no == host_no)) return megasas_mgmt_info.instance[i]; } return NULL; } /* * megasas_set_dynamic_target_properties - * Device property set by driver may not be static and it is required to be * updated after OCR * * set tm_capable. * set dma alignment (only for eedp protection enable vd). * * @sdev: OS provided scsi device * * Returns void */ void megasas_set_dynamic_target_properties(struct scsi_device *sdev, bool is_target_prop) { u16 pd_index = 0, ld; u32 device_id; struct megasas_instance *instance; struct fusion_context *fusion; struct MR_PRIV_DEVICE *mr_device_priv_data; struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync; struct MR_LD_RAID *raid; struct MR_DRV_RAID_MAP_ALL *local_map_ptr; instance = megasas_lookup_instance(sdev->host->host_no); fusion = instance->ctrl_context; mr_device_priv_data = sdev->hostdata; if (!fusion || !mr_device_priv_data) return; if (MEGASAS_IS_LOGICAL(sdev)) { device_id = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)]; ld = MR_TargetIdToLdGet(device_id, local_map_ptr); if (ld >= instance->fw_supported_vd_count) return; raid = MR_LdRaidGet(ld, local_map_ptr); if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER) blk_queue_update_dma_alignment(sdev->request_queue, 0x7); mr_device_priv_data->is_tm_capable = raid->capability.tmCapable; } else if (instance->use_seqnum_jbod_fp) { pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; pd_sync = (void *)fusion->pd_seq_sync [(instance->pd_seq_map_id - 1) & 1]; mr_device_priv_data->is_tm_capable = pd_sync->seq[pd_index].capability.tmCapable; } if (is_target_prop && instance->tgt_prop->reset_tmo) { /* * If FW provides a target reset timeout value, driver will use * it. If not set, fallback to default values. */ mr_device_priv_data->target_reset_tmo = min_t(u8, instance->max_reset_tmo, instance->tgt_prop->reset_tmo); mr_device_priv_data->task_abort_tmo = instance->task_abort_tmo; } else { mr_device_priv_data->target_reset_tmo = MEGASAS_DEFAULT_TM_TIMEOUT; mr_device_priv_data->task_abort_tmo = MEGASAS_DEFAULT_TM_TIMEOUT; } } /* * megasas_set_nvme_device_properties - * set nomerges=2 * set virtual page boundary = 4K (current mr_nvme_pg_size is 4K). * set maximum io transfer = MDTS of NVME device provided by MR firmware. * * MR firmware provides value in KB. Caller of this function converts * kb into bytes. * * e.a MDTS=5 means 2^5 * nvme page size. (In case of 4K page size, * MR firmware provides value 128 as (32 * 4K) = 128K. * * @sdev: scsi device * @max_io_size: maximum io transfer size * */ static inline void megasas_set_nvme_device_properties(struct scsi_device *sdev, u32 max_io_size) { struct megasas_instance *instance; u32 mr_nvme_pg_size; instance = (struct megasas_instance *)sdev->host->hostdata; mr_nvme_pg_size = max_t(u32, instance->nvme_page_size, MR_DEFAULT_NVME_PAGE_SIZE); blk_queue_max_hw_sectors(sdev->request_queue, (max_io_size / 512)); blk_queue_flag_set(QUEUE_FLAG_NOMERGES, sdev->request_queue); blk_queue_virt_boundary(sdev->request_queue, mr_nvme_pg_size - 1); } /* * megasas_set_static_target_properties - * Device property set by driver are static and it is not required to be * updated after OCR. * * set io timeout * set device queue depth * set nvme device properties. see - megasas_set_nvme_device_properties * * @sdev: scsi device * @is_target_prop true, if fw provided target properties. */ static void megasas_set_static_target_properties(struct scsi_device *sdev, bool is_target_prop) { u16 target_index = 0; u8 interface_type; u32 device_qd = MEGASAS_DEFAULT_CMD_PER_LUN; u32 max_io_size_kb = MR_DEFAULT_NVME_MDTS_KB; u32 tgt_device_qd; struct megasas_instance *instance; struct MR_PRIV_DEVICE *mr_device_priv_data; instance = megasas_lookup_instance(sdev->host->host_no); mr_device_priv_data = sdev->hostdata; interface_type = mr_device_priv_data->interface_type; /* * The RAID firmware may require extended timeouts. */ blk_queue_rq_timeout(sdev->request_queue, scmd_timeout * HZ); target_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; switch (interface_type) { case SAS_PD: device_qd = MEGASAS_SAS_QD; break; case SATA_PD: device_qd = MEGASAS_SATA_QD; break; case NVME_PD: device_qd = MEGASAS_NVME_QD; break; } if (is_target_prop) { tgt_device_qd = le32_to_cpu(instance->tgt_prop->device_qdepth); if (tgt_device_qd && (tgt_device_qd <= instance->host->can_queue)) device_qd = tgt_device_qd; /* max_io_size_kb will be set to non zero for * nvme based vd and syspd. */ max_io_size_kb = le32_to_cpu(instance->tgt_prop->max_io_size_kb); } if (instance->nvme_page_size && max_io_size_kb) megasas_set_nvme_device_properties(sdev, (max_io_size_kb << 10)); scsi_change_queue_depth(sdev, device_qd); } static int megasas_slave_configure(struct scsi_device *sdev) { u16 pd_index = 0; struct megasas_instance *instance; int ret_target_prop = DCMD_FAILED; bool is_target_prop = false; instance = megasas_lookup_instance(sdev->host->host_no); if (instance->pd_list_not_supported) { if (!MEGASAS_IS_LOGICAL(sdev) && sdev->type == TYPE_DISK) { pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; if (instance->pd_list[pd_index].driveState != MR_PD_STATE_SYSTEM) return -ENXIO; } } mutex_lock(&instance->reset_mutex); /* Send DCMD to Firmware and cache the information */ if ((instance->pd_info) && !MEGASAS_IS_LOGICAL(sdev)) megasas_get_pd_info(instance, sdev); /* Some ventura firmware may not have instance->nvme_page_size set. * Do not send MR_DCMD_DRV_GET_TARGET_PROP */ if ((instance->tgt_prop) && (instance->nvme_page_size)) ret_target_prop = megasas_get_target_prop(instance, sdev); is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false; megasas_set_static_target_properties(sdev, is_target_prop); /* This sdev property may change post OCR */ megasas_set_dynamic_target_properties(sdev, is_target_prop); mutex_unlock(&instance->reset_mutex); return 0; } static int megasas_slave_alloc(struct scsi_device *sdev) { u16 pd_index = 0; struct megasas_instance *instance ; struct MR_PRIV_DEVICE *mr_device_priv_data; instance = megasas_lookup_instance(sdev->host->host_no); if (!MEGASAS_IS_LOGICAL(sdev)) { /* * Open the OS scan to the SYSTEM PD */ pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; if ((instance->pd_list_not_supported || instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM)) { goto scan_target; } return -ENXIO; } scan_target: mr_device_priv_data = kzalloc(sizeof(*mr_device_priv_data), GFP_KERNEL); if (!mr_device_priv_data) return -ENOMEM; sdev->hostdata = mr_device_priv_data; atomic_set(&mr_device_priv_data->r1_ldio_hint, instance->r1_ldio_hint_default); return 0; } static void megasas_slave_destroy(struct scsi_device *sdev) { kfree(sdev->hostdata); sdev->hostdata = NULL; } /* * megasas_complete_outstanding_ioctls - Complete outstanding ioctls after a * kill adapter * @instance: Adapter soft state * */ static void megasas_complete_outstanding_ioctls(struct megasas_instance *instance) { int i; struct megasas_cmd *cmd_mfi; struct megasas_cmd_fusion *cmd_fusion; struct fusion_context *fusion = instance->ctrl_context; /* Find all outstanding ioctls */ if (fusion) { for (i = 0; i < instance->max_fw_cmds; i++) { cmd_fusion = fusion->cmd_list[i]; if (cmd_fusion->sync_cmd_idx != (u32)ULONG_MAX) { cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx]; if (cmd_mfi->sync_cmd && (cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT)) { cmd_mfi->frame->hdr.cmd_status = MFI_STAT_WRONG_STATE; megasas_complete_cmd(instance, cmd_mfi, DID_OK); } } } } else { for (i = 0; i < instance->max_fw_cmds; i++) { cmd_mfi = instance->cmd_list[i]; if (cmd_mfi->sync_cmd && cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT) megasas_complete_cmd(instance, cmd_mfi, DID_OK); } } } void megaraid_sas_kill_hba(struct megasas_instance *instance) { /* Set critical error to block I/O & ioctls in case caller didn't */ atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR); /* Wait 1 second to ensure IO or ioctls in build have posted */ msleep(1000); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->adapter_type != MFI_SERIES)) { if (!instance->requestorId) { writel(MFI_STOP_ADP, &instance->reg_set->doorbell); /* Flush */ readl(&instance->reg_set->doorbell); } if (instance->requestorId && instance->peerIsPresent) memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS); } else { writel(MFI_STOP_ADP, &instance->reg_set->inbound_doorbell); } /* Complete outstanding ioctls when adapter is killed */ megasas_complete_outstanding_ioctls(instance); } /** * megasas_check_and_restore_queue_depth - Check if queue depth needs to be * restored to max value * @instance: Adapter soft state * */ void megasas_check_and_restore_queue_depth(struct megasas_instance *instance) { unsigned long flags; if (instance->flag & MEGASAS_FW_BUSY && time_after(jiffies, instance->last_time + 5 * HZ) && atomic_read(&instance->fw_outstanding) < instance->throttlequeuedepth + 1) { spin_lock_irqsave(instance->host->host_lock, flags); instance->flag &= ~MEGASAS_FW_BUSY; instance->host->can_queue = instance->cur_can_queue; spin_unlock_irqrestore(instance->host->host_lock, flags); } } /** * megasas_complete_cmd_dpc - Returns FW's controller structure * @instance_addr: Address of adapter soft state * * Tasklet to complete cmds */ static void megasas_complete_cmd_dpc(unsigned long instance_addr) { u32 producer; u32 consumer; u32 context; struct megasas_cmd *cmd; struct megasas_instance *instance = (struct megasas_instance *)instance_addr; unsigned long flags; /* If we have already declared adapter dead, donot complete cmds */ if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) return; spin_lock_irqsave(&instance->completion_lock, flags); producer = le32_to_cpu(*instance->producer); consumer = le32_to_cpu(*instance->consumer); while (consumer != producer) { context = le32_to_cpu(instance->reply_queue[consumer]); if (context >= instance->max_fw_cmds) { dev_err(&instance->pdev->dev, "Unexpected context value %x\n", context); BUG(); } cmd = instance->cmd_list[context]; megasas_complete_cmd(instance, cmd, DID_OK); consumer++; if (consumer == (instance->max_fw_cmds + 1)) { consumer = 0; } } *instance->consumer = cpu_to_le32(producer); spin_unlock_irqrestore(&instance->completion_lock, flags); /* * Check if we can restore can_queue */ megasas_check_and_restore_queue_depth(instance); } static void megasas_sriov_heartbeat_handler(struct timer_list *t); /** * megasas_start_timer - Initializes sriov heartbeat timer object * @instance: Adapter soft state * */ void megasas_start_timer(struct megasas_instance *instance) { struct timer_list *timer = &instance->sriov_heartbeat_timer; timer_setup(timer, megasas_sriov_heartbeat_handler, 0); timer->expires = jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF; add_timer(timer); } static void megasas_internal_reset_defer_cmds(struct megasas_instance *instance); static void process_fw_state_change_wq(struct work_struct *work); void megasas_do_ocr(struct megasas_instance *instance) { if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) || (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) || (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) { *instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN); } instance->instancet->disable_intr(instance); atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT); instance->issuepend_done = 0; atomic_set(&instance->fw_outstanding, 0); megasas_internal_reset_defer_cmds(instance); process_fw_state_change_wq(&instance->work_init); } static int megasas_get_ld_vf_affiliation_111(struct megasas_instance *instance, int initial) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_LD_VF_AFFILIATION_111 *new_affiliation_111 = NULL; dma_addr_t new_affiliation_111_h; int ld, retval = 0; u8 thisVf; cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation_111:" "Failed to get cmd for scsi%d\n", instance->host->host_no); return -ENOMEM; } dcmd = &cmd->frame->dcmd; if (!instance->vf_affiliation_111) { dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF " "affiliation for scsi%d\n", instance->host->host_no); megasas_return_cmd(instance, cmd); return -ENOMEM; } if (initial) memset(instance->vf_affiliation_111, 0, sizeof(struct MR_LD_VF_AFFILIATION_111)); else { new_affiliation_111 = dma_zalloc_coherent(&instance->pdev->dev, sizeof(struct MR_LD_VF_AFFILIATION_111), &new_affiliation_111_h, GFP_KERNEL); if (!new_affiliation_111) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate " "memory for new affiliation for scsi%d\n", instance->host->host_no); megasas_return_cmd(instance, cmd); return -ENOMEM; } } memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH); dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_VF_AFFILIATION_111)); dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS_111); if (initial) dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(instance->vf_affiliation_111_h); else dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(new_affiliation_111_h); dcmd->sgl.sge32[0].length = cpu_to_le32( sizeof(struct MR_LD_VF_AFFILIATION_111)); dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for " "scsi%d\n", instance->host->host_no); if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) { dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD" " failed with status 0x%x for scsi%d\n", dcmd->cmd_status, instance->host->host_no); retval = 1; /* Do a scan if we couldn't get affiliation */ goto out; } if (!initial) { thisVf = new_affiliation_111->thisVf; for (ld = 0 ; ld < new_affiliation_111->vdCount; ld++) if (instance->vf_affiliation_111->map[ld].policy[thisVf] != new_affiliation_111->map[ld].policy[thisVf]) { dev_warn(&instance->pdev->dev, "SR-IOV: " "Got new LD/VF affiliation for scsi%d\n", instance->host->host_no); memcpy(instance->vf_affiliation_111, new_affiliation_111, sizeof(struct MR_LD_VF_AFFILIATION_111)); retval = 1; goto out; } } out: if (new_affiliation_111) { dma_free_coherent(&instance->pdev->dev, sizeof(struct MR_LD_VF_AFFILIATION_111), new_affiliation_111, new_affiliation_111_h); } megasas_return_cmd(instance, cmd); return retval; } static int megasas_get_ld_vf_affiliation_12(struct megasas_instance *instance, int initial) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_LD_VF_AFFILIATION *new_affiliation = NULL; struct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL; dma_addr_t new_affiliation_h; int i, j, retval = 0, found = 0, doscan = 0; u8 thisVf; cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation12: " "Failed to get cmd for scsi%d\n", instance->host->host_no); return -ENOMEM; } dcmd = &cmd->frame->dcmd; if (!instance->vf_affiliation) { dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF " "affiliation for scsi%d\n", instance->host->host_no); megasas_return_cmd(instance, cmd); return -ENOMEM; } if (initial) memset(instance->vf_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION)); else { new_affiliation = dma_zalloc_coherent(&instance->pdev->dev, (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION), &new_affiliation_h, GFP_KERNEL); if (!new_affiliation) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate " "memory for new affiliation for scsi%d\n", instance->host->host_no); megasas_return_cmd(instance, cmd); return -ENOMEM; } } memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH); dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION)); dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS); if (initial) dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(instance->vf_affiliation_h); else dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(new_affiliation_h); dcmd->sgl.sge32[0].length = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION)); dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for " "scsi%d\n", instance->host->host_no); if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) { dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD" " failed with status 0x%x for scsi%d\n", dcmd->cmd_status, instance->host->host_no); retval = 1; /* Do a scan if we couldn't get affiliation */ goto out; } if (!initial) { if (!new_affiliation->ldCount) { dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF " "affiliation for passive path for scsi%d\n", instance->host->host_no); retval = 1; goto out; } newmap = new_affiliation->map; savedmap = instance->vf_affiliation->map; thisVf = new_affiliation->thisVf; for (i = 0 ; i < new_affiliation->ldCount; i++) { found = 0; for (j = 0; j < instance->vf_affiliation->ldCount; j++) { if (newmap->ref.targetId == savedmap->ref.targetId) { found = 1; if (newmap->policy[thisVf] != savedmap->policy[thisVf]) { doscan = 1; goto out; } } savedmap = (struct MR_LD_VF_MAP *) ((unsigned char *)savedmap + savedmap->size); } if (!found && newmap->policy[thisVf] != MR_LD_ACCESS_HIDDEN) { doscan = 1; goto out; } newmap = (struct MR_LD_VF_MAP *) ((unsigned char *)newmap + newmap->size); } newmap = new_affiliation->map; savedmap = instance->vf_affiliation->map; for (i = 0 ; i < instance->vf_affiliation->ldCount; i++) { found = 0; for (j = 0 ; j < new_affiliation->ldCount; j++) { if (savedmap->ref.targetId == newmap->ref.targetId) { found = 1; if (savedmap->policy[thisVf] != newmap->policy[thisVf]) { doscan = 1; goto out; } } newmap = (struct MR_LD_VF_MAP *) ((unsigned char *)newmap + newmap->size); } if (!found && savedmap->policy[thisVf] != MR_LD_ACCESS_HIDDEN) { doscan = 1; goto out; } savedmap = (struct MR_LD_VF_MAP *) ((unsigned char *)savedmap + savedmap->size); } } out: if (doscan) { dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF " "affiliation for scsi%d\n", instance->host->host_no); memcpy(instance->vf_affiliation, new_affiliation, new_affiliation->size); retval = 1; } if (new_affiliation) dma_free_coherent(&instance->pdev->dev, (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION), new_affiliation, new_affiliation_h); megasas_return_cmd(instance, cmd); return retval; } /* This function will get the current SR-IOV LD/VF affiliation */ static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance, int initial) { int retval; if (instance->PlasmaFW111) retval = megasas_get_ld_vf_affiliation_111(instance, initial); else retval = megasas_get_ld_vf_affiliation_12(instance, initial); return retval; } /* This function will tell FW to start the SR-IOV heartbeat */ int megasas_sriov_start_heartbeat(struct megasas_instance *instance, int initial) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; int retval = 0; cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_sriov_start_heartbeat: " "Failed to get cmd for scsi%d\n", instance->host->host_no); return -ENOMEM; } dcmd = &cmd->frame->dcmd; if (initial) { instance->hb_host_mem = dma_zalloc_coherent(&instance->pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM), &instance->hb_host_mem_h, GFP_KERNEL); if (!instance->hb_host_mem) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate" " memory for heartbeat host memory for scsi%d\n", instance->host->host_no); retval = -ENOMEM; goto out; } } memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.s[0] = cpu_to_le16(sizeof(struct MR_CTRL_HB_HOST_MEM)); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH); dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_CTRL_HB_HOST_MEM)); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SHARED_HOST_MEM_ALLOC); megasas_set_dma_settings(instance, dcmd, instance->hb_host_mem_h, sizeof(struct MR_CTRL_HB_HOST_MEM)); dev_warn(&instance->pdev->dev, "SR-IOV: Starting heartbeat for scsi%d\n", instance->host->host_no); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) retval = megasas_issue_blocked_cmd(instance, cmd, MEGASAS_ROUTINE_WAIT_TIME_VF); else retval = megasas_issue_polled(instance, cmd); if (retval) { dev_warn(&instance->pdev->dev, "SR-IOV: MR_DCMD_CTRL_SHARED_HOST" "_MEM_ALLOC DCMD %s for scsi%d\n", (dcmd->cmd_status == MFI_STAT_INVALID_STATUS) ? "timed out" : "failed", instance->host->host_no); retval = 1; } out: megasas_return_cmd(instance, cmd); return retval; } /* Handler for SR-IOV heartbeat */ static void megasas_sriov_heartbeat_handler(struct timer_list *t) { struct megasas_instance *instance = from_timer(instance, t, sriov_heartbeat_timer); if (instance->hb_host_mem->HB.fwCounter != instance->hb_host_mem->HB.driverCounter) { instance->hb_host_mem->HB.driverCounter = instance->hb_host_mem->HB.fwCounter; mod_timer(&instance->sriov_heartbeat_timer, jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF); } else { dev_warn(&instance->pdev->dev, "SR-IOV: Heartbeat never " "completed for scsi%d\n", instance->host->host_no); schedule_work(&instance->work_init); } } /** * megasas_wait_for_outstanding - Wait for all outstanding cmds * @instance: Adapter soft state * * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to * complete all its outstanding commands. Returns error if one or more IOs * are pending after this time period. It also marks the controller dead. */ static int megasas_wait_for_outstanding(struct megasas_instance *instance) { int i, sl, outstanding; u32 reset_index; u32 wait_time = MEGASAS_RESET_WAIT_TIME; unsigned long flags; struct list_head clist_local; struct megasas_cmd *reset_cmd; u32 fw_state; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_info(&instance->pdev->dev, "%s:%d HBA is killed.\n", __func__, __LINE__); return FAILED; } if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) { INIT_LIST_HEAD(&clist_local); spin_lock_irqsave(&instance->hba_lock, flags); list_splice_init(&instance->internal_reset_pending_q, &clist_local); spin_unlock_irqrestore(&instance->hba_lock, flags); dev_notice(&instance->pdev->dev, "HBA reset wait ...\n"); for (i = 0; i < wait_time; i++) { msleep(1000); if (atomic_read(&instance->adprecovery) == MEGASAS_HBA_OPERATIONAL) break; } if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) { dev_notice(&instance->pdev->dev, "reset: Stopping HBA.\n"); atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR); return FAILED; } reset_index = 0; while (!list_empty(&clist_local)) { reset_cmd = list_entry((&clist_local)->next, struct megasas_cmd, list); list_del_init(&reset_cmd->list); if (reset_cmd->scmd) { reset_cmd->scmd->result = DID_REQUEUE << 16; dev_notice(&instance->pdev->dev, "%d:%p reset [%02x]\n", reset_index, reset_cmd, reset_cmd->scmd->cmnd[0]); reset_cmd->scmd->scsi_done(reset_cmd->scmd); megasas_return_cmd(instance, reset_cmd); } else if (reset_cmd->sync_cmd) { dev_notice(&instance->pdev->dev, "%p synch cmds" "reset queue\n", reset_cmd); reset_cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS; instance->instancet->fire_cmd(instance, reset_cmd->frame_phys_addr, 0, instance->reg_set); } else { dev_notice(&instance->pdev->dev, "%p unexpected" "cmds lst\n", reset_cmd); } reset_index++; } return SUCCESS; } for (i = 0; i < resetwaittime; i++) { outstanding = atomic_read(&instance->fw_outstanding); if (!outstanding) break; if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) { dev_notice(&instance->pdev->dev, "[%2d]waiting for %d " "commands to complete\n",i,outstanding); /* * Call cmd completion routine. Cmd to be * be completed directly without depending on isr. */ megasas_complete_cmd_dpc((unsigned long)instance); } msleep(1000); } i = 0; outstanding = atomic_read(&instance->fw_outstanding); fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK; if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL))) goto no_outstanding; if (instance->disableOnlineCtrlReset) goto kill_hba_and_failed; do { if ((fw_state == MFI_STATE_FAULT) || atomic_read(&instance->fw_outstanding)) { dev_info(&instance->pdev->dev, "%s:%d waiting_for_outstanding: before issue OCR. FW state = 0x%x, oustanding 0x%x\n", __func__, __LINE__, fw_state, atomic_read(&instance->fw_outstanding)); if (i == 3) goto kill_hba_and_failed; megasas_do_ocr(instance); if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_info(&instance->pdev->dev, "%s:%d OCR failed and HBA is killed.\n", __func__, __LINE__); return FAILED; } dev_info(&instance->pdev->dev, "%s:%d waiting_for_outstanding: after issue OCR.\n", __func__, __LINE__); for (sl = 0; sl < 10; sl++) msleep(500); outstanding = atomic_read(&instance->fw_outstanding); fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK; if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL))) goto no_outstanding; } i++; } while (i <= 3); no_outstanding: dev_info(&instance->pdev->dev, "%s:%d no more pending commands remain after reset handling.\n", __func__, __LINE__); return SUCCESS; kill_hba_and_failed: /* Reset not supported, kill adapter */ dev_info(&instance->pdev->dev, "%s:%d killing adapter scsi%d" " disableOnlineCtrlReset %d fw_outstanding %d \n", __func__, __LINE__, instance->host->host_no, instance->disableOnlineCtrlReset, atomic_read(&instance->fw_outstanding)); megasas_dump_pending_frames(instance); megaraid_sas_kill_hba(instance); return FAILED; } /** * megasas_generic_reset - Generic reset routine * @scmd: Mid-layer SCSI command * * This routine implements a generic reset handler for device, bus and host * reset requests. Device, bus and host specific reset handlers can use this * function after they do their specific tasks. */ static int megasas_generic_reset(struct scsi_cmnd *scmd) { int ret_val; struct megasas_instance *instance; instance = (struct megasas_instance *)scmd->device->host->hostdata; scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n", scmd->cmnd[0], scmd->retries); if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_err(&instance->pdev->dev, "cannot recover from previous reset failures\n"); return FAILED; } ret_val = megasas_wait_for_outstanding(instance); if (ret_val == SUCCESS) dev_notice(&instance->pdev->dev, "reset successful\n"); else dev_err(&instance->pdev->dev, "failed to do reset\n"); return ret_val; } /** * megasas_reset_timer - quiesce the adapter if required * @scmd: scsi cmnd * * Sets the FW busy flag and reduces the host->can_queue if the * cmd has not been completed within the timeout period. */ static enum blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd) { struct megasas_instance *instance; unsigned long flags; if (time_after(jiffies, scmd->jiffies_at_alloc + (scmd_timeout * 2) * HZ)) { return BLK_EH_DONE; } instance = (struct megasas_instance *)scmd->device->host->hostdata; if (!(instance->flag & MEGASAS_FW_BUSY)) { /* FW is busy, throttle IO */ spin_lock_irqsave(instance->host->host_lock, flags); instance->host->can_queue = instance->throttlequeuedepth; instance->last_time = jiffies; instance->flag |= MEGASAS_FW_BUSY; spin_unlock_irqrestore(instance->host->host_lock, flags); } return BLK_EH_RESET_TIMER; } /** * megasas_dump_frame - This function will dump MPT/MFI frame */ static inline void megasas_dump_frame(void *mpi_request, int sz) { int i; __le32 *mfp = (__le32 *)mpi_request; printk(KERN_INFO "IO request frame:\n\t"); for (i = 0; i < sz / sizeof(__le32); i++) { if (i && ((i % 8) == 0)) printk("\n\t"); printk("%08x ", le32_to_cpu(mfp[i])); } printk("\n"); } /** * megasas_reset_bus_host - Bus & host reset handler entry point */ static int megasas_reset_bus_host(struct scsi_cmnd *scmd) { int ret; struct megasas_instance *instance; instance = (struct megasas_instance *)scmd->device->host->hostdata; scmd_printk(KERN_INFO, scmd, "Controller reset is requested due to IO timeout\n" "SCSI command pointer: (%p)\t SCSI host state: %d\t" " SCSI host busy: %d\t FW outstanding: %d\n", scmd, scmd->device->host->shost_state, scsi_host_busy(scmd->device->host), atomic_read(&instance->fw_outstanding)); /* * First wait for all commands to complete */ if (instance->adapter_type == MFI_SERIES) { ret = megasas_generic_reset(scmd); } else { struct megasas_cmd_fusion *cmd; cmd = (struct megasas_cmd_fusion *)scmd->SCp.ptr; if (cmd) megasas_dump_frame(cmd->io_request, MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE); ret = megasas_reset_fusion(scmd->device->host, SCSIIO_TIMEOUT_OCR); } return ret; } /** * megasas_task_abort - Issues task abort request to firmware * (supported only for fusion adapters) * @scmd: SCSI command pointer */ static int megasas_task_abort(struct scsi_cmnd *scmd) { int ret; struct megasas_instance *instance; instance = (struct megasas_instance *)scmd->device->host->hostdata; if (instance->adapter_type != MFI_SERIES) ret = megasas_task_abort_fusion(scmd); else { sdev_printk(KERN_NOTICE, scmd->device, "TASK ABORT not supported\n"); ret = FAILED; } return ret; } /** * megasas_reset_target: Issues target reset request to firmware * (supported only for fusion adapters) * @scmd: SCSI command pointer */ static int megasas_reset_target(struct scsi_cmnd *scmd) { int ret; struct megasas_instance *instance; instance = (struct megasas_instance *)scmd->device->host->hostdata; if (instance->adapter_type != MFI_SERIES) ret = megasas_reset_target_fusion(scmd); else { sdev_printk(KERN_NOTICE, scmd->device, "TARGET RESET not supported\n"); ret = FAILED; } return ret; } /** * megasas_bios_param - Returns disk geometry for a disk * @sdev: device handle * @bdev: block device * @capacity: drive capacity * @geom: geometry parameters */ static int megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev, sector_t capacity, int geom[]) { int heads; int sectors; sector_t cylinders; unsigned long tmp; /* Default heads (64) & sectors (32) */ heads = 64; sectors = 32; tmp = heads * sectors; cylinders = capacity; sector_div(cylinders, tmp); /* * Handle extended translation size for logical drives > 1Gb */ if (capacity >= 0x200000) { heads = 255; sectors = 63; tmp = heads*sectors; cylinders = capacity; sector_div(cylinders, tmp); } geom[0] = heads; geom[1] = sectors; geom[2] = cylinders; return 0; } static void megasas_aen_polling(struct work_struct *work); /** * megasas_service_aen - Processes an event notification * @instance: Adapter soft state * @cmd: AEN command completed by the ISR * * For AEN, driver sends a command down to FW that is held by the FW till an * event occurs. When an event of interest occurs, FW completes the command * that it was previously holding. * * This routines sends SIGIO signal to processes that have registered with the * driver for AEN. */ static void megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd) { unsigned long flags; /* * Don't signal app if it is just an aborted previously registered aen */ if ((!cmd->abort_aen) && (instance->unload == 0)) { spin_lock_irqsave(&poll_aen_lock, flags); megasas_poll_wait_aen = 1; spin_unlock_irqrestore(&poll_aen_lock, flags); wake_up(&megasas_poll_wait); kill_fasync(&megasas_async_queue, SIGIO, POLL_IN); } else cmd->abort_aen = 0; instance->aen_cmd = NULL; megasas_return_cmd(instance, cmd); if ((instance->unload == 0) && ((instance->issuepend_done == 1))) { struct megasas_aen_event *ev; ev = kzalloc(sizeof(*ev), GFP_ATOMIC); if (!ev) { dev_err(&instance->pdev->dev, "megasas_service_aen: out of memory\n"); } else { ev->instance = instance; instance->ev = ev; INIT_DELAYED_WORK(&ev->hotplug_work, megasas_aen_polling); schedule_delayed_work(&ev->hotplug_work, 0); } } } static ssize_t megasas_fw_crash_buffer_store(struct device *cdev, struct device_attribute *attr, const char *buf, size_t count) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *) shost->hostdata; int val = 0; unsigned long flags; if (kstrtoint(buf, 0, &val) != 0) return -EINVAL; spin_lock_irqsave(&instance->crashdump_lock, flags); instance->fw_crash_buffer_offset = val; spin_unlock_irqrestore(&instance->crashdump_lock, flags); return strlen(buf); } static ssize_t megasas_fw_crash_buffer_show(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *) shost->hostdata; u32 size; unsigned long buff_addr; unsigned long dmachunk = CRASH_DMA_BUF_SIZE; unsigned long src_addr; unsigned long flags; u32 buff_offset; spin_lock_irqsave(&instance->crashdump_lock, flags); buff_offset = instance->fw_crash_buffer_offset; if (!instance->crash_dump_buf && !((instance->fw_crash_state == AVAILABLE) || (instance->fw_crash_state == COPYING))) { dev_err(&instance->pdev->dev, "Firmware crash dump is not available\n"); spin_unlock_irqrestore(&instance->crashdump_lock, flags); return -EINVAL; } buff_addr = (unsigned long) buf; if (buff_offset > (instance->fw_crash_buffer_size * dmachunk)) { dev_err(&instance->pdev->dev, "Firmware crash dump offset is out of range\n"); spin_unlock_irqrestore(&instance->crashdump_lock, flags); return 0; } size = (instance->fw_crash_buffer_size * dmachunk) - buff_offset; size = (size >= PAGE_SIZE) ? (PAGE_SIZE - 1) : size; src_addr = (unsigned long)instance->crash_buf[buff_offset / dmachunk] + (buff_offset % dmachunk); memcpy(buf, (void *)src_addr, size); spin_unlock_irqrestore(&instance->crashdump_lock, flags); return size; } static ssize_t megasas_fw_crash_buffer_size_show(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *) shost->hostdata; return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long) ((instance->fw_crash_buffer_size) * 1024 * 1024)/PAGE_SIZE); } static ssize_t megasas_fw_crash_state_store(struct device *cdev, struct device_attribute *attr, const char *buf, size_t count) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *) shost->hostdata; int val = 0; unsigned long flags; if (kstrtoint(buf, 0, &val) != 0) return -EINVAL; if ((val <= AVAILABLE || val > COPY_ERROR)) { dev_err(&instance->pdev->dev, "application updates invalid " "firmware crash state\n"); return -EINVAL; } instance->fw_crash_state = val; if ((val == COPIED) || (val == COPY_ERROR)) { spin_lock_irqsave(&instance->crashdump_lock, flags); megasas_free_host_crash_buffer(instance); spin_unlock_irqrestore(&instance->crashdump_lock, flags); if (val == COPY_ERROR) dev_info(&instance->pdev->dev, "application failed to " "copy Firmware crash dump\n"); else dev_info(&instance->pdev->dev, "Firmware crash dump " "copied successfully\n"); } return strlen(buf); } static ssize_t megasas_fw_crash_state_show(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *) shost->hostdata; return snprintf(buf, PAGE_SIZE, "%d\n", instance->fw_crash_state); } static ssize_t megasas_page_size_show(struct device *cdev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)PAGE_SIZE - 1); } static ssize_t megasas_ldio_outstanding_show(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata; return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->ldio_outstanding)); } static ssize_t megasas_fw_cmds_outstanding_show(struct device *cdev, struct device_attribute *attr, char *buf) { struct Scsi_Host *shost = class_to_shost(cdev); struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata; return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->fw_outstanding)); } static DEVICE_ATTR(fw_crash_buffer, S_IRUGO | S_IWUSR, megasas_fw_crash_buffer_show, megasas_fw_crash_buffer_store); static DEVICE_ATTR(fw_crash_buffer_size, S_IRUGO, megasas_fw_crash_buffer_size_show, NULL); static DEVICE_ATTR(fw_crash_state, S_IRUGO | S_IWUSR, megasas_fw_crash_state_show, megasas_fw_crash_state_store); static DEVICE_ATTR(page_size, S_IRUGO, megasas_page_size_show, NULL); static DEVICE_ATTR(ldio_outstanding, S_IRUGO, megasas_ldio_outstanding_show, NULL); static DEVICE_ATTR(fw_cmds_outstanding, S_IRUGO, megasas_fw_cmds_outstanding_show, NULL); struct device_attribute *megaraid_host_attrs[] = { &dev_attr_fw_crash_buffer_size, &dev_attr_fw_crash_buffer, &dev_attr_fw_crash_state, &dev_attr_page_size, &dev_attr_ldio_outstanding, &dev_attr_fw_cmds_outstanding, NULL, }; /* * Scsi host template for megaraid_sas driver */ static struct scsi_host_template megasas_template = { .module = THIS_MODULE, .name = "Avago SAS based MegaRAID driver", .proc_name = "megaraid_sas", .slave_configure = megasas_slave_configure, .slave_alloc = megasas_slave_alloc, .slave_destroy = megasas_slave_destroy, .queuecommand = megasas_queue_command, .eh_target_reset_handler = megasas_reset_target, .eh_abort_handler = megasas_task_abort, .eh_host_reset_handler = megasas_reset_bus_host, .eh_timed_out = megasas_reset_timer, .shost_attrs = megaraid_host_attrs, .bios_param = megasas_bios_param, .change_queue_depth = scsi_change_queue_depth, .no_write_same = 1, }; /** * megasas_complete_int_cmd - Completes an internal command * @instance: Adapter soft state * @cmd: Command to be completed * * The megasas_issue_blocked_cmd() function waits for a command to complete * after it issues a command. This function wakes up that waiting routine by * calling wake_up() on the wait queue. */ static void megasas_complete_int_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd) { cmd->cmd_status_drv = cmd->frame->io.cmd_status; wake_up(&instance->int_cmd_wait_q); } /** * megasas_complete_abort - Completes aborting a command * @instance: Adapter soft state * @cmd: Cmd that was issued to abort another cmd * * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q * after it issues an abort on a previously issued command. This function * wakes up all functions waiting on the same wait queue. */ static void megasas_complete_abort(struct megasas_instance *instance, struct megasas_cmd *cmd) { if (cmd->sync_cmd) { cmd->sync_cmd = 0; cmd->cmd_status_drv = 0; wake_up(&instance->abort_cmd_wait_q); } } /** * megasas_complete_cmd - Completes a command * @instance: Adapter soft state * @cmd: Command to be completed * @alt_status: If non-zero, use this value as status to * SCSI mid-layer instead of the value returned * by the FW. This should be used if caller wants * an alternate status (as in the case of aborted * commands) */ void megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd, u8 alt_status) { int exception = 0; struct megasas_header *hdr = &cmd->frame->hdr; unsigned long flags; struct fusion_context *fusion = instance->ctrl_context; u32 opcode, status; /* flag for the retry reset */ cmd->retry_for_fw_reset = 0; if (cmd->scmd) cmd->scmd->SCp.ptr = NULL; switch (hdr->cmd) { case MFI_CMD_INVALID: /* Some older 1068 controller FW may keep a pended MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel when booting the kdump kernel. Ignore this command to prevent a kernel panic on shutdown of the kdump kernel. */ dev_warn(&instance->pdev->dev, "MFI_CMD_INVALID command " "completed\n"); dev_warn(&instance->pdev->dev, "If you have a controller " "other than PERC5, please upgrade your firmware\n"); break; case MFI_CMD_PD_SCSI_IO: case MFI_CMD_LD_SCSI_IO: /* * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been * issued either through an IO path or an IOCTL path. If it * was via IOCTL, we will send it to internal completion. */ if (cmd->sync_cmd) { cmd->sync_cmd = 0; megasas_complete_int_cmd(instance, cmd); break; } /* fall through */ case MFI_CMD_LD_READ: case MFI_CMD_LD_WRITE: if (alt_status) { cmd->scmd->result = alt_status << 16; exception = 1; } if (exception) { atomic_dec(&instance->fw_outstanding); scsi_dma_unmap(cmd->scmd); cmd->scmd->scsi_done(cmd->scmd); megasas_return_cmd(instance, cmd); break; } switch (hdr->cmd_status) { case MFI_STAT_OK: cmd->scmd->result = DID_OK << 16; break; case MFI_STAT_SCSI_IO_FAILED: case MFI_STAT_LD_INIT_IN_PROGRESS: cmd->scmd->result = (DID_ERROR << 16) | hdr->scsi_status; break; case MFI_STAT_SCSI_DONE_WITH_ERROR: cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status; if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) { memset(cmd->scmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE); memcpy(cmd->scmd->sense_buffer, cmd->sense, hdr->sense_len); cmd->scmd->result |= DRIVER_SENSE << 24; } break; case MFI_STAT_LD_OFFLINE: case MFI_STAT_DEVICE_NOT_FOUND: cmd->scmd->result = DID_BAD_TARGET << 16; break; default: dev_printk(KERN_DEBUG, &instance->pdev->dev, "MFI FW status %#x\n", hdr->cmd_status); cmd->scmd->result = DID_ERROR << 16; break; } atomic_dec(&instance->fw_outstanding); scsi_dma_unmap(cmd->scmd); cmd->scmd->scsi_done(cmd->scmd); megasas_return_cmd(instance, cmd); break; case MFI_CMD_SMP: case MFI_CMD_STP: case MFI_CMD_NVME: megasas_complete_int_cmd(instance, cmd); break; case MFI_CMD_DCMD: opcode = le32_to_cpu(cmd->frame->dcmd.opcode); /* Check for LD map update */ if ((opcode == MR_DCMD_LD_MAP_GET_INFO) && (cmd->frame->dcmd.mbox.b[1] == 1)) { fusion->fast_path_io = 0; spin_lock_irqsave(instance->host->host_lock, flags); status = cmd->frame->hdr.cmd_status; instance->map_update_cmd = NULL; if (status != MFI_STAT_OK) { if (status != MFI_STAT_NOT_FOUND) dev_warn(&instance->pdev->dev, "map syncfailed, status = 0x%x\n", cmd->frame->hdr.cmd_status); else { megasas_return_cmd(instance, cmd); spin_unlock_irqrestore( instance->host->host_lock, flags); break; } } megasas_return_cmd(instance, cmd); /* * Set fast path IO to ZERO. * Validate Map will set proper value. * Meanwhile all IOs will go as LD IO. */ if (status == MFI_STAT_OK && (MR_ValidateMapInfo(instance, (instance->map_id + 1)))) { instance->map_id++; fusion->fast_path_io = 1; } else { fusion->fast_path_io = 0; } megasas_sync_map_info(instance); spin_unlock_irqrestore(instance->host->host_lock, flags); break; } if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO || opcode == MR_DCMD_CTRL_EVENT_GET) { spin_lock_irqsave(&poll_aen_lock, flags); megasas_poll_wait_aen = 0; spin_unlock_irqrestore(&poll_aen_lock, flags); } /* FW has an updated PD sequence */ if ((opcode == MR_DCMD_SYSTEM_PD_MAP_GET_INFO) && (cmd->frame->dcmd.mbox.b[0] == 1)) { spin_lock_irqsave(instance->host->host_lock, flags); status = cmd->frame->hdr.cmd_status; instance->jbod_seq_cmd = NULL; megasas_return_cmd(instance, cmd); if (status == MFI_STAT_OK) { instance->pd_seq_map_id++; /* Re-register a pd sync seq num cmd */ if (megasas_sync_pd_seq_num(instance, true)) instance->use_seqnum_jbod_fp = false; } else instance->use_seqnum_jbod_fp = false; spin_unlock_irqrestore(instance->host->host_lock, flags); break; } /* * See if got an event notification */ if (opcode == MR_DCMD_CTRL_EVENT_WAIT) megasas_service_aen(instance, cmd); else megasas_complete_int_cmd(instance, cmd); break; case MFI_CMD_ABORT: /* * Cmd issued to abort another cmd returned */ megasas_complete_abort(instance, cmd); break; default: dev_info(&instance->pdev->dev, "Unknown command completed! [0x%X]\n", hdr->cmd); megasas_complete_int_cmd(instance, cmd); break; } } /** * megasas_issue_pending_cmds_again - issue all pending cmds * in FW again because of the fw reset * @instance: Adapter soft state */ static inline void megasas_issue_pending_cmds_again(struct megasas_instance *instance) { struct megasas_cmd *cmd; struct list_head clist_local; union megasas_evt_class_locale class_locale; unsigned long flags; u32 seq_num; INIT_LIST_HEAD(&clist_local); spin_lock_irqsave(&instance->hba_lock, flags); list_splice_init(&instance->internal_reset_pending_q, &clist_local); spin_unlock_irqrestore(&instance->hba_lock, flags); while (!list_empty(&clist_local)) { cmd = list_entry((&clist_local)->next, struct megasas_cmd, list); list_del_init(&cmd->list); if (cmd->sync_cmd || cmd->scmd) { dev_notice(&instance->pdev->dev, "command %p, %p:%d" "detected to be pending while HBA reset\n", cmd, cmd->scmd, cmd->sync_cmd); cmd->retry_for_fw_reset++; if (cmd->retry_for_fw_reset == 3) { dev_notice(&instance->pdev->dev, "cmd %p, %p:%d" "was tried multiple times during reset." "Shutting down the HBA\n", cmd, cmd->scmd, cmd->sync_cmd); instance->instancet->disable_intr(instance); atomic_set(&instance->fw_reset_no_pci_access, 1); megaraid_sas_kill_hba(instance); return; } } if (cmd->sync_cmd == 1) { if (cmd->scmd) { dev_notice(&instance->pdev->dev, "unexpected" "cmd attached to internal command!\n"); } dev_notice(&instance->pdev->dev, "%p synchronous cmd" "on the internal reset queue," "issue it again.\n", cmd); cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS; instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, 0, instance->reg_set); } else if (cmd->scmd) { dev_notice(&instance->pdev->dev, "%p scsi cmd [%02x]" "detected on the internal queue, issue again.\n", cmd, cmd->scmd->cmnd[0]); atomic_inc(&instance->fw_outstanding); instance->instancet->fire_cmd(instance, cmd->frame_phys_addr, cmd->frame_count-1, instance->reg_set); } else { dev_notice(&instance->pdev->dev, "%p unexpected cmd on the" "internal reset defer list while re-issue!!\n", cmd); } } if (instance->aen_cmd) { dev_notice(&instance->pdev->dev, "aen_cmd in def process\n"); megasas_return_cmd(instance, instance->aen_cmd); instance->aen_cmd = NULL; } /* * Initiate AEN (Asynchronous Event Notification) */ seq_num = instance->last_seq_num; class_locale.members.reserved = 0; class_locale.members.locale = MR_EVT_LOCALE_ALL; class_locale.members.class = MR_EVT_CLASS_DEBUG; megasas_register_aen(instance, seq_num, class_locale.word); } /** * Move the internal reset pending commands to a deferred queue. * * We move the commands pending at internal reset time to a * pending queue. This queue would be flushed after successful * completion of the internal reset sequence. if the internal reset * did not complete in time, the kernel reset handler would flush * these commands. **/ static void megasas_internal_reset_defer_cmds(struct megasas_instance *instance) { struct megasas_cmd *cmd; int i; u16 max_cmd = instance->max_fw_cmds; u32 defer_index; unsigned long flags; defer_index = 0; spin_lock_irqsave(&instance->mfi_pool_lock, flags); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (cmd->sync_cmd == 1 || cmd->scmd) { dev_notice(&instance->pdev->dev, "moving cmd[%d]:%p:%d:%p" "on the defer queue as internal\n", defer_index, cmd, cmd->sync_cmd, cmd->scmd); if (!list_empty(&cmd->list)) { dev_notice(&instance->pdev->dev, "ERROR while" " moving this cmd:%p, %d %p, it was" "discovered on some list?\n", cmd, cmd->sync_cmd, cmd->scmd); list_del_init(&cmd->list); } defer_index++; list_add_tail(&cmd->list, &instance->internal_reset_pending_q); } } spin_unlock_irqrestore(&instance->mfi_pool_lock, flags); } static void process_fw_state_change_wq(struct work_struct *work) { struct megasas_instance *instance = container_of(work, struct megasas_instance, work_init); u32 wait; unsigned long flags; if (atomic_read(&instance->adprecovery) != MEGASAS_ADPRESET_SM_INFAULT) { dev_notice(&instance->pdev->dev, "error, recovery st %x\n", atomic_read(&instance->adprecovery)); return ; } if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) { dev_notice(&instance->pdev->dev, "FW detected to be in fault" "state, restarting it...\n"); instance->instancet->disable_intr(instance); atomic_set(&instance->fw_outstanding, 0); atomic_set(&instance->fw_reset_no_pci_access, 1); instance->instancet->adp_reset(instance, instance->reg_set); atomic_set(&instance->fw_reset_no_pci_access, 0); dev_notice(&instance->pdev->dev, "FW restarted successfully," "initiating next stage...\n"); dev_notice(&instance->pdev->dev, "HBA recovery state machine," "state 2 starting...\n"); /* waiting for about 20 second before start the second init */ for (wait = 0; wait < 30; wait++) { msleep(1000); } if (megasas_transition_to_ready(instance, 1)) { dev_notice(&instance->pdev->dev, "adapter not ready\n"); atomic_set(&instance->fw_reset_no_pci_access, 1); megaraid_sas_kill_hba(instance); return ; } if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) || (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) || (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR) ) { *instance->consumer = *instance->producer; } else { *instance->consumer = 0; *instance->producer = 0; } megasas_issue_init_mfi(instance); spin_lock_irqsave(&instance->hba_lock, flags); atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL); spin_unlock_irqrestore(&instance->hba_lock, flags); instance->instancet->enable_intr(instance); megasas_issue_pending_cmds_again(instance); instance->issuepend_done = 1; } } /** * megasas_deplete_reply_queue - Processes all completed commands * @instance: Adapter soft state * @alt_status: Alternate status to be returned to * SCSI mid-layer instead of the status * returned by the FW * Note: this must be called with hba lock held */ static int megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status) { u32 mfiStatus; u32 fw_state; if ((mfiStatus = instance->instancet->check_reset(instance, instance->reg_set)) == 1) { return IRQ_HANDLED; } mfiStatus = instance->instancet->clear_intr(instance); if (mfiStatus == 0) { /* Hardware may not set outbound_intr_status in MSI-X mode */ if (!instance->msix_vectors) return IRQ_NONE; } instance->mfiStatus = mfiStatus; if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) { fw_state = instance->instancet->read_fw_status_reg( instance) & MFI_STATE_MASK; if (fw_state != MFI_STATE_FAULT) { dev_notice(&instance->pdev->dev, "fw state:%x\n", fw_state); } if ((fw_state == MFI_STATE_FAULT) && (instance->disableOnlineCtrlReset == 0)) { dev_notice(&instance->pdev->dev, "wait adp restart\n"); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) || (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) || (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) { *instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN); } instance->instancet->disable_intr(instance); atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT); instance->issuepend_done = 0; atomic_set(&instance->fw_outstanding, 0); megasas_internal_reset_defer_cmds(instance); dev_notice(&instance->pdev->dev, "fwState=%x, stage:%d\n", fw_state, atomic_read(&instance->adprecovery)); schedule_work(&instance->work_init); return IRQ_HANDLED; } else { dev_notice(&instance->pdev->dev, "fwstate:%x, dis_OCR=%x\n", fw_state, instance->disableOnlineCtrlReset); } } tasklet_schedule(&instance->isr_tasklet); return IRQ_HANDLED; } /** * megasas_isr - isr entry point */ static irqreturn_t megasas_isr(int irq, void *devp) { struct megasas_irq_context *irq_context = devp; struct megasas_instance *instance = irq_context->instance; unsigned long flags; irqreturn_t rc; if (atomic_read(&instance->fw_reset_no_pci_access)) return IRQ_HANDLED; spin_lock_irqsave(&instance->hba_lock, flags); rc = megasas_deplete_reply_queue(instance, DID_OK); spin_unlock_irqrestore(&instance->hba_lock, flags); return rc; } /** * megasas_transition_to_ready - Move the FW to READY state * @instance: Adapter soft state * * During the initialization, FW passes can potentially be in any one of * several possible states. If the FW in operational, waiting-for-handshake * states, driver must take steps to bring it to ready state. Otherwise, it * has to wait for the ready state. */ int megasas_transition_to_ready(struct megasas_instance *instance, int ocr) { int i; u8 max_wait; u32 fw_state; u32 cur_state; u32 abs_state, curr_abs_state; abs_state = instance->instancet->read_fw_status_reg(instance); fw_state = abs_state & MFI_STATE_MASK; if (fw_state != MFI_STATE_READY) dev_info(&instance->pdev->dev, "Waiting for FW to come to ready" " state\n"); while (fw_state != MFI_STATE_READY) { switch (fw_state) { case MFI_STATE_FAULT: dev_printk(KERN_DEBUG, &instance->pdev->dev, "FW in FAULT state!!\n"); if (ocr) { max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FAULT; break; } else return -ENODEV; case MFI_STATE_WAIT_HANDSHAKE: /* * Set the CLR bit in inbound doorbell */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->adapter_type != MFI_SERIES)) writel( MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG, &instance->reg_set->doorbell); else writel( MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG, &instance->reg_set->inbound_doorbell); max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_WAIT_HANDSHAKE; break; case MFI_STATE_BOOT_MESSAGE_PENDING: if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->adapter_type != MFI_SERIES)) writel(MFI_INIT_HOTPLUG, &instance->reg_set->doorbell); else writel(MFI_INIT_HOTPLUG, &instance->reg_set->inbound_doorbell); max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_BOOT_MESSAGE_PENDING; break; case MFI_STATE_OPERATIONAL: /* * Bring it to READY state; assuming max wait 10 secs */ instance->instancet->disable_intr(instance); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) || (instance->adapter_type != MFI_SERIES)) { writel(MFI_RESET_FLAGS, &instance->reg_set->doorbell); if (instance->adapter_type != MFI_SERIES) { for (i = 0; i < (10 * 1000); i += 20) { if (megasas_readl( instance, &instance-> reg_set-> doorbell) & 1) msleep(20); else break; } } } else writel(MFI_RESET_FLAGS, &instance->reg_set->inbound_doorbell); max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_OPERATIONAL; break; case MFI_STATE_UNDEFINED: /* * This state should not last for more than 2 seconds */ max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_UNDEFINED; break; case MFI_STATE_BB_INIT: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_BB_INIT; break; case MFI_STATE_FW_INIT: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FW_INIT; break; case MFI_STATE_FW_INIT_2: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FW_INIT_2; break; case MFI_STATE_DEVICE_SCAN: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_DEVICE_SCAN; break; case MFI_STATE_FLUSH_CACHE: max_wait = MEGASAS_RESET_WAIT_TIME; cur_state = MFI_STATE_FLUSH_CACHE; break; default: dev_printk(KERN_DEBUG, &instance->pdev->dev, "Unknown state 0x%x\n", fw_state); return -ENODEV; } /* * The cur_state should not last for more than max_wait secs */ for (i = 0; i < max_wait; i++) { curr_abs_state = instance->instancet-> read_fw_status_reg(instance); if (abs_state == curr_abs_state) { msleep(1000); } else break; } /* * Return error if fw_state hasn't changed after max_wait */ if (curr_abs_state == abs_state) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "FW state [%d] hasn't changed " "in %d secs\n", fw_state, max_wait); return -ENODEV; } abs_state = curr_abs_state; fw_state = curr_abs_state & MFI_STATE_MASK; } dev_info(&instance->pdev->dev, "FW now in Ready state\n"); return 0; } /** * megasas_teardown_frame_pool - Destroy the cmd frame DMA pool * @instance: Adapter soft state */ static void megasas_teardown_frame_pool(struct megasas_instance *instance) { int i; u16 max_cmd = instance->max_mfi_cmds; struct megasas_cmd *cmd; if (!instance->frame_dma_pool) return; /* * Return all frames to pool */ for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (cmd->frame) dma_pool_free(instance->frame_dma_pool, cmd->frame, cmd->frame_phys_addr); if (cmd->sense) dma_pool_free(instance->sense_dma_pool, cmd->sense, cmd->sense_phys_addr); } /* * Now destroy the pool itself */ dma_pool_destroy(instance->frame_dma_pool); dma_pool_destroy(instance->sense_dma_pool); instance->frame_dma_pool = NULL; instance->sense_dma_pool = NULL; } /** * megasas_create_frame_pool - Creates DMA pool for cmd frames * @instance: Adapter soft state * * Each command packet has an embedded DMA memory buffer that is used for * filling MFI frame and the SG list that immediately follows the frame. This * function creates those DMA memory buffers for each command packet by using * PCI pool facility. */ static int megasas_create_frame_pool(struct megasas_instance *instance) { int i; u16 max_cmd; u32 sge_sz; u32 frame_count; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * Size of our frame is 64 bytes for MFI frame, followed by max SG * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer */ sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) : sizeof(struct megasas_sge32); if (instance->flag_ieee) sge_sz = sizeof(struct megasas_sge_skinny); /* * For MFI controllers. * max_num_sge = 60 * max_sge_sz = 16 byte (sizeof megasas_sge_skinny) * Total 960 byte (15 MFI frame of 64 byte) * * Fusion adapter require only 3 extra frame. * max_num_sge = 16 (defined as MAX_IOCTL_SGE) * max_sge_sz = 12 byte (sizeof megasas_sge64) * Total 192 byte (3 MFI frame of 64 byte) */ frame_count = (instance->adapter_type == MFI_SERIES) ? (15 + 1) : (3 + 1); instance->mfi_frame_size = MEGAMFI_FRAME_SIZE * frame_count; /* * Use DMA pool facility provided by PCI layer */ instance->frame_dma_pool = dma_pool_create("megasas frame pool", &instance->pdev->dev, instance->mfi_frame_size, 256, 0); if (!instance->frame_dma_pool) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup frame pool\n"); return -ENOMEM; } instance->sense_dma_pool = dma_pool_create("megasas sense pool", &instance->pdev->dev, 128, 4, 0); if (!instance->sense_dma_pool) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup sense pool\n"); dma_pool_destroy(instance->frame_dma_pool); instance->frame_dma_pool = NULL; return -ENOMEM; } /* * Allocate and attach a frame to each of the commands in cmd_list. * By making cmd->index as the context instead of the &cmd, we can * always use 32bit context regardless of the architecture */ for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; cmd->frame = dma_pool_zalloc(instance->frame_dma_pool, GFP_KERNEL, &cmd->frame_phys_addr); cmd->sense = dma_pool_alloc(instance->sense_dma_pool, GFP_KERNEL, &cmd->sense_phys_addr); /* * megasas_teardown_frame_pool() takes care of freeing * whatever has been allocated */ if (!cmd->frame || !cmd->sense) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "dma_pool_alloc failed\n"); megasas_teardown_frame_pool(instance); return -ENOMEM; } cmd->frame->io.context = cpu_to_le32(cmd->index); cmd->frame->io.pad_0 = 0; if ((instance->adapter_type == MFI_SERIES) && reset_devices) cmd->frame->hdr.cmd = MFI_CMD_INVALID; } return 0; } /** * megasas_free_cmds - Free all the cmds in the free cmd pool * @instance: Adapter soft state */ void megasas_free_cmds(struct megasas_instance *instance) { int i; /* First free the MFI frame pool */ megasas_teardown_frame_pool(instance); /* Free all the commands in the cmd_list */ for (i = 0; i < instance->max_mfi_cmds; i++) kfree(instance->cmd_list[i]); /* Free the cmd_list buffer itself */ kfree(instance->cmd_list); instance->cmd_list = NULL; INIT_LIST_HEAD(&instance->cmd_pool); } /** * megasas_alloc_cmds - Allocates the command packets * @instance: Adapter soft state * * Each command that is issued to the FW, whether IO commands from the OS or * internal commands like IOCTLs, are wrapped in local data structure called * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to * the FW. * * Each frame has a 32-bit field called context (tag). This context is used * to get back the megasas_cmd from the frame when a frame gets completed in * the ISR. Typically the address of the megasas_cmd itself would be used as * the context. But we wanted to keep the differences between 32 and 64 bit * systems to the mininum. We always use 32 bit integers for the context. In * this driver, the 32 bit values are the indices into an array cmd_list. * This array is used only to look up the megasas_cmd given the context. The * free commands themselves are maintained in a linked list called cmd_pool. */ int megasas_alloc_cmds(struct megasas_instance *instance) { int i; int j; u16 max_cmd; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * instance->cmd_list is an array of struct megasas_cmd pointers. * Allocate the dynamic array first and then allocate individual * commands. */ instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL); if (!instance->cmd_list) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n"); return -ENOMEM; } memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd); for (i = 0; i < max_cmd; i++) { instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd), GFP_KERNEL); if (!instance->cmd_list[i]) { for (j = 0; j < i; j++) kfree(instance->cmd_list[j]); kfree(instance->cmd_list); instance->cmd_list = NULL; return -ENOMEM; } } for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; memset(cmd, 0, sizeof(struct megasas_cmd)); cmd->index = i; cmd->scmd = NULL; cmd->instance = instance; list_add_tail(&cmd->list, &instance->cmd_pool); } /* * Create a frame pool and assign one frame to each cmd */ if (megasas_create_frame_pool(instance)) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n"); megasas_free_cmds(instance); return -ENOMEM; } return 0; } /* * dcmd_timeout_ocr_possible - Check if OCR is possible based on Driver/FW state. * @instance: Adapter soft state * * Return 0 for only Fusion adapter, if driver load/unload is not in progress * or FW is not under OCR. */ inline int dcmd_timeout_ocr_possible(struct megasas_instance *instance) { if (instance->adapter_type == MFI_SERIES) return KILL_ADAPTER; else if (instance->unload || test_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags)) return IGNORE_TIMEOUT; else return INITIATE_OCR; } static void megasas_get_pd_info(struct megasas_instance *instance, struct scsi_device *sdev) { int ret; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_PRIV_DEVICE *mr_device_priv_data; u16 device_id = 0; device_id = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id; cmd = megasas_get_cmd(instance); if (!cmd) { dev_err(&instance->pdev->dev, "Failed to get cmd %s\n", __func__); return; } dcmd = &cmd->frame->dcmd; memset(instance->pd_info, 0, sizeof(*instance->pd_info)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.s[0] = cpu_to_le16(device_id); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0xFF; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_PD_INFO)); dcmd->opcode = cpu_to_le32(MR_DCMD_PD_GET_INFO); megasas_set_dma_settings(instance, dcmd, instance->pd_info_h, sizeof(struct MR_PD_INFO)); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); else ret = megasas_issue_polled(instance, cmd); switch (ret) { case DCMD_SUCCESS: mr_device_priv_data = sdev->hostdata; le16_to_cpus((u16 *)&instance->pd_info->state.ddf.pdType); mr_device_priv_data->interface_type = instance->pd_info->state.ddf.pdType.intf; break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } break; } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); return; } /* * megasas_get_pd_list_info - Returns FW's pd_list structure * @instance: Adapter soft state * @pd_list: pd_list structure * * Issues an internal command (DCMD) to get the FW's controller PD * list structure. This information is mainly used to find out SYSTEM * supported by the FW. */ static int megasas_get_pd_list(struct megasas_instance *instance) { int ret = 0, pd_index = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_PD_LIST *ci; struct MR_PD_ADDRESS *pd_addr; dma_addr_t ci_h = 0; if (instance->pd_list_not_supported) { dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY " "not supported by firmware\n"); return ret; } ci = instance->pd_list_buf; ci_h = instance->pd_list_buf_h; cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "(get_pd_list): Failed to get cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST; dcmd->mbox.b[1] = 0; dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST)); dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY); megasas_set_dma_settings(instance, dcmd, instance->pd_list_buf_h, (MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST))); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); else ret = megasas_issue_polled(instance, cmd); switch (ret) { case DCMD_FAILED: dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY " "failed/not supported by firmware\n"); if (instance->adapter_type != MFI_SERIES) megaraid_sas_kill_hba(instance); else instance->pd_list_not_supported = 1; break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; /* * DCMD failed from AEN path. * AEN path already hold reset_mutex to avoid PCI access * while OCR is in progress. */ mutex_unlock(&instance->reset_mutex); megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); mutex_lock(&instance->reset_mutex); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d \n", __func__, __LINE__); break; } break; case DCMD_SUCCESS: pd_addr = ci->addr; if ((le32_to_cpu(ci->count) > (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) break; memset(instance->local_pd_list, 0, MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)); for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) { instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid = le16_to_cpu(pd_addr->deviceId); instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType = pd_addr->scsiDevType; instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState = MR_PD_STATE_SYSTEM; pd_addr++; } memcpy(instance->pd_list, instance->local_pd_list, sizeof(instance->pd_list)); break; } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); return ret; } /* * megasas_get_ld_list_info - Returns FW's ld_list structure * @instance: Adapter soft state * @ld_list: ld_list structure * * Issues an internal command (DCMD) to get the FW's controller PD * list structure. This information is mainly used to find out SYSTEM * supported by the FW. */ static int megasas_get_ld_list(struct megasas_instance *instance) { int ret = 0, ld_index = 0, ids = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_LD_LIST *ci; dma_addr_t ci_h = 0; u32 ld_count; ci = instance->ld_list_buf; ci_h = instance->ld_list_buf_h; cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_list: Failed to get cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); if (instance->supportmax256vd) dcmd->mbox.b[0] = 1; dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST)); dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST); dcmd->pad_0 = 0; megasas_set_dma_settings(instance, dcmd, ci_h, sizeof(struct MR_LD_LIST)); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); else ret = megasas_issue_polled(instance, cmd); ld_count = le32_to_cpu(ci->ldCount); switch (ret) { case DCMD_FAILED: megaraid_sas_kill_hba(instance); break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; /* * DCMD failed from AEN path. * AEN path already hold reset_mutex to avoid PCI access * while OCR is in progress. */ mutex_unlock(&instance->reset_mutex); megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); mutex_lock(&instance->reset_mutex); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } break; case DCMD_SUCCESS: if (ld_count > instance->fw_supported_vd_count) break; memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT); for (ld_index = 0; ld_index < ld_count; ld_index++) { if (ci->ldList[ld_index].state != 0) { ids = ci->ldList[ld_index].ref.targetId; instance->ld_ids[ids] = ci->ldList[ld_index].ref.targetId; } } break; } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); return ret; } /** * megasas_ld_list_query - Returns FW's ld_list structure * @instance: Adapter soft state * @ld_list: ld_list structure * * Issues an internal command (DCMD) to get the FW's controller PD * list structure. This information is mainly used to find out SYSTEM * supported by the FW. */ static int megasas_ld_list_query(struct megasas_instance *instance, u8 query_type) { int ret = 0, ld_index = 0, ids = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_LD_TARGETID_LIST *ci; dma_addr_t ci_h = 0; u32 tgtid_count; ci = instance->ld_targetid_list_buf; ci_h = instance->ld_targetid_list_buf_h; cmd = megasas_get_cmd(instance); if (!cmd) { dev_warn(&instance->pdev->dev, "megasas_ld_list_query: Failed to get cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.b[0] = query_type; if (instance->supportmax256vd) dcmd->mbox.b[2] = 1; dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST)); dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY); dcmd->pad_0 = 0; megasas_set_dma_settings(instance, dcmd, ci_h, sizeof(struct MR_LD_TARGETID_LIST)); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); else ret = megasas_issue_polled(instance, cmd); switch (ret) { case DCMD_FAILED: dev_info(&instance->pdev->dev, "DCMD not supported by firmware - %s %d\n", __func__, __LINE__); ret = megasas_get_ld_list(instance); break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; /* * DCMD failed from AEN path. * AEN path already hold reset_mutex to avoid PCI access * while OCR is in progress. */ mutex_unlock(&instance->reset_mutex); megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); mutex_lock(&instance->reset_mutex); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } break; case DCMD_SUCCESS: tgtid_count = le32_to_cpu(ci->count); if ((tgtid_count > (instance->fw_supported_vd_count))) break; memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS); for (ld_index = 0; ld_index < tgtid_count; ld_index++) { ids = ci->targetId[ld_index]; instance->ld_ids[ids] = ci->targetId[ld_index]; } break; } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); return ret; } /** * dcmd.opcode - MR_DCMD_CTRL_DEVICE_LIST_GET * dcmd.mbox - reserved * dcmd.sge IN - ptr to return MR_HOST_DEVICE_LIST structure * Desc: This DCMD will return the combined device list * Status: MFI_STAT_OK - List returned successfully * MFI_STAT_INVALID_CMD - Firmware support for the feature has been * disabled * @instance: Adapter soft state * @is_probe: Driver probe check * Return: 0 if DCMD succeeded * non-zero if failed */ int megasas_host_device_list_query(struct megasas_instance *instance, bool is_probe) { int ret, i, target_id; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_HOST_DEVICE_LIST *ci; u32 count; dma_addr_t ci_h; ci = instance->host_device_list_buf; ci_h = instance->host_device_list_buf_h; cmd = megasas_get_cmd(instance); if (!cmd) { dev_warn(&instance->pdev->dev, "%s: failed to get cmd\n", __func__); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.b[0] = is_probe ? 0 : 1; dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(HOST_DEVICE_LIST_SZ); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_DEVICE_LIST_GET); megasas_set_dma_settings(instance, dcmd, ci_h, HOST_DEVICE_LIST_SZ); if (!instance->mask_interrupts) { ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); } else { ret = megasas_issue_polled(instance, cmd); cmd->flags |= DRV_DCMD_SKIP_REFIRE; } switch (ret) { case DCMD_SUCCESS: /* Fill the internal pd_list and ld_ids array based on * targetIds returned by FW */ count = le32_to_cpu(ci->count); memset(instance->local_pd_list, 0, MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)); memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT); for (i = 0; i < count; i++) { target_id = le16_to_cpu(ci->host_device_list[i].target_id); if (ci->host_device_list[i].flags.u.bits.is_sys_pd) { instance->local_pd_list[target_id].tid = target_id; instance->local_pd_list[target_id].driveType = ci->host_device_list[i].scsi_type; instance->local_pd_list[target_id].driveState = MR_PD_STATE_SYSTEM; } else { instance->ld_ids[target_id] = target_id; } } memcpy(instance->pd_list, instance->local_pd_list, sizeof(instance->pd_list)); break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } break; case DCMD_FAILED: dev_err(&instance->pdev->dev, "%s: MR_DCMD_CTRL_DEVICE_LIST_GET failed\n", __func__); break; } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); return ret; } /* * megasas_update_ext_vd_details : Update details w.r.t Extended VD * instance : Controller's instance */ static void megasas_update_ext_vd_details(struct megasas_instance *instance) { struct fusion_context *fusion; u32 ventura_map_sz = 0; fusion = instance->ctrl_context; /* For MFI based controllers return dummy success */ if (!fusion) return; instance->supportmax256vd = instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs; /* Below is additional check to address future FW enhancement */ if (instance->ctrl_info_buf->max_lds > 64) instance->supportmax256vd = 1; instance->drv_supported_vd_count = MEGASAS_MAX_LD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL; instance->drv_supported_pd_count = MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL; if (instance->supportmax256vd) { instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES_EXT; instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES; } else { instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES; instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES; } dev_info(&instance->pdev->dev, "FW provided supportMaxExtLDs: %d\tmax_lds: %d\n", instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs ? 1 : 0, instance->ctrl_info_buf->max_lds); if (instance->max_raid_mapsize) { ventura_map_sz = instance->max_raid_mapsize * MR_MIN_MAP_SIZE; /* 64k */ fusion->current_map_sz = ventura_map_sz; fusion->max_map_sz = ventura_map_sz; } else { fusion->old_map_sz = sizeof(struct MR_FW_RAID_MAP) + (sizeof(struct MR_LD_SPAN_MAP) * (instance->fw_supported_vd_count - 1)); fusion->new_map_sz = sizeof(struct MR_FW_RAID_MAP_EXT); fusion->max_map_sz = max(fusion->old_map_sz, fusion->new_map_sz); if (instance->supportmax256vd) fusion->current_map_sz = fusion->new_map_sz; else fusion->current_map_sz = fusion->old_map_sz; } /* irrespective of FW raid maps, driver raid map is constant */ fusion->drv_map_sz = sizeof(struct MR_DRV_RAID_MAP_ALL); } /* * dcmd.opcode - MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES * dcmd.hdr.length - number of bytes to read * dcmd.sge - Ptr to MR_SNAPDUMP_PROPERTIES * Desc: Fill in snapdump properties * Status: MFI_STAT_OK- Command successful */ void megasas_get_snapdump_properties(struct megasas_instance *instance) { int ret = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct MR_SNAPDUMP_PROPERTIES *ci; dma_addr_t ci_h = 0; ci = instance->snapdump_prop; ci_h = instance->snapdump_prop_h; if (!ci) return; cmd = megasas_get_cmd(instance); if (!cmd) { dev_dbg(&instance->pdev->dev, "Failed to get a free cmd\n"); return; } dcmd = &cmd->frame->dcmd; memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_SNAPDUMP_PROPERTIES)); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES); megasas_set_dma_settings(instance, dcmd, ci_h, sizeof(struct MR_SNAPDUMP_PROPERTIES)); if (!instance->mask_interrupts) { ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); } else { ret = megasas_issue_polled(instance, cmd); cmd->flags |= DRV_DCMD_SKIP_REFIRE; } switch (ret) { case DCMD_SUCCESS: instance->snapdump_wait_time = min_t(u8, ci->trigger_min_num_sec_before_ocr, MEGASAS_MAX_SNAP_DUMP_WAIT_TIME); break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); } /** * megasas_get_controller_info - Returns FW's controller structure * @instance: Adapter soft state * * Issues an internal command (DCMD) to get the FW's controller structure. * This information is mainly used to find out the maximum IO transfer per * command supported by the FW. */ int megasas_get_ctrl_info(struct megasas_instance *instance) { int ret = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct megasas_ctrl_info *ci; dma_addr_t ci_h = 0; ci = instance->ctrl_info_buf; ci_h = instance->ctrl_info_buf_h; cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a free cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(ci, 0, sizeof(*ci)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info)); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO); dcmd->mbox.b[0] = 1; megasas_set_dma_settings(instance, dcmd, ci_h, sizeof(struct megasas_ctrl_info)); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) { ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); } else { ret = megasas_issue_polled(instance, cmd); cmd->flags |= DRV_DCMD_SKIP_REFIRE; } switch (ret) { case DCMD_SUCCESS: /* Save required controller information in * CPU endianness format. */ le32_to_cpus((u32 *)&ci->properties.OnOffProperties); le16_to_cpus((u16 *)&ci->properties.on_off_properties2); le32_to_cpus((u32 *)&ci->adapterOperations2); le32_to_cpus((u32 *)&ci->adapterOperations3); le16_to_cpus((u16 *)&ci->adapter_operations4); /* Update the latest Ext VD info. * From Init path, store current firmware details. * From OCR path, detect any firmware properties changes. * in case of Firmware upgrade without system reboot. */ megasas_update_ext_vd_details(instance); instance->use_seqnum_jbod_fp = ci->adapterOperations3.useSeqNumJbodFP; instance->support_morethan256jbod = ci->adapter_operations4.support_pd_map_target_id; instance->support_nvme_passthru = ci->adapter_operations4.support_nvme_passthru; instance->task_abort_tmo = ci->TaskAbortTO; instance->max_reset_tmo = ci->MaxResetTO; /*Check whether controller is iMR or MR */ instance->is_imr = (ci->memory_size ? 0 : 1); instance->snapdump_wait_time = (ci->properties.on_off_properties2.enable_snap_dump ? MEGASAS_DEFAULT_SNAP_DUMP_WAIT_TIME : 0); instance->enable_fw_dev_list = ci->properties.on_off_properties2.enable_fw_dev_list; dev_info(&instance->pdev->dev, "controller type\t: %s(%dMB)\n", instance->is_imr ? "iMR" : "MR", le16_to_cpu(ci->memory_size)); instance->disableOnlineCtrlReset = ci->properties.OnOffProperties.disableOnlineCtrlReset; instance->secure_jbod_support = ci->adapterOperations3.supportSecurityonJBOD; dev_info(&instance->pdev->dev, "Online Controller Reset(OCR)\t: %s\n", instance->disableOnlineCtrlReset ? "Disabled" : "Enabled"); dev_info(&instance->pdev->dev, "Secure JBOD support\t: %s\n", instance->secure_jbod_support ? "Yes" : "No"); dev_info(&instance->pdev->dev, "NVMe passthru support\t: %s\n", instance->support_nvme_passthru ? "Yes" : "No"); dev_info(&instance->pdev->dev, "FW provided TM TaskAbort/Reset timeout\t: %d secs/%d secs\n", instance->task_abort_tmo, instance->max_reset_tmo); break; case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } break; case DCMD_FAILED: megaraid_sas_kill_hba(instance); break; } if (ret != DCMD_TIMEOUT) megasas_return_cmd(instance, cmd); return ret; } /* * megasas_set_crash_dump_params - Sends address of crash dump DMA buffer * to firmware * * @instance: Adapter soft state * @crash_buf_state - tell FW to turn ON/OFF crash dump feature MR_CRASH_BUF_TURN_OFF = 0 MR_CRASH_BUF_TURN_ON = 1 * @return 0 on success non-zero on failure. * Issues an internal command (DCMD) to set parameters for crash dump feature. * Driver will send address of crash dump DMA buffer and set mbox to tell FW * that driver supports crash dump feature. This DCMD will be sent only if * crash dump feature is supported by the FW. * */ int megasas_set_crash_dump_params(struct megasas_instance *instance, u8 crash_buf_state) { int ret = 0; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; cmd = megasas_get_cmd(instance); if (!cmd) { dev_err(&instance->pdev->dev, "Failed to get a free cmd\n"); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.b[0] = crash_buf_state; dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = MFI_STAT_INVALID_STATUS; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_NONE; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(CRASH_DMA_BUF_SIZE); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SET_CRASH_DUMP_PARAMS); megasas_set_dma_settings(instance, dcmd, instance->crash_dump_h, CRASH_DMA_BUF_SIZE); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); else ret = megasas_issue_polled(instance, cmd); if (ret == DCMD_TIMEOUT) { switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } } else megasas_return_cmd(instance, cmd); return ret; } /** * megasas_issue_init_mfi - Initializes the FW * @instance: Adapter soft state * * Issues the INIT MFI cmd */ static int megasas_issue_init_mfi(struct megasas_instance *instance) { __le32 context; struct megasas_cmd *cmd; struct megasas_init_frame *init_frame; struct megasas_init_queue_info *initq_info; dma_addr_t init_frame_h; dma_addr_t initq_info_h; /* * Prepare a init frame. Note the init frame points to queue info * structure. Each frame has SGL allocated after first 64 bytes. For * this frame - since we don't need any SGL - we use SGL's space as * queue info structure * * We will not get a NULL command below. We just created the pool. */ cmd = megasas_get_cmd(instance); init_frame = (struct megasas_init_frame *)cmd->frame; initq_info = (struct megasas_init_queue_info *) ((unsigned long)init_frame + 64); init_frame_h = cmd->frame_phys_addr; initq_info_h = init_frame_h + 64; context = init_frame->context; memset(init_frame, 0, MEGAMFI_FRAME_SIZE); memset(initq_info, 0, sizeof(struct megasas_init_queue_info)); init_frame->context = context; initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1); initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h); initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h); initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h); init_frame->cmd = MFI_CMD_INIT; init_frame->cmd_status = MFI_STAT_INVALID_STATUS; init_frame->queue_info_new_phys_addr_lo = cpu_to_le32(lower_32_bits(initq_info_h)); init_frame->queue_info_new_phys_addr_hi = cpu_to_le32(upper_32_bits(initq_info_h)); init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info)); /* * disable the intr before firing the init frame to FW */ instance->instancet->disable_intr(instance); /* * Issue the init frame in polled mode */ if (megasas_issue_polled(instance, cmd)) { dev_err(&instance->pdev->dev, "Failed to init firmware\n"); megasas_return_cmd(instance, cmd); goto fail_fw_init; } megasas_return_cmd(instance, cmd); return 0; fail_fw_init: return -EINVAL; } static u32 megasas_init_adapter_mfi(struct megasas_instance *instance) { u32 context_sz; u32 reply_q_sz; /* * Get various operational parameters from status register */ instance->max_fw_cmds = instance->instancet->read_fw_status_reg(instance) & 0x00FFFF; /* * Reduce the max supported cmds by 1. This is to ensure that the * reply_q_sz (1 more than the max cmd that driver may send) * does not exceed max cmds that the FW can support */ instance->max_fw_cmds = instance->max_fw_cmds-1; instance->max_mfi_cmds = instance->max_fw_cmds; instance->max_num_sge = (instance->instancet->read_fw_status_reg(instance) & 0xFF0000) >> 0x10; /* * For MFI skinny adapters, MEGASAS_SKINNY_INT_CMDS commands * are reserved for IOCTL + driver's internal DCMDs. */ if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) { instance->max_scsi_cmds = (instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS); sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS); } else { instance->max_scsi_cmds = (instance->max_fw_cmds - MEGASAS_INT_CMDS); sema_init(&instance->ioctl_sem, (MEGASAS_MFI_IOCTL_CMDS)); } instance->cur_can_queue = instance->max_scsi_cmds; /* * Create a pool of commands */ if (megasas_alloc_cmds(instance)) goto fail_alloc_cmds; /* * Allocate memory for reply queue. Length of reply queue should * be _one_ more than the maximum commands handled by the firmware. * * Note: When FW completes commands, it places corresponding contex * values in this circular reply queue. This circular queue is a fairly * typical producer-consumer queue. FW is the producer (of completed * commands) and the driver is the consumer. */ context_sz = sizeof(u32); reply_q_sz = context_sz * (instance->max_fw_cmds + 1); instance->reply_queue = dma_alloc_coherent(&instance->pdev->dev, reply_q_sz, &instance->reply_queue_h, GFP_KERNEL); if (!instance->reply_queue) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Out of DMA mem for reply queue\n"); goto fail_reply_queue; } if (megasas_issue_init_mfi(instance)) goto fail_fw_init; if (megasas_get_ctrl_info(instance)) { dev_err(&instance->pdev->dev, "(%d): Could get controller info " "Fail from %s %d\n", instance->unique_id, __func__, __LINE__); goto fail_fw_init; } instance->fw_support_ieee = 0; instance->fw_support_ieee = (instance->instancet->read_fw_status_reg(instance) & 0x04000000); dev_notice(&instance->pdev->dev, "megasas_init_mfi: fw_support_ieee=%d", instance->fw_support_ieee); if (instance->fw_support_ieee) instance->flag_ieee = 1; return 0; fail_fw_init: dma_free_coherent(&instance->pdev->dev, reply_q_sz, instance->reply_queue, instance->reply_queue_h); fail_reply_queue: megasas_free_cmds(instance); fail_alloc_cmds: return 1; } /* * megasas_setup_irqs_ioapic - register legacy interrupts. * @instance: Adapter soft state * * Do not enable interrupt, only setup ISRs. * * Return 0 on success. */ static int megasas_setup_irqs_ioapic(struct megasas_instance *instance) { struct pci_dev *pdev; pdev = instance->pdev; instance->irq_context[0].instance = instance; instance->irq_context[0].MSIxIndex = 0; if (request_irq(pci_irq_vector(pdev, 0), instance->instancet->service_isr, IRQF_SHARED, "megasas", &instance->irq_context[0])) { dev_err(&instance->pdev->dev, "Failed to register IRQ from %s %d\n", __func__, __LINE__); return -1; } return 0; } /** * megasas_setup_irqs_msix - register MSI-x interrupts. * @instance: Adapter soft state * @is_probe: Driver probe check * * Do not enable interrupt, only setup ISRs. * * Return 0 on success. */ static int megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe) { int i, j; struct pci_dev *pdev; pdev = instance->pdev; /* Try MSI-x */ for (i = 0; i < instance->msix_vectors; i++) { instance->irq_context[i].instance = instance; instance->irq_context[i].MSIxIndex = i; if (request_irq(pci_irq_vector(pdev, i), instance->instancet->service_isr, 0, "megasas", &instance->irq_context[i])) { dev_err(&instance->pdev->dev, "Failed to register IRQ for vector %d.\n", i); for (j = 0; j < i; j++) free_irq(pci_irq_vector(pdev, j), &instance->irq_context[j]); /* Retry irq register for IO_APIC*/ instance->msix_vectors = 0; if (is_probe) { pci_free_irq_vectors(instance->pdev); return megasas_setup_irqs_ioapic(instance); } else { return -1; } } } return 0; } /* * megasas_destroy_irqs- unregister interrupts. * @instance: Adapter soft state * return: void */ static void megasas_destroy_irqs(struct megasas_instance *instance) { int i; if (instance->msix_vectors) for (i = 0; i < instance->msix_vectors; i++) { free_irq(pci_irq_vector(instance->pdev, i), &instance->irq_context[i]); } else free_irq(pci_irq_vector(instance->pdev, 0), &instance->irq_context[0]); } /** * megasas_setup_jbod_map - setup jbod map for FP seq_number. * @instance: Adapter soft state * @is_probe: Driver probe check * * Return 0 on success. */ void megasas_setup_jbod_map(struct megasas_instance *instance) { int i; struct fusion_context *fusion = instance->ctrl_context; u32 pd_seq_map_sz; pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) + (sizeof(struct MR_PD_CFG_SEQ) * (MAX_PHYSICAL_DEVICES - 1)); if (reset_devices || !fusion || !instance->ctrl_info_buf->adapterOperations3.useSeqNumJbodFP) { dev_info(&instance->pdev->dev, "Jbod map is not supported %s %d\n", __func__, __LINE__); instance->use_seqnum_jbod_fp = false; return; } if (fusion->pd_seq_sync[0]) goto skip_alloc; for (i = 0; i < JBOD_MAPS_COUNT; i++) { fusion->pd_seq_sync[i] = dma_alloc_coherent (&instance->pdev->dev, pd_seq_map_sz, &fusion->pd_seq_phys[i], GFP_KERNEL); if (!fusion->pd_seq_sync[i]) { dev_err(&instance->pdev->dev, "Failed to allocate memory from %s %d\n", __func__, __LINE__); if (i == 1) { dma_free_coherent(&instance->pdev->dev, pd_seq_map_sz, fusion->pd_seq_sync[0], fusion->pd_seq_phys[0]); fusion->pd_seq_sync[0] = NULL; } instance->use_seqnum_jbod_fp = false; return; } } skip_alloc: if (!megasas_sync_pd_seq_num(instance, false) && !megasas_sync_pd_seq_num(instance, true)) instance->use_seqnum_jbod_fp = true; else instance->use_seqnum_jbod_fp = false; } static void megasas_setup_reply_map(struct megasas_instance *instance) { const struct cpumask *mask; unsigned int queue, cpu; for (queue = 0; queue < instance->msix_vectors; queue++) { mask = pci_irq_get_affinity(instance->pdev, queue); if (!mask) goto fallback; for_each_cpu(cpu, mask) instance->reply_map[cpu] = queue; } return; fallback: for_each_possible_cpu(cpu) instance->reply_map[cpu] = cpu % instance->msix_vectors; } /** * megasas_get_device_list - Get the PD and LD device list from FW. * @instance: Adapter soft state * @return: Success or failure * * Issue DCMDs to Firmware to get the PD and LD list. * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list. */ static int megasas_get_device_list(struct megasas_instance *instance) { memset(instance->pd_list, 0, (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list))); memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS); if (instance->enable_fw_dev_list) { if (megasas_host_device_list_query(instance, true)) return FAILED; } else { if (megasas_get_pd_list(instance) < 0) { dev_err(&instance->pdev->dev, "failed to get PD list\n"); return FAILED; } if (megasas_ld_list_query(instance, MR_LD_QUERY_TYPE_EXPOSED_TO_HOST)) { dev_err(&instance->pdev->dev, "failed to get LD list\n"); return FAILED; } } return SUCCESS; } /** * megasas_init_fw - Initializes the FW * @instance: Adapter soft state * * This is the main function for initializing firmware */ static int megasas_init_fw(struct megasas_instance *instance) { u32 max_sectors_1; u32 max_sectors_2, tmp_sectors, msix_enable; u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg; resource_size_t base_addr; struct megasas_ctrl_info *ctrl_info = NULL; unsigned long bar_list; int i, j, loop, fw_msix_count = 0; struct IOV_111 *iovPtr; struct fusion_context *fusion; bool do_adp_reset = true; fusion = instance->ctrl_context; /* Find first memory bar */ bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM); instance->bar = find_first_bit(&bar_list, BITS_PER_LONG); if (pci_request_selected_regions(instance->pdev, 1<<instance->bar, "megasas: LSI")) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "IO memory region busy!\n"); return -EBUSY; } base_addr = pci_resource_start(instance->pdev, instance->bar); instance->reg_set = ioremap_nocache(base_addr, 8192); if (!instance->reg_set) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to map IO mem\n"); goto fail_ioremap; } if (instance->adapter_type != MFI_SERIES) instance->instancet = &megasas_instance_template_fusion; else { switch (instance->pdev->device) { case PCI_DEVICE_ID_LSI_SAS1078R: case PCI_DEVICE_ID_LSI_SAS1078DE: instance->instancet = &megasas_instance_template_ppc; break; case PCI_DEVICE_ID_LSI_SAS1078GEN2: case PCI_DEVICE_ID_LSI_SAS0079GEN2: instance->instancet = &megasas_instance_template_gen2; break; case PCI_DEVICE_ID_LSI_SAS0073SKINNY: case PCI_DEVICE_ID_LSI_SAS0071SKINNY: instance->instancet = &megasas_instance_template_skinny; break; case PCI_DEVICE_ID_LSI_SAS1064R: case PCI_DEVICE_ID_DELL_PERC5: default: instance->instancet = &megasas_instance_template_xscale; instance->pd_list_not_supported = 1; break; } } if (megasas_transition_to_ready(instance, 0)) { if (instance->adapter_type >= INVADER_SERIES) { status_reg = instance->instancet->read_fw_status_reg( instance); do_adp_reset = status_reg & MFI_RESET_ADAPTER; } if (do_adp_reset) { atomic_set(&instance->fw_reset_no_pci_access, 1); instance->instancet->adp_reset (instance, instance->reg_set); atomic_set(&instance->fw_reset_no_pci_access, 0); dev_info(&instance->pdev->dev, "FW restarted successfully from %s!\n", __func__); /*waiting for about 30 second before retry*/ ssleep(30); if (megasas_transition_to_ready(instance, 0)) goto fail_ready_state; } else { goto fail_ready_state; } } megasas_init_ctrl_params(instance); if (megasas_set_dma_mask(instance)) goto fail_ready_state; if (megasas_alloc_ctrl_mem(instance)) goto fail_alloc_dma_buf; if (megasas_alloc_ctrl_dma_buffers(instance)) goto fail_alloc_dma_buf; fusion = instance->ctrl_context; if (instance->adapter_type >= VENTURA_SERIES) { scratch_pad_2 = megasas_readl(instance, &instance->reg_set->outbound_scratch_pad_2); instance->max_raid_mapsize = ((scratch_pad_2 >> MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) & MR_MAX_RAID_MAP_SIZE_MASK); } /* Check if MSI-X is supported while in ready state */ msix_enable = (instance->instancet->read_fw_status_reg(instance) & 0x4000000) >> 0x1a; if (msix_enable && !msix_disable) { int irq_flags = PCI_IRQ_MSIX; scratch_pad_1 = megasas_readl (instance, &instance->reg_set->outbound_scratch_pad_1); /* Check max MSI-X vectors */ if (fusion) { if (instance->adapter_type == THUNDERBOLT_SERIES) { /* Thunderbolt Series*/ instance->msix_vectors = (scratch_pad_1 & MR_MAX_REPLY_QUEUES_OFFSET) + 1; fw_msix_count = instance->msix_vectors; } else { instance->msix_vectors = ((scratch_pad_1 & MR_MAX_REPLY_QUEUES_EXT_OFFSET) >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1; /* * For Invader series, > 8 MSI-x vectors * supported by FW/HW implies combined * reply queue mode is enabled. * For Ventura series, > 16 MSI-x vectors * supported by FW/HW implies combined * reply queue mode is enabled. */ switch (instance->adapter_type) { case INVADER_SERIES: if (instance->msix_vectors > 8) instance->msix_combined = true; break; case AERO_SERIES: case VENTURA_SERIES: if (instance->msix_vectors > 16) instance->msix_combined = true; break; } if (rdpq_enable) instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ? 1 : 0; fw_msix_count = instance->msix_vectors; /* Save 1-15 reply post index address to local memory * Index 0 is already saved from reg offset * MPI2_REPLY_POST_HOST_INDEX_OFFSET */ for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) { instance->reply_post_host_index_addr[loop] = (u32 __iomem *) ((u8 __iomem *)instance->reg_set + MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET + (loop * 0x10)); } } if (msix_vectors) instance->msix_vectors = min(msix_vectors, instance->msix_vectors); } else /* MFI adapters */ instance->msix_vectors = 1; /* Don't bother allocating more MSI-X vectors than cpus */ instance->msix_vectors = min(instance->msix_vectors, (unsigned int)num_online_cpus()); if (smp_affinity_enable) irq_flags |= PCI_IRQ_AFFINITY; i = pci_alloc_irq_vectors(instance->pdev, 1, instance->msix_vectors, irq_flags); if (i > 0) instance->msix_vectors = i; else instance->msix_vectors = 0; } /* * MSI-X host index 0 is common for all adapter. * It is used for all MPT based Adapters. */ if (instance->msix_combined) { instance->reply_post_host_index_addr[0] = (u32 *)((u8 *)instance->reg_set + MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET); } else { instance->reply_post_host_index_addr[0] = (u32 *)((u8 *)instance->reg_set + MPI2_REPLY_POST_HOST_INDEX_OFFSET); } if (!instance->msix_vectors) { i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_LEGACY); if (i < 0) goto fail_init_adapter; } megasas_setup_reply_map(instance); dev_info(&instance->pdev->dev, "firmware supports msix\t: (%d)", fw_msix_count); dev_info(&instance->pdev->dev, "current msix/online cpus\t: (%d/%d)\n", instance->msix_vectors, (unsigned int)num_online_cpus()); dev_info(&instance->pdev->dev, "RDPQ mode\t: (%s)\n", instance->is_rdpq ? "enabled" : "disabled"); tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet, (unsigned long)instance); /* * Below are default value for legacy Firmware. * non-fusion based controllers */ instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES; instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES; /* Get operational params, sge flags, send init cmd to controller */ if (instance->instancet->init_adapter(instance)) goto fail_init_adapter; if (instance->adapter_type >= VENTURA_SERIES) { scratch_pad_3 = megasas_readl(instance, &instance->reg_set->outbound_scratch_pad_3); if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >= MR_DEFAULT_NVME_PAGE_SHIFT) instance->nvme_page_size = (1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK)); dev_info(&instance->pdev->dev, "NVME page size\t: (%d)\n", instance->nvme_page_size); } if (instance->msix_vectors ? megasas_setup_irqs_msix(instance, 1) : megasas_setup_irqs_ioapic(instance)) goto fail_init_adapter; instance->instancet->enable_intr(instance); dev_info(&instance->pdev->dev, "INIT adapter done\n"); megasas_setup_jbod_map(instance); if (megasas_get_device_list(instance) != SUCCESS) { dev_err(&instance->pdev->dev, "%s: megasas_get_device_list failed\n", __func__); goto fail_get_ld_pd_list; } /* stream detection initialization */ if (instance->adapter_type >= VENTURA_SERIES) { fusion->stream_detect_by_ld = kcalloc(MAX_LOGICAL_DRIVES_EXT, sizeof(struct LD_STREAM_DETECT *), GFP_KERNEL); if (!fusion->stream_detect_by_ld) { dev_err(&instance->pdev->dev, "unable to allocate stream detection for pool of LDs\n"); goto fail_get_ld_pd_list; } for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) { fusion->stream_detect_by_ld[i] = kzalloc(sizeof(struct LD_STREAM_DETECT), GFP_KERNEL); if (!fusion->stream_detect_by_ld[i]) { dev_err(&instance->pdev->dev, "unable to allocate stream detect by LD\n "); for (j = 0; j < i; ++j) kfree(fusion->stream_detect_by_ld[j]); kfree(fusion->stream_detect_by_ld); fusion->stream_detect_by_ld = NULL; goto fail_get_ld_pd_list; } fusion->stream_detect_by_ld[i]->mru_bit_map = MR_STREAM_BITMAP; } } /* * Compute the max allowed sectors per IO: The controller info has two * limits on max sectors. Driver should use the minimum of these two. * * 1 << stripe_sz_ops.min = max sectors per strip * * Note that older firmwares ( < FW ver 30) didn't report information * to calculate max_sectors_1. So the number ended up as zero always. */ tmp_sectors = 0; ctrl_info = instance->ctrl_info_buf; max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) * le16_to_cpu(ctrl_info->max_strips_per_io); max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size); tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2); instance->peerIsPresent = ctrl_info->cluster.peerIsPresent; instance->passive = ctrl_info->cluster.passive; memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId)); instance->UnevenSpanSupport = ctrl_info->adapterOperations2.supportUnevenSpans; if (instance->UnevenSpanSupport) { struct fusion_context *fusion = instance->ctrl_context; if (MR_ValidateMapInfo(instance, instance->map_id)) fusion->fast_path_io = 1; else fusion->fast_path_io = 0; } if (ctrl_info->host_interface.SRIOV) { instance->requestorId = ctrl_info->iov.requestorId; if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) { if (!ctrl_info->adapterOperations2.activePassive) instance->PlasmaFW111 = 1; dev_info(&instance->pdev->dev, "SR-IOV: firmware type: %s\n", instance->PlasmaFW111 ? "1.11" : "new"); if (instance->PlasmaFW111) { iovPtr = (struct IOV_111 *) ((unsigned char *)ctrl_info + IOV_111_OFFSET); instance->requestorId = iovPtr->requestorId; } } dev_info(&instance->pdev->dev, "SRIOV: VF requestorId %d\n", instance->requestorId); } instance->crash_dump_fw_support = ctrl_info->adapterOperations3.supportCrashDump; instance->crash_dump_drv_support = (instance->crash_dump_fw_support && instance->crash_dump_buf); if (instance->crash_dump_drv_support) megasas_set_crash_dump_params(instance, MR_CRASH_BUF_TURN_OFF); else { if (instance->crash_dump_buf) dma_free_coherent(&instance->pdev->dev, CRASH_DMA_BUF_SIZE, instance->crash_dump_buf, instance->crash_dump_h); instance->crash_dump_buf = NULL; } if (instance->snapdump_wait_time) { megasas_get_snapdump_properties(instance); dev_info(&instance->pdev->dev, "Snap dump wait time\t: %d\n", instance->snapdump_wait_time); } dev_info(&instance->pdev->dev, "pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n", le16_to_cpu(ctrl_info->pci.vendor_id), le16_to_cpu(ctrl_info->pci.device_id), le16_to_cpu(ctrl_info->pci.sub_vendor_id), le16_to_cpu(ctrl_info->pci.sub_device_id)); dev_info(&instance->pdev->dev, "unevenspan support : %s\n", instance->UnevenSpanSupport ? "yes" : "no"); dev_info(&instance->pdev->dev, "firmware crash dump : %s\n", instance->crash_dump_drv_support ? "yes" : "no"); dev_info(&instance->pdev->dev, "jbod sync map : %s\n", instance->use_seqnum_jbod_fp ? "yes" : "no"); instance->max_sectors_per_req = instance->max_num_sge * SGE_BUFFER_SIZE / 512; if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors)) instance->max_sectors_per_req = tmp_sectors; /* Check for valid throttlequeuedepth module parameter */ if (throttlequeuedepth && throttlequeuedepth <= instance->max_scsi_cmds) instance->throttlequeuedepth = throttlequeuedepth; else instance->throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH; if ((resetwaittime < 1) || (resetwaittime > MEGASAS_RESET_WAIT_TIME)) resetwaittime = MEGASAS_RESET_WAIT_TIME; if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT)) scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT; /* Launch SR-IOV heartbeat timer */ if (instance->requestorId) { if (!megasas_sriov_start_heartbeat(instance, 1)) { megasas_start_timer(instance); } else { instance->skip_heartbeat_timer_del = 1; goto fail_get_ld_pd_list; } } /* * Create and start watchdog thread which will monitor * controller state every 1 sec and trigger OCR when * it enters fault state */ if (instance->adapter_type != MFI_SERIES) if (megasas_fusion_start_watchdog(instance) != SUCCESS) goto fail_start_watchdog; return 0; fail_start_watchdog: if (instance->requestorId && !instance->skip_heartbeat_timer_del) del_timer_sync(&instance->sriov_heartbeat_timer); fail_get_ld_pd_list: instance->instancet->disable_intr(instance); megasas_destroy_irqs(instance); fail_init_adapter: if (instance->msix_vectors) pci_free_irq_vectors(instance->pdev); instance->msix_vectors = 0; fail_alloc_dma_buf: megasas_free_ctrl_dma_buffers(instance); megasas_free_ctrl_mem(instance); fail_ready_state: iounmap(instance->reg_set); fail_ioremap: pci_release_selected_regions(instance->pdev, 1<<instance->bar); dev_err(&instance->pdev->dev, "Failed from %s %d\n", __func__, __LINE__); return -EINVAL; } /** * megasas_release_mfi - Reverses the FW initialization * @instance: Adapter soft state */ static void megasas_release_mfi(struct megasas_instance *instance) { u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1); if (instance->reply_queue) dma_free_coherent(&instance->pdev->dev, reply_q_sz, instance->reply_queue, instance->reply_queue_h); megasas_free_cmds(instance); iounmap(instance->reg_set); pci_release_selected_regions(instance->pdev, 1<<instance->bar); } /** * megasas_get_seq_num - Gets latest event sequence numbers * @instance: Adapter soft state * @eli: FW event log sequence numbers information * * FW maintains a log of all events in a non-volatile area. Upper layers would * usually find out the latest sequence number of the events, the seq number at * the boot etc. They would "read" all the events below the latest seq number * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq * number), they would subsribe to AEN (asynchronous event notification) and * wait for the events to happen. */ static int megasas_get_seq_num(struct megasas_instance *instance, struct megasas_evt_log_info *eli) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; struct megasas_evt_log_info *el_info; dma_addr_t el_info_h = 0; int ret; cmd = megasas_get_cmd(instance); if (!cmd) { return -ENOMEM; } dcmd = &cmd->frame->dcmd; el_info = dma_zalloc_coherent(&instance->pdev->dev, sizeof(struct megasas_evt_log_info), &el_info_h, GFP_KERNEL); if (!el_info) { megasas_return_cmd(instance, cmd); return -ENOMEM; } memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info)); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO); megasas_set_dma_settings(instance, dcmd, el_info_h, sizeof(struct megasas_evt_log_info)); ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); if (ret != DCMD_SUCCESS) { dev_err(&instance->pdev->dev, "Failed from %s %d\n", __func__, __LINE__); goto dcmd_failed; } /* * Copy the data back into callers buffer */ eli->newest_seq_num = el_info->newest_seq_num; eli->oldest_seq_num = el_info->oldest_seq_num; eli->clear_seq_num = el_info->clear_seq_num; eli->shutdown_seq_num = el_info->shutdown_seq_num; eli->boot_seq_num = el_info->boot_seq_num; dcmd_failed: dma_free_coherent(&instance->pdev->dev, sizeof(struct megasas_evt_log_info), el_info, el_info_h); megasas_return_cmd(instance, cmd); return ret; } /** * megasas_register_aen - Registers for asynchronous event notification * @instance: Adapter soft state * @seq_num: The starting sequence number * @class_locale: Class of the event * * This function subscribes for AEN for events beyond the @seq_num. It requests * to be notified if and only if the event is of type @class_locale */ static int megasas_register_aen(struct megasas_instance *instance, u32 seq_num, u32 class_locale_word) { int ret_val; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; union megasas_evt_class_locale curr_aen; union megasas_evt_class_locale prev_aen; /* * If there an AEN pending already (aen_cmd), check if the * class_locale of that pending AEN is inclusive of the new * AEN request we currently have. If it is, then we don't have * to do anything. In other words, whichever events the current * AEN request is subscribing to, have already been subscribed * to. * * If the old_cmd is _not_ inclusive, then we have to abort * that command, form a class_locale that is superset of both * old and current and re-issue to the FW */ curr_aen.word = class_locale_word; if (instance->aen_cmd) { prev_aen.word = le32_to_cpu(instance->aen_cmd->frame->dcmd.mbox.w[1]); if ((curr_aen.members.class < MFI_EVT_CLASS_DEBUG) || (curr_aen.members.class > MFI_EVT_CLASS_DEAD)) { dev_info(&instance->pdev->dev, "%s %d out of range class %d send by application\n", __func__, __LINE__, curr_aen.members.class); return 0; } /* * A class whose enum value is smaller is inclusive of all * higher values. If a PROGRESS (= -1) was previously * registered, then a new registration requests for higher * classes need not be sent to FW. They are automatically * included. * * Locale numbers don't have such hierarchy. They are bitmap * values */ if ((prev_aen.members.class <= curr_aen.members.class) && !((prev_aen.members.locale & curr_aen.members.locale) ^ curr_aen.members.locale)) { /* * Previously issued event registration includes * current request. Nothing to do. */ return 0; } else { curr_aen.members.locale |= prev_aen.members.locale; if (prev_aen.members.class < curr_aen.members.class) curr_aen.members.class = prev_aen.members.class; instance->aen_cmd->abort_aen = 1; ret_val = megasas_issue_blocked_abort_cmd(instance, instance-> aen_cmd, 30); if (ret_val) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to abort " "previous AEN command\n"); return ret_val; } } } cmd = megasas_get_cmd(instance); if (!cmd) return -ENOMEM; dcmd = &cmd->frame->dcmd; memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail)); /* * Prepare DCMD for aen registration */ memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail)); dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT); dcmd->mbox.w[0] = cpu_to_le32(seq_num); instance->last_seq_num = seq_num; dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word); megasas_set_dma_settings(instance, dcmd, instance->evt_detail_h, sizeof(struct megasas_evt_detail)); if (instance->aen_cmd != NULL) { megasas_return_cmd(instance, cmd); return 0; } /* * Store reference to the cmd used to register for AEN. When an * application wants us to register for AEN, we have to abort this * cmd and re-register with a new EVENT LOCALE supplied by that app */ instance->aen_cmd = cmd; /* * Issue the aen registration frame */ instance->instancet->issue_dcmd(instance, cmd); return 0; } /* megasas_get_target_prop - Send DCMD with below details to firmware. * * This DCMD will fetch few properties of LD/system PD defined * in MR_TARGET_DEV_PROPERTIES. eg. Queue Depth, MDTS value. * * DCMD send by drivers whenever new target is added to the OS. * * dcmd.opcode - MR_DCMD_DEV_GET_TARGET_PROP * dcmd.mbox.b[0] - DCMD is to be fired for LD or system PD. * 0 = system PD, 1 = LD. * dcmd.mbox.s[1] - TargetID for LD/system PD. * dcmd.sge IN - Pointer to return MR_TARGET_DEV_PROPERTIES. * * @instance: Adapter soft state * @sdev: OS provided scsi device * * Returns 0 on success non-zero on failure. */ int megasas_get_target_prop(struct megasas_instance *instance, struct scsi_device *sdev) { int ret; struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; u16 targetId = (sdev->channel % 2) + sdev->id; cmd = megasas_get_cmd(instance); if (!cmd) { dev_err(&instance->pdev->dev, "Failed to get cmd %s\n", __func__); return -ENOMEM; } dcmd = &cmd->frame->dcmd; memset(instance->tgt_prop, 0, sizeof(*instance->tgt_prop)); memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->mbox.b[0] = MEGASAS_IS_LOGICAL(sdev); dcmd->mbox.s[1] = cpu_to_le16(targetId); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0xFF; dcmd->sge_count = 1; dcmd->flags = MFI_FRAME_DIR_READ; dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_TARGET_PROPERTIES)); dcmd->opcode = cpu_to_le32(MR_DCMD_DRV_GET_TARGET_PROP); megasas_set_dma_settings(instance, dcmd, instance->tgt_prop_h, sizeof(struct MR_TARGET_PROPERTIES)); if ((instance->adapter_type != MFI_SERIES) && !instance->mask_interrupts) ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS); else ret = megasas_issue_polled(instance, cmd); switch (ret) { case DCMD_TIMEOUT: switch (dcmd_timeout_ocr_possible(instance)) { case INITIATE_OCR: cmd->flags |= DRV_DCMD_SKIP_REFIRE; megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR); break; case KILL_ADAPTER: megaraid_sas_kill_hba(instance); break; case IGNORE_TIMEOUT: dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n", __func__, __LINE__); break; } break; default: megasas_return_cmd(instance, cmd); } if (ret != DCMD_SUCCESS) dev_err(&instance->pdev->dev, "return from %s %d return value %d\n", __func__, __LINE__, ret); return ret; } /** * megasas_start_aen - Subscribes to AEN during driver load time * @instance: Adapter soft state */ static int megasas_start_aen(struct megasas_instance *instance) { struct megasas_evt_log_info eli; union megasas_evt_class_locale class_locale; /* * Get the latest sequence number from FW */ memset(&eli, 0, sizeof(eli)); if (megasas_get_seq_num(instance, &eli)) return -1; /* * Register AEN with FW for latest sequence number plus 1 */ class_locale.members.reserved = 0; class_locale.members.locale = MR_EVT_LOCALE_ALL; class_locale.members.class = MR_EVT_CLASS_DEBUG; return megasas_register_aen(instance, le32_to_cpu(eli.newest_seq_num) + 1, class_locale.word); } /** * megasas_io_attach - Attaches this driver to SCSI mid-layer * @instance: Adapter soft state */ static int megasas_io_attach(struct megasas_instance *instance) { struct Scsi_Host *host = instance->host; /* * Export parameters required by SCSI mid-layer */ host->unique_id = instance->unique_id; host->can_queue = instance->max_scsi_cmds; host->this_id = instance->init_id; host->sg_tablesize = instance->max_num_sge; if (instance->fw_support_ieee) instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE; /* * Check if the module parameter value for max_sectors can be used */ if (max_sectors && max_sectors < instance->max_sectors_per_req) instance->max_sectors_per_req = max_sectors; else { if (max_sectors) { if (((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1078GEN2) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0079GEN2)) && (max_sectors <= MEGASAS_MAX_SECTORS)) { instance->max_sectors_per_req = max_sectors; } else { dev_info(&instance->pdev->dev, "max_sectors should be > 0" "and <= %d (or < 1MB for GEN2 controller)\n", instance->max_sectors_per_req); } } } host->max_sectors = instance->max_sectors_per_req; host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN; host->max_channel = MEGASAS_MAX_CHANNELS - 1; host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL; host->max_lun = MEGASAS_MAX_LUN; host->max_cmd_len = 16; /* * Notify the mid-layer about the new controller */ if (scsi_add_host(host, &instance->pdev->dev)) { dev_err(&instance->pdev->dev, "Failed to add host from %s %d\n", __func__, __LINE__); return -ENODEV; } return 0; } /** * megasas_set_dma_mask - Set DMA mask for supported controllers * * @instance: Adapter soft state * Description: * * For Ventura, driver/FW will operate in 63bit DMA addresses. * * For invader- * By default, driver/FW will operate in 32bit DMA addresses * for consistent DMA mapping but if 32 bit consistent * DMA mask fails, driver will try with 63 bit consistent * mask provided FW is true 63bit DMA capable * * For older controllers(Thunderbolt and MFI based adapters)- * driver/FW will operate in 32 bit consistent DMA addresses. */ static int megasas_set_dma_mask(struct megasas_instance *instance) { u64 consistent_mask; struct pci_dev *pdev; u32 scratch_pad_1; pdev = instance->pdev; consistent_mask = (instance->adapter_type >= VENTURA_SERIES) ? DMA_BIT_MASK(63) : DMA_BIT_MASK(32); if (IS_DMA64) { if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(63)) && dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))) goto fail_set_dma_mask; if ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) && (dma_set_coherent_mask(&pdev->dev, consistent_mask) && dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))) { /* * If 32 bit DMA mask fails, then try for 64 bit mask * for FW capable of handling 64 bit DMA. */ scratch_pad_1 = megasas_readl (instance, &instance->reg_set->outbound_scratch_pad_1); if (!(scratch_pad_1 & MR_CAN_HANDLE_64_BIT_DMA_OFFSET)) goto fail_set_dma_mask; else if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(63))) goto fail_set_dma_mask; } } else if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))) goto fail_set_dma_mask; if (pdev->dev.coherent_dma_mask == DMA_BIT_MASK(32)) instance->consistent_mask_64bit = false; else instance->consistent_mask_64bit = true; dev_info(&pdev->dev, "%s bit DMA mask and %s bit consistent mask\n", ((*pdev->dev.dma_mask == DMA_BIT_MASK(64)) ? "63" : "32"), (instance->consistent_mask_64bit ? "63" : "32")); return 0; fail_set_dma_mask: dev_err(&pdev->dev, "Failed to set DMA mask\n"); return -1; } /* * megasas_set_adapter_type - Set adapter type. * Supported controllers can be divided in * different categories- * enum MR_ADAPTER_TYPE { * MFI_SERIES = 1, * THUNDERBOLT_SERIES = 2, * INVADER_SERIES = 3, * VENTURA_SERIES = 4, * AERO_SERIES = 5, * }; * @instance: Adapter soft state * return: void */ static inline void megasas_set_adapter_type(struct megasas_instance *instance) { if ((instance->pdev->vendor == PCI_VENDOR_ID_DELL) && (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5)) { instance->adapter_type = MFI_SERIES; } else { switch (instance->pdev->device) { case PCI_DEVICE_ID_LSI_AERO_10E1: case PCI_DEVICE_ID_LSI_AERO_10E2: case PCI_DEVICE_ID_LSI_AERO_10E5: case PCI_DEVICE_ID_LSI_AERO_10E6: instance->adapter_type = AERO_SERIES; break; case PCI_DEVICE_ID_LSI_VENTURA: case PCI_DEVICE_ID_LSI_CRUSADER: case PCI_DEVICE_ID_LSI_HARPOON: case PCI_DEVICE_ID_LSI_TOMCAT: case PCI_DEVICE_ID_LSI_VENTURA_4PORT: case PCI_DEVICE_ID_LSI_CRUSADER_4PORT: instance->adapter_type = VENTURA_SERIES; break; case PCI_DEVICE_ID_LSI_FUSION: case PCI_DEVICE_ID_LSI_PLASMA: instance->adapter_type = THUNDERBOLT_SERIES; break; case PCI_DEVICE_ID_LSI_INVADER: case PCI_DEVICE_ID_LSI_INTRUDER: case PCI_DEVICE_ID_LSI_INTRUDER_24: case PCI_DEVICE_ID_LSI_CUTLASS_52: case PCI_DEVICE_ID_LSI_CUTLASS_53: case PCI_DEVICE_ID_LSI_FURY: instance->adapter_type = INVADER_SERIES; break; default: /* For all other supported controllers */ instance->adapter_type = MFI_SERIES; break; } } } static inline int megasas_alloc_mfi_ctrl_mem(struct megasas_instance *instance) { instance->producer = dma_alloc_coherent(&instance->pdev->dev, sizeof(u32), &instance->producer_h, GFP_KERNEL); instance->consumer = dma_alloc_coherent(&instance->pdev->dev, sizeof(u32), &instance->consumer_h, GFP_KERNEL); if (!instance->producer || !instance->consumer) { dev_err(&instance->pdev->dev, "Failed to allocate memory for producer, consumer\n"); return -1; } *instance->producer = 0; *instance->consumer = 0; return 0; } /** * megasas_alloc_ctrl_mem - Allocate per controller memory for core data * structures which are not common across MFI * adapters and fusion adapters. * For MFI based adapters, allocate producer and * consumer buffers. For fusion adapters, allocate * memory for fusion context. * @instance: Adapter soft state * return: 0 for SUCCESS */ static int megasas_alloc_ctrl_mem(struct megasas_instance *instance) { instance->reply_map = kcalloc(nr_cpu_ids, sizeof(unsigned int), GFP_KERNEL); if (!instance->reply_map) return -ENOMEM; switch (instance->adapter_type) { case MFI_SERIES: if (megasas_alloc_mfi_ctrl_mem(instance)) goto fail; break; case AERO_SERIES: case VENTURA_SERIES: case THUNDERBOLT_SERIES: case INVADER_SERIES: if (megasas_alloc_fusion_context(instance)) goto fail; break; } return 0; fail: kfree(instance->reply_map); instance->reply_map = NULL; return -ENOMEM; } /* * megasas_free_ctrl_mem - Free fusion context for fusion adapters and * producer, consumer buffers for MFI adapters * * @instance - Adapter soft instance * */ static inline void megasas_free_ctrl_mem(struct megasas_instance *instance) { kfree(instance->reply_map); if (instance->adapter_type == MFI_SERIES) { if (instance->producer) dma_free_coherent(&instance->pdev->dev, sizeof(u32), instance->producer, instance->producer_h); if (instance->consumer) dma_free_coherent(&instance->pdev->dev, sizeof(u32), instance->consumer, instance->consumer_h); } else { megasas_free_fusion_context(instance); } } /** * megasas_alloc_ctrl_dma_buffers - Allocate consistent DMA buffers during * driver load time * * @instance- Adapter soft instance * @return- O for SUCCESS */ static inline int megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance) { struct pci_dev *pdev = instance->pdev; struct fusion_context *fusion = instance->ctrl_context; instance->evt_detail = dma_alloc_coherent(&pdev->dev, sizeof(struct megasas_evt_detail), &instance->evt_detail_h, GFP_KERNEL); if (!instance->evt_detail) { dev_err(&instance->pdev->dev, "Failed to allocate event detail buffer\n"); return -ENOMEM; } if (fusion) { fusion->ioc_init_request = dma_alloc_coherent(&pdev->dev, sizeof(struct MPI2_IOC_INIT_REQUEST), &fusion->ioc_init_request_phys, GFP_KERNEL); if (!fusion->ioc_init_request) { dev_err(&pdev->dev, "Failed to allocate PD list buffer\n"); return -ENOMEM; } instance->snapdump_prop = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_SNAPDUMP_PROPERTIES), &instance->snapdump_prop_h, GFP_KERNEL); if (!instance->snapdump_prop) dev_err(&pdev->dev, "Failed to allocate snapdump properties buffer\n"); instance->host_device_list_buf = dma_alloc_coherent(&pdev->dev, HOST_DEVICE_LIST_SZ, &instance->host_device_list_buf_h, GFP_KERNEL); if (!instance->host_device_list_buf) { dev_err(&pdev->dev, "Failed to allocate targetid list buffer\n"); return -ENOMEM; } } instance->pd_list_buf = dma_alloc_coherent(&pdev->dev, MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &instance->pd_list_buf_h, GFP_KERNEL); if (!instance->pd_list_buf) { dev_err(&pdev->dev, "Failed to allocate PD list buffer\n"); return -ENOMEM; } instance->ctrl_info_buf = dma_alloc_coherent(&pdev->dev, sizeof(struct megasas_ctrl_info), &instance->ctrl_info_buf_h, GFP_KERNEL); if (!instance->ctrl_info_buf) { dev_err(&pdev->dev, "Failed to allocate controller info buffer\n"); return -ENOMEM; } instance->ld_list_buf = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_LD_LIST), &instance->ld_list_buf_h, GFP_KERNEL); if (!instance->ld_list_buf) { dev_err(&pdev->dev, "Failed to allocate LD list buffer\n"); return -ENOMEM; } instance->ld_targetid_list_buf = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_LD_TARGETID_LIST), &instance->ld_targetid_list_buf_h, GFP_KERNEL); if (!instance->ld_targetid_list_buf) { dev_err(&pdev->dev, "Failed to allocate LD targetid list buffer\n"); return -ENOMEM; } if (!reset_devices) { instance->system_info_buf = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_DRV_SYSTEM_INFO), &instance->system_info_h, GFP_KERNEL); instance->pd_info = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_PD_INFO), &instance->pd_info_h, GFP_KERNEL); instance->tgt_prop = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_TARGET_PROPERTIES), &instance->tgt_prop_h, GFP_KERNEL); instance->crash_dump_buf = dma_alloc_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE, &instance->crash_dump_h, GFP_KERNEL); if (!instance->system_info_buf) dev_err(&instance->pdev->dev, "Failed to allocate system info buffer\n"); if (!instance->pd_info) dev_err(&instance->pdev->dev, "Failed to allocate pd_info buffer\n"); if (!instance->tgt_prop) dev_err(&instance->pdev->dev, "Failed to allocate tgt_prop buffer\n"); if (!instance->crash_dump_buf) dev_err(&instance->pdev->dev, "Failed to allocate crash dump buffer\n"); } return 0; } /* * megasas_free_ctrl_dma_buffers - Free consistent DMA buffers allocated * during driver load time * * @instance- Adapter soft instance * */ static inline void megasas_free_ctrl_dma_buffers(struct megasas_instance *instance) { struct pci_dev *pdev = instance->pdev; struct fusion_context *fusion = instance->ctrl_context; if (instance->evt_detail) dma_free_coherent(&pdev->dev, sizeof(struct megasas_evt_detail), instance->evt_detail, instance->evt_detail_h); if (fusion && fusion->ioc_init_request) dma_free_coherent(&pdev->dev, sizeof(struct MPI2_IOC_INIT_REQUEST), fusion->ioc_init_request, fusion->ioc_init_request_phys); if (instance->pd_list_buf) dma_free_coherent(&pdev->dev, MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), instance->pd_list_buf, instance->pd_list_buf_h); if (instance->ld_list_buf) dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_LIST), instance->ld_list_buf, instance->ld_list_buf_h); if (instance->ld_targetid_list_buf) dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_TARGETID_LIST), instance->ld_targetid_list_buf, instance->ld_targetid_list_buf_h); if (instance->ctrl_info_buf) dma_free_coherent(&pdev->dev, sizeof(struct megasas_ctrl_info), instance->ctrl_info_buf, instance->ctrl_info_buf_h); if (instance->system_info_buf) dma_free_coherent(&pdev->dev, sizeof(struct MR_DRV_SYSTEM_INFO), instance->system_info_buf, instance->system_info_h); if (instance->pd_info) dma_free_coherent(&pdev->dev, sizeof(struct MR_PD_INFO), instance->pd_info, instance->pd_info_h); if (instance->tgt_prop) dma_free_coherent(&pdev->dev, sizeof(struct MR_TARGET_PROPERTIES), instance->tgt_prop, instance->tgt_prop_h); if (instance->crash_dump_buf) dma_free_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE, instance->crash_dump_buf, instance->crash_dump_h); if (instance->snapdump_prop) dma_free_coherent(&pdev->dev, sizeof(struct MR_SNAPDUMP_PROPERTIES), instance->snapdump_prop, instance->snapdump_prop_h); if (instance->host_device_list_buf) dma_free_coherent(&pdev->dev, HOST_DEVICE_LIST_SZ, instance->host_device_list_buf, instance->host_device_list_buf_h); } /* * megasas_init_ctrl_params - Initialize controller's instance * parameters before FW init * @instance - Adapter soft instance * @return - void */ static inline void megasas_init_ctrl_params(struct megasas_instance *instance) { instance->fw_crash_state = UNAVAILABLE; megasas_poll_wait_aen = 0; instance->issuepend_done = 1; atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL); /* * Initialize locks and queues */ INIT_LIST_HEAD(&instance->cmd_pool); INIT_LIST_HEAD(&instance->internal_reset_pending_q); atomic_set(&instance->fw_outstanding, 0); init_waitqueue_head(&instance->int_cmd_wait_q); init_waitqueue_head(&instance->abort_cmd_wait_q); spin_lock_init(&instance->crashdump_lock); spin_lock_init(&instance->mfi_pool_lock); spin_lock_init(&instance->hba_lock); spin_lock_init(&instance->stream_lock); spin_lock_init(&instance->completion_lock); mutex_init(&instance->reset_mutex); if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) || (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) instance->flag_ieee = 1; megasas_dbg_lvl = 0; instance->flag = 0; instance->unload = 1; instance->last_time = 0; instance->disableOnlineCtrlReset = 1; instance->UnevenSpanSupport = 0; if (instance->adapter_type != MFI_SERIES) INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq); else INIT_WORK(&instance->work_init, process_fw_state_change_wq); } /** * megasas_probe_one - PCI hotplug entry point * @pdev: PCI device structure * @id: PCI ids of supported hotplugged adapter */ static int megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id) { int rval, pos; struct Scsi_Host *host; struct megasas_instance *instance; u16 control = 0; switch (pdev->device) { case PCI_DEVICE_ID_LSI_AERO_10E1: case PCI_DEVICE_ID_LSI_AERO_10E5: dev_info(&pdev->dev, "Adapter is in configurable secure mode\n"); break; } /* Reset MSI-X in the kdump kernel */ if (reset_devices) { pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX); if (pos) { pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS, &control); if (control & PCI_MSIX_FLAGS_ENABLE) { dev_info(&pdev->dev, "resetting MSI-X\n"); pci_write_config_word(pdev, pos + PCI_MSIX_FLAGS, control & ~PCI_MSIX_FLAGS_ENABLE); } } } /* * PCI prepping: enable device set bus mastering and dma mask */ rval = pci_enable_device_mem(pdev); if (rval) { return rval; } pci_set_master(pdev); host = scsi_host_alloc(&megasas_template, sizeof(struct megasas_instance)); if (!host) { dev_printk(KERN_DEBUG, &pdev->dev, "scsi_host_alloc failed\n"); goto fail_alloc_instance; } instance = (struct megasas_instance *)host->hostdata; memset(instance, 0, sizeof(*instance)); atomic_set(&instance->fw_reset_no_pci_access, 0); /* * Initialize PCI related and misc parameters */ instance->pdev = pdev; instance->host = host; instance->unique_id = pdev->bus->number << 8 | pdev->devfn; instance->init_id = MEGASAS_DEFAULT_INIT_ID; megasas_set_adapter_type(instance); /* * Initialize MFI Firmware */ if (megasas_init_fw(instance)) goto fail_init_mfi; if (instance->requestorId) { if (instance->PlasmaFW111) { instance->vf_affiliation_111 = dma_alloc_coherent(&pdev->dev, sizeof(struct MR_LD_VF_AFFILIATION_111), &instance->vf_affiliation_111_h, GFP_KERNEL); if (!instance->vf_affiliation_111) dev_warn(&pdev->dev, "Can't allocate " "memory for VF affiliation buffer\n"); } else { instance->vf_affiliation = dma_alloc_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION), &instance->vf_affiliation_h, GFP_KERNEL); if (!instance->vf_affiliation) dev_warn(&pdev->dev, "Can't allocate " "memory for VF affiliation buffer\n"); } } /* * Store instance in PCI softstate */ pci_set_drvdata(pdev, instance); /* * Add this controller to megasas_mgmt_info structure so that it * can be exported to management applications */ megasas_mgmt_info.count++; megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance; megasas_mgmt_info.max_index++; /* * Register with SCSI mid-layer */ if (megasas_io_attach(instance)) goto fail_io_attach; instance->unload = 0; /* * Trigger SCSI to scan our drives */ if (!instance->enable_fw_dev_list || (instance->host_device_list_buf->count > 0)) scsi_scan_host(host); /* * Initiate AEN (Asynchronous Event Notification) */ if (megasas_start_aen(instance)) { dev_printk(KERN_DEBUG, &pdev->dev, "start aen failed\n"); goto fail_start_aen; } /* Get current SR-IOV LD/VF affiliation */ if (instance->requestorId) megasas_get_ld_vf_affiliation(instance, 1); return 0; fail_start_aen: fail_io_attach: megasas_mgmt_info.count--; megasas_mgmt_info.max_index--; megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL; instance->instancet->disable_intr(instance); megasas_destroy_irqs(instance); if (instance->adapter_type != MFI_SERIES) megasas_release_fusion(instance); else megasas_release_mfi(instance); if (instance->msix_vectors) pci_free_irq_vectors(instance->pdev); fail_init_mfi: scsi_host_put(host); fail_alloc_instance: pci_disable_device(pdev); return -ENODEV; } /** * megasas_flush_cache - Requests FW to flush all its caches * @instance: Adapter soft state */ static void megasas_flush_cache(struct megasas_instance *instance) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) return; cmd = megasas_get_cmd(instance); if (!cmd) return; dcmd = &cmd->frame->dcmd; memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 0; dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE); dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = 0; dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH); dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE; if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS) != DCMD_SUCCESS) { dev_err(&instance->pdev->dev, "return from %s %d\n", __func__, __LINE__); return; } megasas_return_cmd(instance, cmd); } /** * megasas_shutdown_controller - Instructs FW to shutdown the controller * @instance: Adapter soft state * @opcode: Shutdown/Hibernate */ static void megasas_shutdown_controller(struct megasas_instance *instance, u32 opcode) { struct megasas_cmd *cmd; struct megasas_dcmd_frame *dcmd; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) return; cmd = megasas_get_cmd(instance); if (!cmd) return; if (instance->aen_cmd) megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd, MFI_IO_TIMEOUT_SECS); if (instance->map_update_cmd) megasas_issue_blocked_abort_cmd(instance, instance->map_update_cmd, MFI_IO_TIMEOUT_SECS); if (instance->jbod_seq_cmd) megasas_issue_blocked_abort_cmd(instance, instance->jbod_seq_cmd, MFI_IO_TIMEOUT_SECS); dcmd = &cmd->frame->dcmd; memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE); dcmd->cmd = MFI_CMD_DCMD; dcmd->cmd_status = 0x0; dcmd->sge_count = 0; dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE); dcmd->timeout = 0; dcmd->pad_0 = 0; dcmd->data_xfer_len = 0; dcmd->opcode = cpu_to_le32(opcode); if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS) != DCMD_SUCCESS) { dev_err(&instance->pdev->dev, "return from %s %d\n", __func__, __LINE__); return; } megasas_return_cmd(instance, cmd); } #ifdef CONFIG_PM /** * megasas_suspend - driver suspend entry point * @pdev: PCI device structure * @state: PCI power state to suspend routine */ static int megasas_suspend(struct pci_dev *pdev, pm_message_t state) { struct Scsi_Host *host; struct megasas_instance *instance; instance = pci_get_drvdata(pdev); host = instance->host; instance->unload = 1; /* Shutdown SR-IOV heartbeat timer */ if (instance->requestorId && !instance->skip_heartbeat_timer_del) del_timer_sync(&instance->sriov_heartbeat_timer); /* Stop the FW fault detection watchdog */ if (instance->adapter_type != MFI_SERIES) megasas_fusion_stop_watchdog(instance); megasas_flush_cache(instance); megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN); /* cancel the delayed work if this work still in queue */ if (instance->ev != NULL) { struct megasas_aen_event *ev = instance->ev; cancel_delayed_work_sync(&ev->hotplug_work); instance->ev = NULL; } tasklet_kill(&instance->isr_tasklet); pci_set_drvdata(instance->pdev, instance); instance->instancet->disable_intr(instance); megasas_destroy_irqs(instance); if (instance->msix_vectors) pci_free_irq_vectors(instance->pdev); pci_save_state(pdev); pci_disable_device(pdev); pci_set_power_state(pdev, pci_choose_state(pdev, state)); return 0; } /** * megasas_resume- driver resume entry point * @pdev: PCI device structure */ static int megasas_resume(struct pci_dev *pdev) { int rval; struct Scsi_Host *host; struct megasas_instance *instance; int irq_flags = PCI_IRQ_LEGACY; instance = pci_get_drvdata(pdev); host = instance->host; pci_set_power_state(pdev, PCI_D0); pci_enable_wake(pdev, PCI_D0, 0); pci_restore_state(pdev); /* * PCI prepping: enable device set bus mastering and dma mask */ rval = pci_enable_device_mem(pdev); if (rval) { dev_err(&pdev->dev, "Enable device failed\n"); return rval; } pci_set_master(pdev); /* * We expect the FW state to be READY */ if (megasas_transition_to_ready(instance, 0)) goto fail_ready_state; if (megasas_set_dma_mask(instance)) goto fail_set_dma_mask; /* * Initialize MFI Firmware */ atomic_set(&instance->fw_outstanding, 0); atomic_set(&instance->ldio_outstanding, 0); /* Now re-enable MSI-X */ if (instance->msix_vectors) { irq_flags = PCI_IRQ_MSIX; if (smp_affinity_enable) irq_flags |= PCI_IRQ_AFFINITY; } rval = pci_alloc_irq_vectors(instance->pdev, 1, instance->msix_vectors ? instance->msix_vectors : 1, irq_flags); if (rval < 0) goto fail_reenable_msix; megasas_setup_reply_map(instance); if (instance->adapter_type != MFI_SERIES) { megasas_reset_reply_desc(instance); if (megasas_ioc_init_fusion(instance)) { megasas_free_cmds(instance); megasas_free_cmds_fusion(instance); goto fail_init_mfi; } if (!megasas_get_map_info(instance)) megasas_sync_map_info(instance); } else { *instance->producer = 0; *instance->consumer = 0; if (megasas_issue_init_mfi(instance)) goto fail_init_mfi; } if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS) goto fail_init_mfi; tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet, (unsigned long)instance); if (instance->msix_vectors ? megasas_setup_irqs_msix(instance, 0) : megasas_setup_irqs_ioapic(instance)) goto fail_init_mfi; /* Re-launch SR-IOV heartbeat timer */ if (instance->requestorId) { if (!megasas_sriov_start_heartbeat(instance, 0)) megasas_start_timer(instance); else { instance->skip_heartbeat_timer_del = 1; goto fail_init_mfi; } } instance->instancet->enable_intr(instance); megasas_setup_jbod_map(instance); instance->unload = 0; /* * Initiate AEN (Asynchronous Event Notification) */ if (megasas_start_aen(instance)) dev_err(&instance->pdev->dev, "Start AEN failed\n"); /* Re-launch FW fault watchdog */ if (instance->adapter_type != MFI_SERIES) if (megasas_fusion_start_watchdog(instance) != SUCCESS) goto fail_start_watchdog; return 0; fail_start_watchdog: if (instance->requestorId && !instance->skip_heartbeat_timer_del) del_timer_sync(&instance->sriov_heartbeat_timer); fail_init_mfi: megasas_free_ctrl_dma_buffers(instance); megasas_free_ctrl_mem(instance); scsi_host_put(host); fail_reenable_msix: fail_set_dma_mask: fail_ready_state: pci_disable_device(pdev); return -ENODEV; } #else #define megasas_suspend NULL #define megasas_resume NULL #endif static inline int megasas_wait_for_adapter_operational(struct megasas_instance *instance) { int wait_time = MEGASAS_RESET_WAIT_TIME * 2; int i; u8 adp_state; for (i = 0; i < wait_time; i++) { adp_state = atomic_read(&instance->adprecovery); if ((adp_state == MEGASAS_HBA_OPERATIONAL) || (adp_state == MEGASAS_HW_CRITICAL_ERROR)) break; if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) dev_notice(&instance->pdev->dev, "waiting for controller reset to finish\n"); msleep(1000); } if (adp_state != MEGASAS_HBA_OPERATIONAL) { dev_info(&instance->pdev->dev, "%s HBA failed to become operational, adp_state %d\n", __func__, adp_state); return 1; } return 0; } /** * megasas_detach_one - PCI hot"un"plug entry point * @pdev: PCI device structure */ static void megasas_detach_one(struct pci_dev *pdev) { int i; struct Scsi_Host *host; struct megasas_instance *instance; struct fusion_context *fusion; u32 pd_seq_map_sz; instance = pci_get_drvdata(pdev); host = instance->host; fusion = instance->ctrl_context; /* Shutdown SR-IOV heartbeat timer */ if (instance->requestorId && !instance->skip_heartbeat_timer_del) del_timer_sync(&instance->sriov_heartbeat_timer); /* Stop the FW fault detection watchdog */ if (instance->adapter_type != MFI_SERIES) megasas_fusion_stop_watchdog(instance); if (instance->fw_crash_state != UNAVAILABLE) megasas_free_host_crash_buffer(instance); scsi_remove_host(instance->host); instance->unload = 1; if (megasas_wait_for_adapter_operational(instance)) goto skip_firing_dcmds; megasas_flush_cache(instance); megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN); skip_firing_dcmds: /* cancel the delayed work if this work still in queue*/ if (instance->ev != NULL) { struct megasas_aen_event *ev = instance->ev; cancel_delayed_work_sync(&ev->hotplug_work); instance->ev = NULL; } /* cancel all wait events */ wake_up_all(&instance->int_cmd_wait_q); tasklet_kill(&instance->isr_tasklet); /* * Take the instance off the instance array. Note that we will not * decrement the max_index. We let this array be sparse array */ for (i = 0; i < megasas_mgmt_info.max_index; i++) { if (megasas_mgmt_info.instance[i] == instance) { megasas_mgmt_info.count--; megasas_mgmt_info.instance[i] = NULL; break; } } instance->instancet->disable_intr(instance); megasas_destroy_irqs(instance); if (instance->msix_vectors) pci_free_irq_vectors(instance->pdev); if (instance->adapter_type >= VENTURA_SERIES) { for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) kfree(fusion->stream_detect_by_ld[i]); kfree(fusion->stream_detect_by_ld); fusion->stream_detect_by_ld = NULL; } if (instance->adapter_type != MFI_SERIES) { megasas_release_fusion(instance); pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) + (sizeof(struct MR_PD_CFG_SEQ) * (MAX_PHYSICAL_DEVICES - 1)); for (i = 0; i < 2 ; i++) { if (fusion->ld_map[i]) dma_free_coherent(&instance->pdev->dev, fusion->max_map_sz, fusion->ld_map[i], fusion->ld_map_phys[i]); if (fusion->ld_drv_map[i]) { if (is_vmalloc_addr(fusion->ld_drv_map[i])) vfree(fusion->ld_drv_map[i]); else free_pages((ulong)fusion->ld_drv_map[i], fusion->drv_map_pages); } if (fusion->pd_seq_sync[i]) dma_free_coherent(&instance->pdev->dev, pd_seq_map_sz, fusion->pd_seq_sync[i], fusion->pd_seq_phys[i]); } } else { megasas_release_mfi(instance); } if (instance->vf_affiliation) dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION), instance->vf_affiliation, instance->vf_affiliation_h); if (instance->vf_affiliation_111) dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_VF_AFFILIATION_111), instance->vf_affiliation_111, instance->vf_affiliation_111_h); if (instance->hb_host_mem) dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM), instance->hb_host_mem, instance->hb_host_mem_h); megasas_free_ctrl_dma_buffers(instance); megasas_free_ctrl_mem(instance); scsi_host_put(host); pci_disable_device(pdev); } /** * megasas_shutdown - Shutdown entry point * @device: Generic device structure */ static void megasas_shutdown(struct pci_dev *pdev) { struct megasas_instance *instance = pci_get_drvdata(pdev); instance->unload = 1; if (megasas_wait_for_adapter_operational(instance)) goto skip_firing_dcmds; megasas_flush_cache(instance); megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN); skip_firing_dcmds: instance->instancet->disable_intr(instance); megasas_destroy_irqs(instance); if (instance->msix_vectors) pci_free_irq_vectors(instance->pdev); } /** * megasas_mgmt_open - char node "open" entry point */ static int megasas_mgmt_open(struct inode *inode, struct file *filep) { /* * Allow only those users with admin rights */ if (!capable(CAP_SYS_ADMIN)) return -EACCES; return 0; } /** * megasas_mgmt_fasync - Async notifier registration from applications * * This function adds the calling process to a driver global queue. When an * event occurs, SIGIO will be sent to all processes in this queue. */ static int megasas_mgmt_fasync(int fd, struct file *filep, int mode) { int rc; mutex_lock(&megasas_async_queue_mutex); rc = fasync_helper(fd, filep, mode, &megasas_async_queue); mutex_unlock(&megasas_async_queue_mutex); if (rc >= 0) { /* For sanity check when we get ioctl */ filep->private_data = filep; return 0; } printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc); return rc; } /** * megasas_mgmt_poll - char node "poll" entry point * */ static __poll_t megasas_mgmt_poll(struct file *file, poll_table *wait) { __poll_t mask; unsigned long flags; poll_wait(file, &megasas_poll_wait, wait); spin_lock_irqsave(&poll_aen_lock, flags); if (megasas_poll_wait_aen) mask = (EPOLLIN | EPOLLRDNORM); else mask = 0; megasas_poll_wait_aen = 0; spin_unlock_irqrestore(&poll_aen_lock, flags); return mask; } /* * megasas_set_crash_dump_params_ioctl: * Send CRASH_DUMP_MODE DCMD to all controllers * @cmd: MFI command frame */ static int megasas_set_crash_dump_params_ioctl(struct megasas_cmd *cmd) { struct megasas_instance *local_instance; int i, error = 0; int crash_support; crash_support = cmd->frame->dcmd.mbox.w[0]; for (i = 0; i < megasas_mgmt_info.max_index; i++) { local_instance = megasas_mgmt_info.instance[i]; if (local_instance && local_instance->crash_dump_drv_support) { if ((atomic_read(&local_instance->adprecovery) == MEGASAS_HBA_OPERATIONAL) && !megasas_set_crash_dump_params(local_instance, crash_support)) { local_instance->crash_dump_app_support = crash_support; dev_info(&local_instance->pdev->dev, "Application firmware crash " "dump mode set success\n"); error = 0; } else { dev_info(&local_instance->pdev->dev, "Application firmware crash " "dump mode set failed\n"); error = -1; } } } return error; } /** * megasas_mgmt_fw_ioctl - Issues management ioctls to FW * @instance: Adapter soft state * @argp: User's ioctl packet */ static int megasas_mgmt_fw_ioctl(struct megasas_instance *instance, struct megasas_iocpacket __user * user_ioc, struct megasas_iocpacket *ioc) { struct megasas_sge64 *kern_sge64 = NULL; struct megasas_sge32 *kern_sge32 = NULL; struct megasas_cmd *cmd; void *kbuff_arr[MAX_IOCTL_SGE]; dma_addr_t buf_handle = 0; int error = 0, i; void *sense = NULL; dma_addr_t sense_handle; unsigned long *sense_ptr; u32 opcode = 0; memset(kbuff_arr, 0, sizeof(kbuff_arr)); if (ioc->sge_count > MAX_IOCTL_SGE) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "SGE count [%d] > max limit [%d]\n", ioc->sge_count, MAX_IOCTL_SGE); return -EINVAL; } if ((ioc->frame.hdr.cmd >= MFI_CMD_OP_COUNT) || ((ioc->frame.hdr.cmd == MFI_CMD_NVME) && !instance->support_nvme_passthru)) { dev_err(&instance->pdev->dev, "Received invalid ioctl command 0x%x\n", ioc->frame.hdr.cmd); return -ENOTSUPP; } cmd = megasas_get_cmd(instance); if (!cmd) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a cmd packet\n"); return -ENOMEM; } /* * User's IOCTL packet has 2 frames (maximum). Copy those two * frames into our cmd's frames. cmd->frame's context will get * overwritten when we copy from user's frames. So set that value * alone separately */ memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE); cmd->frame->hdr.context = cpu_to_le32(cmd->index); cmd->frame->hdr.pad_0 = 0; cmd->frame->hdr.flags &= (~MFI_FRAME_IEEE); if (instance->consistent_mask_64bit) cmd->frame->hdr.flags |= cpu_to_le16((MFI_FRAME_SGL64 | MFI_FRAME_SENSE64)); else cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_SGL64 | MFI_FRAME_SENSE64)); if (cmd->frame->hdr.cmd == MFI_CMD_DCMD) opcode = le32_to_cpu(cmd->frame->dcmd.opcode); if (opcode == MR_DCMD_CTRL_SHUTDOWN) { if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS) { megasas_return_cmd(instance, cmd); return -1; } } if (opcode == MR_DRIVER_SET_APP_CRASHDUMP_MODE) { error = megasas_set_crash_dump_params_ioctl(cmd); megasas_return_cmd(instance, cmd); return error; } /* * The management interface between applications and the fw uses * MFI frames. E.g, RAID configuration changes, LD property changes * etc are accomplishes through different kinds of MFI frames. The * driver needs to care only about substituting user buffers with * kernel buffers in SGLs. The location of SGL is embedded in the * struct iocpacket itself. */ if (instance->consistent_mask_64bit) kern_sge64 = (struct megasas_sge64 *) ((unsigned long)cmd->frame + ioc->sgl_off); else kern_sge32 = (struct megasas_sge32 *) ((unsigned long)cmd->frame + ioc->sgl_off); /* * For each user buffer, create a mirror buffer and copy in */ for (i = 0; i < ioc->sge_count; i++) { if (!ioc->sgl[i].iov_len) continue; kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev, ioc->sgl[i].iov_len, &buf_handle, GFP_KERNEL); if (!kbuff_arr[i]) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc " "kernel SGL buffer for IOCTL\n"); error = -ENOMEM; goto out; } /* * We don't change the dma_coherent_mask, so * dma_alloc_coherent only returns 32bit addresses */ if (instance->consistent_mask_64bit) { kern_sge64[i].phys_addr = cpu_to_le64(buf_handle); kern_sge64[i].length = cpu_to_le32(ioc->sgl[i].iov_len); } else { kern_sge32[i].phys_addr = cpu_to_le32(buf_handle); kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len); } /* * We created a kernel buffer corresponding to the * user buffer. Now copy in from the user buffer */ if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base, (u32) (ioc->sgl[i].iov_len))) { error = -EFAULT; goto out; } } if (ioc->sense_len) { sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len, &sense_handle, GFP_KERNEL); if (!sense) { error = -ENOMEM; goto out; } sense_ptr = (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off); if (instance->consistent_mask_64bit) *sense_ptr = cpu_to_le64(sense_handle); else *sense_ptr = cpu_to_le32(sense_handle); } /* * Set the sync_cmd flag so that the ISR knows not to complete this * cmd to the SCSI mid-layer */ cmd->sync_cmd = 1; if (megasas_issue_blocked_cmd(instance, cmd, 0) == DCMD_NOT_FIRED) { cmd->sync_cmd = 0; dev_err(&instance->pdev->dev, "return -EBUSY from %s %d cmd 0x%x opcode 0x%x cmd->cmd_status_drv 0x%x\n", __func__, __LINE__, cmd->frame->hdr.cmd, opcode, cmd->cmd_status_drv); return -EBUSY; } cmd->sync_cmd = 0; if (instance->unload == 1) { dev_info(&instance->pdev->dev, "Driver unload is in progress " "don't submit data to application\n"); goto out; } /* * copy out the kernel buffers to user buffers */ for (i = 0; i < ioc->sge_count; i++) { if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i], ioc->sgl[i].iov_len)) { error = -EFAULT; goto out; } } /* * copy out the sense */ if (ioc->sense_len) { /* * sense_ptr points to the location that has the user * sense buffer address */ sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw + ioc->sense_off); if (copy_to_user((void __user *)((unsigned long) get_unaligned((unsigned long *)sense_ptr)), sense, ioc->sense_len)) { dev_err(&instance->pdev->dev, "Failed to copy out to user " "sense data\n"); error = -EFAULT; goto out; } } /* * copy the status codes returned by the fw */ if (copy_to_user(&user_ioc->frame.hdr.cmd_status, &cmd->frame->hdr.cmd_status, sizeof(u8))) { dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error copying out cmd_status\n"); error = -EFAULT; } out: if (sense) { dma_free_coherent(&instance->pdev->dev, ioc->sense_len, sense, sense_handle); } for (i = 0; i < ioc->sge_count; i++) { if (kbuff_arr[i]) { if (instance->consistent_mask_64bit) dma_free_coherent(&instance->pdev->dev, le32_to_cpu(kern_sge64[i].length), kbuff_arr[i], le64_to_cpu(kern_sge64[i].phys_addr)); else dma_free_coherent(&instance->pdev->dev, le32_to_cpu(kern_sge32[i].length), kbuff_arr[i], le32_to_cpu(kern_sge32[i].phys_addr)); kbuff_arr[i] = NULL; } } megasas_return_cmd(instance, cmd); return error; } static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg) { struct megasas_iocpacket __user *user_ioc = (struct megasas_iocpacket __user *)arg; struct megasas_iocpacket *ioc; struct megasas_instance *instance; int error; ioc = memdup_user(user_ioc, sizeof(*ioc)); if (IS_ERR(ioc)) return PTR_ERR(ioc); instance = megasas_lookup_instance(ioc->host_no); if (!instance) { error = -ENODEV; goto out_kfree_ioc; } /* Block ioctls in VF mode */ if (instance->requestorId && !allow_vf_ioctls) { error = -ENODEV; goto out_kfree_ioc; } if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { dev_err(&instance->pdev->dev, "Controller in crit error\n"); error = -ENODEV; goto out_kfree_ioc; } if (instance->unload == 1) { error = -ENODEV; goto out_kfree_ioc; } if (down_interruptible(&instance->ioctl_sem)) { error = -ERESTARTSYS; goto out_kfree_ioc; } if (megasas_wait_for_adapter_operational(instance)) { error = -ENODEV; goto out_up; } error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc); out_up: up(&instance->ioctl_sem); out_kfree_ioc: kfree(ioc); return error; } static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg) { struct megasas_instance *instance; struct megasas_aen aen; int error; if (file->private_data != file) { printk(KERN_DEBUG "megasas: fasync_helper was not " "called first\n"); return -EINVAL; } if (copy_from_user(&aen, (void __user *)arg, sizeof(aen))) return -EFAULT; instance = megasas_lookup_instance(aen.host_no); if (!instance) return -ENODEV; if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) { return -ENODEV; } if (instance->unload == 1) { return -ENODEV; } if (megasas_wait_for_adapter_operational(instance)) return -ENODEV; mutex_lock(&instance->reset_mutex); error = megasas_register_aen(instance, aen.seq_num, aen.class_locale_word); mutex_unlock(&instance->reset_mutex); return error; } /** * megasas_mgmt_ioctl - char node ioctl entry point */ static long megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case MEGASAS_IOC_FIRMWARE: return megasas_mgmt_ioctl_fw(file, arg); case MEGASAS_IOC_GET_AEN: return megasas_mgmt_ioctl_aen(file, arg); } return -ENOTTY; } #ifdef CONFIG_COMPAT static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg) { struct compat_megasas_iocpacket __user *cioc = (struct compat_megasas_iocpacket __user *)arg; struct megasas_iocpacket __user *ioc = compat_alloc_user_space(sizeof(struct megasas_iocpacket)); int i; int error = 0; compat_uptr_t ptr; u32 local_sense_off; u32 local_sense_len; u32 user_sense_off; if (clear_user(ioc, sizeof(*ioc))) return -EFAULT; if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) || copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) || copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) || copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) || copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) || copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32))) return -EFAULT; /* * The sense_ptr is used in megasas_mgmt_fw_ioctl only when * sense_len is not null, so prepare the 64bit value under * the same condition. */ if (get_user(local_sense_off, &ioc->sense_off) || get_user(local_sense_len, &ioc->sense_len) || get_user(user_sense_off, &cioc->sense_off)) return -EFAULT; if (local_sense_off != user_sense_off) return -EINVAL; if (local_sense_len) { void __user **sense_ioc_ptr = (void __user **)((u8 *)((unsigned long)&ioc->frame.raw) + local_sense_off); compat_uptr_t *sense_cioc_ptr = (compat_uptr_t *)(((unsigned long)&cioc->frame.raw) + user_sense_off); if (get_user(ptr, sense_cioc_ptr) || put_user(compat_ptr(ptr), sense_ioc_ptr)) return -EFAULT; } for (i = 0; i < MAX_IOCTL_SGE; i++) { if (get_user(ptr, &cioc->sgl[i].iov_base) || put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) || copy_in_user(&ioc->sgl[i].iov_len, &cioc->sgl[i].iov_len, sizeof(compat_size_t))) return -EFAULT; } error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc); if (copy_in_user(&cioc->frame.hdr.cmd_status, &ioc->frame.hdr.cmd_status, sizeof(u8))) { printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n"); return -EFAULT; } return error; } static long megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case MEGASAS_IOC_FIRMWARE32: return megasas_mgmt_compat_ioctl_fw(file, arg); case MEGASAS_IOC_GET_AEN: return megasas_mgmt_ioctl_aen(file, arg); } return -ENOTTY; } #endif /* * File operations structure for management interface */ static const struct file_operations megasas_mgmt_fops = { .owner = THIS_MODULE, .open = megasas_mgmt_open, .fasync = megasas_mgmt_fasync, .unlocked_ioctl = megasas_mgmt_ioctl, .poll = megasas_mgmt_poll, #ifdef CONFIG_COMPAT .compat_ioctl = megasas_mgmt_compat_ioctl, #endif .llseek = noop_llseek, }; /* * PCI hotplug support registration structure */ static struct pci_driver megasas_pci_driver = { .name = "megaraid_sas", .id_table = megasas_pci_table, .probe = megasas_probe_one, .remove = megasas_detach_one, .suspend = megasas_suspend, .resume = megasas_resume, .shutdown = megasas_shutdown, }; /* * Sysfs driver attributes */ static ssize_t version_show(struct device_driver *dd, char *buf) { return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n", MEGASAS_VERSION); } static DRIVER_ATTR_RO(version); static ssize_t release_date_show(struct device_driver *dd, char *buf) { return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n", MEGASAS_RELDATE); } static DRIVER_ATTR_RO(release_date); static ssize_t support_poll_for_event_show(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", support_poll_for_event); } static DRIVER_ATTR_RO(support_poll_for_event); static ssize_t support_device_change_show(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", support_device_change); } static DRIVER_ATTR_RO(support_device_change); static ssize_t dbg_lvl_show(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", megasas_dbg_lvl); } static ssize_t dbg_lvl_store(struct device_driver *dd, const char *buf, size_t count) { int retval = count; if (sscanf(buf, "%u", &megasas_dbg_lvl) < 1) { printk(KERN_ERR "megasas: could not set dbg_lvl\n"); retval = -EINVAL; } return retval; } static DRIVER_ATTR_RW(dbg_lvl); static ssize_t support_nvme_encapsulation_show(struct device_driver *dd, char *buf) { return sprintf(buf, "%u\n", support_nvme_encapsulation); } static DRIVER_ATTR_RO(support_nvme_encapsulation); static inline void megasas_remove_scsi_device(struct scsi_device *sdev) { sdev_printk(KERN_INFO, sdev, "SCSI device is removed\n"); scsi_remove_device(sdev); scsi_device_put(sdev); } /** * megasas_update_device_list - Update the PD and LD device list from FW * after an AEN event notification * @instance: Adapter soft state * @event_type: Indicates type of event (PD or LD event) * * @return: Success or failure * * Issue DCMDs to Firmware to update the internal device list in driver. * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list. */ static int megasas_update_device_list(struct megasas_instance *instance, int event_type) { int dcmd_ret = DCMD_SUCCESS; if (instance->enable_fw_dev_list) { dcmd_ret = megasas_host_device_list_query(instance, false); if (dcmd_ret != DCMD_SUCCESS) goto out; } else { if (event_type & SCAN_PD_CHANNEL) { dcmd_ret = megasas_get_pd_list(instance); if (dcmd_ret != DCMD_SUCCESS) goto out; } if (event_type & SCAN_VD_CHANNEL) { if (!instance->requestorId || (instance->requestorId && megasas_get_ld_vf_affiliation(instance, 0))) { dcmd_ret = megasas_ld_list_query(instance, MR_LD_QUERY_TYPE_EXPOSED_TO_HOST); if (dcmd_ret != DCMD_SUCCESS) goto out; } } } out: return dcmd_ret; } /** * megasas_add_remove_devices - Add/remove devices to SCSI mid-layer * after an AEN event notification * @instance: Adapter soft state * @scan_type: Indicates type of devices (PD/LD) to add * @return void */ static void megasas_add_remove_devices(struct megasas_instance *instance, int scan_type) { int i, j; u16 pd_index = 0; u16 ld_index = 0; u16 channel = 0, id = 0; struct Scsi_Host *host; struct scsi_device *sdev1; struct MR_HOST_DEVICE_LIST *targetid_list = NULL; struct MR_HOST_DEVICE_LIST_ENTRY *targetid_entry = NULL; host = instance->host; if (instance->enable_fw_dev_list) { targetid_list = instance->host_device_list_buf; for (i = 0; i < targetid_list->count; i++) { targetid_entry = &targetid_list->host_device_list[i]; if (targetid_entry->flags.u.bits.is_sys_pd) { channel = le16_to_cpu(targetid_entry->target_id) / MEGASAS_MAX_DEV_PER_CHANNEL; id = le16_to_cpu(targetid_entry->target_id) % MEGASAS_MAX_DEV_PER_CHANNEL; } else { channel = MEGASAS_MAX_PD_CHANNELS + (le16_to_cpu(targetid_entry->target_id) / MEGASAS_MAX_DEV_PER_CHANNEL); id = le16_to_cpu(targetid_entry->target_id) % MEGASAS_MAX_DEV_PER_CHANNEL; } sdev1 = scsi_device_lookup(host, channel, id, 0); if (!sdev1) { scsi_add_device(host, channel, id, 0); } else { scsi_device_put(sdev1); } } } if (scan_type & SCAN_PD_CHANNEL) { for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { pd_index = i * MEGASAS_MAX_DEV_PER_CHANNEL + j; sdev1 = scsi_device_lookup(host, i, j, 0); if (instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) { if (!sdev1) scsi_add_device(host, i, j, 0); else scsi_device_put(sdev1); } else { if (sdev1) megasas_remove_scsi_device(sdev1); } } } } if (scan_type & SCAN_VD_CHANNEL) { for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) { for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) { ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j; sdev1 = scsi_device_lookup(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0); if (instance->ld_ids[ld_index] != 0xff) { if (!sdev1) scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0); else scsi_device_put(sdev1); } else { if (sdev1) megasas_remove_scsi_device(sdev1); } } } } } static void megasas_aen_polling(struct work_struct *work) { struct megasas_aen_event *ev = container_of(work, struct megasas_aen_event, hotplug_work.work); struct megasas_instance *instance = ev->instance; union megasas_evt_class_locale class_locale; int event_type = 0; u32 seq_num, wait_time = MEGASAS_RESET_WAIT_TIME; int error; u8 dcmd_ret = DCMD_SUCCESS; if (!instance) { printk(KERN_ERR "invalid instance!\n"); kfree(ev); return; } /* Adjust event workqueue thread wait time for VF mode */ if (instance->requestorId) wait_time = MEGASAS_ROUTINE_WAIT_TIME_VF; /* Don't run the event workqueue thread if OCR is running */ mutex_lock(&instance->reset_mutex); instance->ev = NULL; if (instance->evt_detail) { megasas_decode_evt(instance); switch (le32_to_cpu(instance->evt_detail->code)) { case MR_EVT_PD_INSERTED: case MR_EVT_PD_REMOVED: event_type = SCAN_PD_CHANNEL; break; case MR_EVT_LD_OFFLINE: case MR_EVT_CFG_CLEARED: case MR_EVT_LD_DELETED: case MR_EVT_LD_CREATED: event_type = SCAN_VD_CHANNEL; break; case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED: case MR_EVT_FOREIGN_CFG_IMPORTED: case MR_EVT_LD_STATE_CHANGE: event_type = SCAN_PD_CHANNEL | SCAN_VD_CHANNEL; dev_info(&instance->pdev->dev, "scanning for scsi%d...\n", instance->host->host_no); break; case MR_EVT_CTRL_PROP_CHANGED: dcmd_ret = megasas_get_ctrl_info(instance); if (dcmd_ret == DCMD_SUCCESS && instance->snapdump_wait_time) { megasas_get_snapdump_properties(instance); dev_info(&instance->pdev->dev, "Snap dump wait time\t: %d\n", instance->snapdump_wait_time); } break; default: event_type = 0; break; } } else { dev_err(&instance->pdev->dev, "invalid evt_detail!\n"); mutex_unlock(&instance->reset_mutex); kfree(ev); return; } if (event_type) dcmd_ret = megasas_update_device_list(instance, event_type); mutex_unlock(&instance->reset_mutex); if (event_type && dcmd_ret == DCMD_SUCCESS) megasas_add_remove_devices(instance, event_type); if (dcmd_ret == DCMD_SUCCESS) seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1; else seq_num = instance->last_seq_num; /* Register AEN with FW for latest sequence number plus 1 */ class_locale.members.reserved = 0; class_locale.members.locale = MR_EVT_LOCALE_ALL; class_locale.members.class = MR_EVT_CLASS_DEBUG; if (instance->aen_cmd != NULL) { kfree(ev); return; } mutex_lock(&instance->reset_mutex); error = megasas_register_aen(instance, seq_num, class_locale.word); if (error) dev_err(&instance->pdev->dev, "register aen failed error %x\n", error); mutex_unlock(&instance->reset_mutex); kfree(ev); } /** * megasas_init - Driver load entry point */ static int __init megasas_init(void) { int rval; /* * Booted in kdump kernel, minimize memory footprints by * disabling few features */ if (reset_devices) { msix_vectors = 1; rdpq_enable = 0; dual_qdepth_disable = 1; } /* * Announce driver version and other information */ pr_info("megasas: %s\n", MEGASAS_VERSION); spin_lock_init(&poll_aen_lock); support_poll_for_event = 2; support_device_change = 1; support_nvme_encapsulation = true; memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info)); /* * Register character device node */ rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops); if (rval < 0) { printk(KERN_DEBUG "megasas: failed to open device node\n"); return rval; } megasas_mgmt_majorno = rval; /* * Register ourselves as PCI hotplug module */ rval = pci_register_driver(&megasas_pci_driver); if (rval) { printk(KERN_DEBUG "megasas: PCI hotplug registration failed \n"); goto err_pcidrv; } rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_version); if (rval) goto err_dcf_attr_ver; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_release_date); if (rval) goto err_dcf_rel_date; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_support_poll_for_event); if (rval) goto err_dcf_support_poll_for_event; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_dbg_lvl); if (rval) goto err_dcf_dbg_lvl; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_support_device_change); if (rval) goto err_dcf_support_device_change; rval = driver_create_file(&megasas_pci_driver.driver, &driver_attr_support_nvme_encapsulation); if (rval) goto err_dcf_support_nvme_encapsulation; return rval; err_dcf_support_nvme_encapsulation: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_device_change); err_dcf_support_device_change: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_dbg_lvl); err_dcf_dbg_lvl: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_poll_for_event); err_dcf_support_poll_for_event: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_release_date); err_dcf_rel_date: driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version); err_dcf_attr_ver: pci_unregister_driver(&megasas_pci_driver); err_pcidrv: unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl"); return rval; } /** * megasas_exit - Driver unload entry point */ static void __exit megasas_exit(void) { driver_remove_file(&megasas_pci_driver.driver, &driver_attr_dbg_lvl); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_poll_for_event); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_device_change); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_release_date); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version); driver_remove_file(&megasas_pci_driver.driver, &driver_attr_support_nvme_encapsulation); pci_unregister_driver(&megasas_pci_driver); unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl"); } module_init(megasas_init); module_exit(megasas_exit);
./CrossVul/dataset_final_sorted/CWE-476/c/good_831_0
crossvul-cpp_data_good_5485_2
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT X X TTTTT % % T X X T % % T X T % % T X X T % % T X X T % % % % % % Render Text Onto A Canvas Image. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 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 "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteTXTImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T X T % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTXT() returns MagickTrue if the image format type, identified by the magick % string, is TXT. % % The format of the IsTXT method is: % % MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length) { #define MagickID "# ImageMagick pixel enumeration:" char colorspace[MagickPathExtent]; ssize_t count; unsigned long columns, depth, rows; if (length < 40) return(MagickFalse); if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0) return(MagickFalse); count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns, &rows,&depth,colorspace); if (count != 4) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T E X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTEXTImage() reads a text file and returns it as an image. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadTEXTImage method is: % % Image *ReadTEXTImage(const ImageInfo *image_info,Image *image, % char *text,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o text: the text storage buffer. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadTEXTImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent], geometry[MagickPathExtent], *p, text[MagickPathExtent]; DrawInfo *draw_info; Image *image, *texture; MagickBooleanType status; PointInfo delta; RectangleInfo page; ssize_t offset; TypeMetric metrics; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); /* Set the page geometry. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } page.width=612; page.height=792; page.x=43; page.y=43; if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); /* Initialize Image structure. */ image->columns=(size_t) floor((((double) page.width*image->resolution.x)/ delta.x)+0.5); image->rows=(size_t) floor((((double) page.height*image->resolution.y)/ delta.y)+0.5); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); image->page.x=0; image->page.y=0; texture=(Image *) NULL; if (image_info->texture != (char *) NULL) { ImageInfo *read_info; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->filename,image_info->texture, MagickPathExtent); texture=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); } /* Annotate the text image. */ (void) SetImageBackgroundColor(image,exception); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,image_info->filename); (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double) image->columns,(double) image->rows,(double) page.x,(double) page.y); (void) CloneString(&draw_info->geometry,geometry); status=GetTypeMetrics(image,draw_info,&metrics,exception); if (status == MagickFalse) ThrowReaderException(TypeError,"UnableToGetTypeMetrics"); page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double) image->columns,(double) image->rows,(double) page.x,(double) page.y); (void) CloneString(&draw_info->geometry,geometry); (void) CopyMagickString(filename,image_info->filename,MagickPathExtent); if (*draw_info->text != '\0') *draw_info->text='\0'; p=text; for (offset=2*page.y; p != (char *) NULL; ) { /* Annotate image with text. */ (void) ConcatenateString(&draw_info->text,text); (void) ConcatenateString(&draw_info->text,"\n"); offset+=(ssize_t) (metrics.ascent-metrics.descent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset, image->rows); if (status == MagickFalse) break; } p=ReadBlobString(image,text); if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) continue; if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture,exception); (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); } (void) AnnotateImage(image,draw_info,exception); if (p == (char *) NULL) break; /* Page is full-- allocate next image structure. */ *draw_info->text='\0'; offset=2*page.y; AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image->next->columns=image->columns; image->next->rows=image->rows; image=SyncNextImageInList(image); (void) CopyMagickString(image->filename,filename,MagickPathExtent); (void) SetImageBackgroundColor(image,exception); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture,exception); (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); } (void) AnnotateImage(image,draw_info,exception); if (texture != (Image *) NULL) texture=DestroyImage(texture); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTXTImage() reads a text file and returns it as an image. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadTXTImage method is: % % Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MagickPathExtent], text[MagickPathExtent]; Image *image; long x_offset, y_offset; PixelInfo pixel; MagickBooleanType status; QuantumAny range; register ssize_t i, x; register Quantum *q; ssize_t count, type, y; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->alpha_trait=UndefinedPixelTrait; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->alpha_trait=BlendPixelTrait; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) SetImageBackgroundColor(image,exception); (void) SetImageColorspace(image,(ColorspaceType) type,exception); GetPixelInfo(image,&pixel); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double alpha, black, blue, green, red; red=0.0; green=0.0; blue=0.0; black=0.0; alpha=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&alpha); green=red; blue=red; break; } count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset, &y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&black,&alpha); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&black); break; } default: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&alpha); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; black*=0.01*range; alpha*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5), range); pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5), range); pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5), range); pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5), range); pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5), range); q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1, exception); if (q == (Quantum *) NULL) continue; SetPixelViaPixelInfo(image,&pixel,q); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is: % % size_t RegisterTXTImage(void) % */ ModuleExport size_t RegisterTXTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("TXT","SPARSE-COLOR","Sparse Color"); entry->encoder=(EncodeImageHandler *) WriteTXTImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TXT","TEXT","Text"); entry->decoder=(DecodeImageHandler *) ReadTEXTImage; entry->format_type=ImplicitFormatType; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TXT","TXT","Text"); entry->decoder=(DecodeImageHandler *) ReadTXTImage; entry->encoder=(EncodeImageHandler *) WriteTXTImage; entry->magick=(IsImageFormatHandler *) IsTXT; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTXTImage() removes format registrations made by the % TXT module from the list of supported format. % % The format of the UnregisterTXTImage method is: % % UnregisterTXTImage(void) % */ ModuleExport void UnregisterTXTImage(void) { (void) UnregisterMagickInfo("SPARSE-COLOR"); (void) UnregisterMagickInfo("TEXT"); (void) UnregisterMagickInfo("TXT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e T X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTXTImage writes the pixel values as text numbers. % % The format of the WriteTXTImage method is: % % MagickBooleanType WriteTXTImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], colorspace[MagickPathExtent], tuple[MagickPathExtent]; MagickBooleanType status; MagickOffsetType scene; PixelInfo pixel; register const Quantum *p; register ssize_t x; ssize_t y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { ComplianceType compliance; const char *value; (void) CopyMagickString(colorspace,CommandOptionToMnemonic( MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent); LocaleLower(colorspace); image->depth=GetImageQuantumDepth(image,MagickTrue); if (image->alpha_trait != UndefinedPixelTrait) (void) ConcatenateMagickString(colorspace,"a",MagickPathExtent); compliance=NoCompliance; value=GetImageOption(image_info,"txt:compliance"); if (value != (char *) NULL) compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions, MagickFalse,value); if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0) { size_t depth; depth=compliance == SVGCompliance ? image->depth : MAGICKCORE_QUANTUM_DEPTH; (void) FormatLocaleString(buffer,MagickPathExtent, "# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double) image->columns,(double) image->rows,(double) ((MagickOffsetType) GetQuantumRange(depth)),colorspace); (void) WriteBlobString(image,buffer); } GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,p,&pixel); if (pixel.colorspace == LabColorspace) { pixel.green-=(QuantumRange+1)/2.0; pixel.blue-=(QuantumRange+1)/2.0; } if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0) { /* Sparse-color format. */ if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha) { GetColorTuple(&pixel,MagickFalse,tuple); (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g,%.20g,",(double) x,(double) y); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); } p+=GetPixelChannels(image); continue; } (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ", (double) x,(double) y); (void) WriteBlobString(image,buffer); (void) CopyMagickString(tuple,"(",MagickPathExtent); if (pixel.colorspace == GRAYColorspace) ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple); else { ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance, tuple); (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple); } if (pixel.colorspace == CMYKColorspace) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance, tuple); } if (pixel.alpha_trait != UndefinedPixelTrait) { (void) ConcatenateMagickString(tuple,",",MagickPathExtent); ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance, tuple); } (void) ConcatenateMagickString(tuple,")",MagickPathExtent); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image," "); GetColorTuple(&pixel,MagickTrue,tuple); (void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," "); (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception); (void) WriteBlobString(image,tuple); (void) WriteBlobString(image,"\n"); p+=GetPixelChannels(image); } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_5485_2
crossvul-cpp_data_bad_5108_0
/* packet-u3v.c * Routines for AIA USB3 Vision (TM) Protocol dissection * Copyright 2016, AIA (www.visiononline.org) * * USB3 Vision (TM): USB3 Vision a standard developed under the sponsorship of * the AIA for the benefit of the machine vision industry. * U3V stands for USB3 Vision (TM) Protocol. * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include <epan/proto_data.h> #include <epan/dissectors/packet-usb.h> /* U3V descriptor constants */ #define DESCRIPTOR_TYPE_U3V_INTERFACE 0x24 #define DESCRIPTOR_SUBTYPE_U3V_DEVICE_INFO 0x01 /* Bootstrap registers addresses */ #define U3V_ABRM_GENCP_VERSION 0x00000000 #define U3V_ABRM_MANUFACTURER_NAME 0x00000004 #define U3V_ABRM_MODEL_NAME 0x00000044 #define U3V_ABRM_FAMILY_NAME 0x00000084 #define U3V_ABRM_DEVICE_VERSION 0x000000C4 #define U3V_ABRM_MANUFACTURER_INFO 0x00000104 #define U3V_ABRM_SERIAL_NUMBER 0x00000144 #define U3V_ABRM_USER_DEFINED_NAME 0x00000184 #define U3V_ABRM_DEVICE_CAPABILITY 0x000001C4 #define U3V_ABRM_MAXIMUM_DEVICE_RESPONSE_TIME 0x000001CC #define U3V_ABRM_MANIFEST_TABLE_ADDRESS 0x000001D0 #define U3V_ABRM_SBRM_ADDRESS 0x000001D8 #define U3V_ABRM_DEVICE_CONFIGURATION 0x000001E0 #define U3V_ABRM_HEARTBEAT_TIMEOUT 0x000001E8 #define U3V_ABRM_MESSAGE_CHANNEL_CHANNEL_ID 0x000001EC #define U3V_ABRM_TIMESTAMP 0x000001F0 #define U3V_ABRM_TIMESTAMP_LATCH 0x000001F8 #define U3V_ABRM_TIMESTAMP_INCREMENT 0x000001FC #define U3V_ABRM_ACCESS_PRIVILEGE 0x00000204 #define U3V_ABRM_PROTOCOL_ENDIANESS 0x00000208 #define U3V_ABRM_IMPLEMENTATION_ENDIANESS 0x0000020C #define U3V_SBRM_U3V_VERSION 0x00000000 #define U3V_SBRM_U3VCP_CAPABILITY_REGISTER 0x00000004 #define U3V_SBRM_U3VCP_CONFIGURATION_REGISTER 0x0000000C #define U3V_SBRM_MAXIMUM_COMMAND_TRANSFER_LENGTH 0x00000014 #define U3V_SBRM_MAXIMUM_ACKNOWLEDGE_TRANSFER_LENGTH 0x00000018 #define U3V_SBRM_NUMBER_OF_STREAM_CHANNELS 0x0000001C #define U3V_SBRM_SIRM_ADDRESS 0x00000020 #define U3V_SBRM_SIRM_LENGTH 0x00000028 #define U3V_SBRM_EIRM_ADDRESS 0x0000002C #define U3V_SBRM_EIRM_LENGTH 0x00000034 #define U3V_SBRM_IIDC2_ADDRESS 0x00000038 #define U3V_SBRM_CURRENT_SPEED 0x00000040 #define U3V_SIRM_SI_INFO 0x00000000 #define U3V_SIRM_SI_CONTROL 0x00000004 #define U3V_SIRM_SI_REQUIRED_PAYLOAD_SIZE 0x00000008 #define U3V_SIRM_SI_REQUIRED_LEADER_SIZE 0x00000010 #define U3V_SIRM_SI_REQUIRED_TRAILER_SIZE 0x00000014 #define U3V_SIRM_SI_MAXIMUM_LEADER_SIZE 0x00000018 #define U3V_SIRM_SI_PAYLOAD_TRANSFER_SIZE 0x0000001C #define U3V_SIRM_SI_PAYLOAD_TRANSFER_COUNT 0x00000020 #define U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER1_SIZE 0x00000024 #define U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER2_SIZE 0x00000028 #define U3V_SIRM_SI_MAXIMUM_TRAILER_SIZE 0x0000002C #define U3V_EIRM_EI_CONTROL 0x00000000 #define U3V_EIRM_MAXIMUM_EVENT_TRANSFER_LENGTH 0x00000004 #define U3V_EIRM_EVENT_TEST_CONTROL 0x00000008 /* Command and acknowledge IDs */ #define U3V_READMEM_CMD 0x0800 #define U3V_READMEM_ACK 0x0801 #define U3V_WRITEMEM_CMD 0x0802 #define U3V_WRITEMEM_ACK 0x0803 #define U3V_PENDING_ACK 0x0805 #define U3V_EVENT_CMD 0x0C00 #define U3V_EVENT_ACK 0x0C01 /* Status codes */ #define U3V_STATUS_GENCP_SUCCESS 0x0000 #define U3V_STATUS_GENCP_NOT_IMPLEMENTED 0x8001 #define U3V_STATUS_GENCP_INVALID_PARAMETER 0x8002 #define U3V_STATUS_GENCP_INVALID_ADDRESS 0x8003 #define U3V_STATUS_GENCP_WRITE_PROTECT 0x8004 #define U3V_STATUS_GENCP_BAD_ALIGNMENT 0x8005 #define U3V_STATUS_GENCP_ACCESS_DENIED 0x8006 #define U3V_STATUS_GENCP_BUSY 0x8007 /* 0x8008 - 0x800A have been used in GEV 1.x but are now deprecated. The GenCP specification did NOT recycle these values! */ #define U3V_STATUS_GENCP_MSG_TIMEOUT 0x800B /* 0x800C - 0x800D are used in GEV only. The GenCP specification did NOT recycle these values! */ #define U3V_STATUS_GENCP_INVALID_HEADER 0x800E #define U3V_STATUS_GENCP_WRONG_CONFIG 0x800F #define U3V_STATUS_GENCP_ERROR 0x8FFF #define U3V_STATUS_RESEND_NOT_SUPPORTED 0xA001 #define U3V_STATUS_DSI_ENDPOINT_HALTED 0xA002 #define U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED 0xA003 #define U3V_STATUS_SI_REGISTERS_INCONSISTENT 0xA004 #define U3V_STATUS_DATA_DISCARDED 0xA100 /* Prefix */ #define U3V_CONTROL_PREFIX 0x43563355 #define U3V_EVENT_PREFIX 0x45563355 #define U3V_STREAM_LEADER_PREFIX 0x4C563355 #define U3V_STREAM_TRAILER_PREFIX 0x54563355 /* Event IDs */ #define U3V_EVENT_TESTEVENT 0x4FFF /* * Pixel Format IDs */ #define PFNC_U3V_MONO1P 0x01010037 #define PFNC_U3V_CONFIDENCE1P 0x010100C5 #define PFNC_U3V_MONO2P 0x01020038 #define PFNC_U3V_MONO4P 0x01040039 #define PFNC_U3V_MONO8 0x01080001 #define PFNC_U3V_MONO8S 0x01080002 #define PFNC_U3V_BAYERGR8 0x01080008 #define PFNC_U3V_BAYERRG8 0x01080009 #define PFNC_U3V_BAYERGB8 0x0108000A #define PFNC_U3V_BAYERBG8 0x0108000B #define PFNC_U3V_SCF1WBWG8 0x01080067 #define PFNC_U3V_SCF1WGWB8 0x0108006E #define PFNC_U3V_SCF1WGWR8 0x01080075 #define PFNC_U3V_SCF1WRWG8 0x0108007C #define PFNC_U3V_COORD3D_A8 0x010800AF #define PFNC_U3V_COORD3D_B8 0x010800B0 #define PFNC_U3V_COORD3D_C8 0x010800B1 #define PFNC_U3V_CONFIDENCE1 0x010800C4 #define PFNC_U3V_CONFIDENCE8 0x010800C6 #define PFNC_U3V_R8 0x010800C9 #define PFNC_U3V_G8 0x010800CD #define PFNC_U3V_B8 0x010800D1 #define PFNC_U3V_MONO10P 0x010A0046 #define PFNC_U3V_BAYERBG10P 0x010A0052 #define PFNC_U3V_BAYERGB10P 0x010A0054 #define PFNC_U3V_BAYERGR10P 0x010A0056 #define PFNC_U3V_BAYERRG10P 0x010A0058 #define PFNC_U3V_SCF1WBWG10P 0x010A0069 #define PFNC_U3V_SCF1WGWB10P 0x010A0070 #define PFNC_U3V_SCF1WGWR10P 0x010A0077 #define PFNC_U3V_SCF1WRWG10P 0x010A007E #define PFNC_U3V_R10 0x010A00CA #define PFNC_U3V_G10 0x010A00CE #define PFNC_U3V_B10 0x010A00D2 #define PFNC_U3V_COORD3D_A10P 0x010A00D5 #define PFNC_U3V_COORD3D_B10P 0x010A00D6 #define PFNC_U3V_COORD3D_C10P 0x010A00D7 #define PFNC_U3V_MONO10PACKED 0x010C0004 #define PFNC_U3V_MONO12PACKED 0x010C0006 #define PFNC_U3V_BAYERGR10PACKED 0x010C0026 #define PFNC_U3V_BAYERRG10PACKED 0x010C0027 #define PFNC_U3V_BAYERGB10PACKED 0x010C0028 #define PFNC_U3V_BAYERBG10PACKED 0x010C0029 #define PFNC_U3V_BAYERGR12PACKED 0x010C002A #define PFNC_U3V_BAYERRG12PACKED 0x010C002B #define PFNC_U3V_BAYERGB12PACKED 0x010C002C #define PFNC_U3V_BAYERBG12PACKED 0x010C002D #define PFNC_U3V_MONO12P 0x010C0047 #define PFNC_U3V_BAYERBG12P 0x010C0053 #define PFNC_U3V_BAYERGB12P 0x010C0055 #define PFNC_U3V_BAYERGR12P 0x010C0057 #define PFNC_U3V_BAYERRG12P 0x010C0059 #define PFNC_U3V_SCF1WBWG12P 0x010C006B #define PFNC_U3V_SCF1WGWB12P 0x010C0072 #define PFNC_U3V_SCF1WGWR12P 0x010C0079 #define PFNC_U3V_SCF1WRWG12P 0x010C0080 #define PFNC_U3V_R12 0x010C00CB #define PFNC_U3V_G12 0x010C00CF #define PFNC_U3V_B12 0x010C00D3 #define PFNC_U3V_COORD3D_A12P 0x010C00D8 #define PFNC_U3V_COORD3D_B12P 0x010C00D9 #define PFNC_U3V_COORD3D_C12P 0x010C00DA #define PFNC_U3V_MONO10 0x01100003 #define PFNC_U3V_MONO12 0x01100005 #define PFNC_U3V_MONO16 0x01100007 #define PFNC_U3V_BAYERGR10 0x0110000C #define PFNC_U3V_BAYERRG10 0x0110000D #define PFNC_U3V_BAYERGB10 0x0110000E #define PFNC_U3V_BAYERBG10 0x0110000F #define PFNC_U3V_BAYERGR12 0x01100010 #define PFNC_U3V_BAYERRG12 0x01100011 #define PFNC_U3V_BAYERGB12 0x01100012 #define PFNC_U3V_BAYERBG12 0x01100013 #define PFNC_U3V_MONO14 0x01100025 #define PFNC_U3V_BAYERGR16 0x0110002E #define PFNC_U3V_BAYERRG16 0x0110002F #define PFNC_U3V_BAYERGB16 0x01100030 #define PFNC_U3V_BAYERBG16 0x01100031 #define PFNC_U3V_SCF1WBWG10 0x01100068 #define PFNC_U3V_SCF1WBWG12 0x0110006A #define PFNC_U3V_SCF1WBWG14 0x0110006C #define PFNC_U3V_SCF1WBWG16 0x0110006D #define PFNC_U3V_SCF1WGWB10 0x0110006F #define PFNC_U3V_SCF1WGWB12 0x01100071 #define PFNC_U3V_SCF1WGWB14 0x01100073 #define PFNC_U3V_SCF1WGWB16 0x01100074 #define PFNC_U3V_SCF1WGWR10 0x01100076 #define PFNC_U3V_SCF1WGWR12 0x01100078 #define PFNC_U3V_SCF1WGWR14 0x0110007A #define PFNC_U3V_SCF1WGWR16 0x0110007B #define PFNC_U3V_SCF1WRWG10 0x0110007D #define PFNC_U3V_SCF1WRWG12 0x0110007F #define PFNC_U3V_SCF1WRWG14 0x01100081 #define PFNC_U3V_SCF1WRWG16 0x01100082 #define PFNC_U3V_COORD3D_A16 0x011000B6 #define PFNC_U3V_COORD3D_B16 0x011000B7 #define PFNC_U3V_COORD3D_C16 0x011000B8 #define PFNC_U3V_CONFIDENCE16 0x011000C7 #define PFNC_U3V_R16 0x011000CC #define PFNC_U3V_G16 0x011000D0 #define PFNC_U3V_B16 0x011000D4 #define PFNC_U3V_COORD3D_A32F 0x012000BD #define PFNC_U3V_COORD3D_B32F 0x012000BE #define PFNC_U3V_COORD3D_C32F 0x012000BF #define PFNC_U3V_CONFIDENCE32F 0x012000C8 #define PFNC_U3V_YUV411_8_UYYVYY 0x020C001E #define PFNC_U3V_YCBCR411_8_CBYYCRYY 0x020C003C #define PFNC_U3V_YCBCR601_411_8_CBYYCRYY 0x020C003F #define PFNC_U3V_YCBCR709_411_8_CBYYCRYY 0x020C0042 #define PFNC_U3V_YCBCR411_8 0x020C005A #define PFNC_U3V_YUV422_8_UYVY 0x0210001F #define PFNC_U3V_YUV422_8 0x02100032 #define PFNC_U3V_RGB565P 0x02100035 #define PFNC_U3V_BGR565P 0x02100036 #define PFNC_U3V_YCBCR422_8 0x0210003B #define PFNC_U3V_YCBCR601_422_8 0x0210003E #define PFNC_U3V_YCBCR709_422_8 0x02100041 #define PFNC_U3V_YCBCR422_8_CBYCRY 0x02100043 #define PFNC_U3V_YCBCR601_422_8_CBYCRY 0x02100044 #define PFNC_U3V_YCBCR709_422_8_CBYCRY 0x02100045 #define PFNC_U3V_BICOLORRGBG8 0x021000A5 #define PFNC_U3V_BICOLORBGRG8 0x021000A6 #define PFNC_U3V_COORD3D_AC8 0x021000B4 #define PFNC_U3V_COORD3D_AC8_PLANAR 0x021000B5 #define PFNC_U3V_YCBCR422_10P 0x02140087 #define PFNC_U3V_YCBCR601_422_10P 0x0214008E #define PFNC_U3V_YCBCR709_422_10P 0x02140096 #define PFNC_U3V_YCBCR422_10P_CBYCRY 0x0214009A #define PFNC_U3V_YCBCR601_422_10P_CBYCRY 0x0214009E #define PFNC_U3V_YCBCR709_422_10P_CBYCRY 0x021400A2 #define PFNC_U3V_BICOLORRGBG10P 0x021400A8 #define PFNC_U3V_BICOLORBGRG10P 0x021400AA #define PFNC_U3V_COORD3D_AC10P 0x021400F0 #define PFNC_U3V_COORD3D_AC10P_PLANAR 0x021400F1 #define PFNC_U3V_RGB8 0x02180014 #define PFNC_U3V_BGR8 0x02180015 #define PFNC_U3V_YUV8_UYV 0x02180020 #define PFNC_U3V_RGB8_PLANAR 0x02180021 #define PFNC_U3V_YCBCR8_CBYCR 0x0218003A #define PFNC_U3V_YCBCR601_8_CBYCR 0x0218003D #define PFNC_U3V_YCBCR709_8_CBYCR 0x02180040 #define PFNC_U3V_YCBCR8 0x0218005B #define PFNC_U3V_YCBCR422_12P 0x02180088 #define PFNC_U3V_YCBCR601_422_12P 0x02180090 #define PFNC_U3V_YCBCR709_422_12P 0x02180098 #define PFNC_U3V_YCBCR422_12P_CBYCRY 0x0218009C #define PFNC_U3V_YCBCR601_422_12P_CBYCRY 0x021800A0 #define PFNC_U3V_YCBCR709_422_12P_CBYCRY 0x021800A4 #define PFNC_U3V_BICOLORRGBG12P 0x021800AC #define PFNC_U3V_BICOLORBGRG12P 0x021800AE #define PFNC_U3V_COORD3D_ABC8 0x021800B2 #define PFNC_U3V_COORD3D_ABC8_PLANAR 0x021800B3 #define PFNC_U3V_COORD3D_AC12P 0x021800F2 #define PFNC_U3V_COORD3D_AC12P_PLANAR 0x021800F3 #define PFNC_U3V_BGR10P 0x021E0048 #define PFNC_U3V_RGB10P 0x021E005C #define PFNC_U3V_YCBCR10P_CBYCR 0x021E0084 #define PFNC_U3V_YCBCR601_10P_CBYCR 0x021E008A #define PFNC_U3V_YCBCR709_10P_CBYCR 0x021E0092 #define PFNC_U3V_COORD3D_ABC10P 0x021E00DB #define PFNC_U3V_COORD3D_ABC10P_PLANAR 0x021E00DC #define PFNC_U3V_RGBA8 0x02200016 #define PFNC_U3V_BGRA8 0x02200017 #define PFNC_U3V_RGB10V1PACKED 0x0220001C #define PFNC_U3V_RGB10P32 0x0220001D #define PFNC_U3V_YCBCR422_10 0x02200065 #define PFNC_U3V_YCBCR422_12 0x02200066 #define PFNC_U3V_YCBCR601_422_10 0x0220008D #define PFNC_U3V_YCBCR601_422_12 0x0220008F #define PFNC_U3V_YCBCR709_422_10 0x02200095 #define PFNC_U3V_YCBCR709_422_12 0x02200097 #define PFNC_U3V_YCBCR422_10_CBYCRY 0x02200099 #define PFNC_U3V_YCBCR422_12_CBYCRY 0x0220009B #define PFNC_U3V_YCBCR601_422_10_CBYCRY 0x0220009D #define PFNC_U3V_YCBCR601_422_12_CBYCRY 0x0220009F #define PFNC_U3V_YCBCR709_422_10_CBYCRY 0x022000A1 #define PFNC_U3V_YCBCR709_422_12_CBYCRY 0x022000A3 #define PFNC_U3V_BICOLORRGBG10 0x022000A7 #define PFNC_U3V_BICOLORBGRG10 0x022000A9 #define PFNC_U3V_BICOLORRGBG12 0x022000AB #define PFNC_U3V_BICOLORBGRG12 0x022000AD #define PFNC_U3V_COORD3D_AC16 0x022000BB #define PFNC_U3V_COORD3D_AC16_PLANAR 0x022000BC #define PFNC_U3V_RGB12V1PACKED 0x02240034 #define PFNC_U3V_BGR12P 0x02240049 #define PFNC_U3V_RGB12P 0x0224005D #define PFNC_U3V_YCBCR12P_CBYCR 0x02240086 #define PFNC_U3V_YCBCR601_12P_CBYCR 0x0224008C #define PFNC_U3V_YCBCR709_12P_CBYCR 0x02240094 #define PFNC_U3V_COORD3D_ABC12P 0x022400DE #define PFNC_U3V_COORD3D_ABC12P_PLANAR 0x022400DF #define PFNC_U3V_BGRA10P 0x0228004D #define PFNC_U3V_RGBA10P 0x02280060 #define PFNC_U3V_RGB10 0x02300018 #define PFNC_U3V_BGR10 0x02300019 #define PFNC_U3V_RGB12 0x0230001A #define PFNC_U3V_BGR12 0x0230001B #define PFNC_U3V_RGB10_PLANAR 0x02300022 #define PFNC_U3V_RGB12_PLANAR 0x02300023 #define PFNC_U3V_RGB16_PLANAR 0x02300024 #define PFNC_U3V_RGB16 0x02300033 #define PFNC_U3V_BGR14 0x0230004A #define PFNC_U3V_BGR16 0x0230004B #define PFNC_U3V_BGRA12P 0x0230004F #define PFNC_U3V_RGB14 0x0230005E #define PFNC_U3V_RGBA12P 0x02300062 #define PFNC_U3V_YCBCR10_CBYCR 0x02300083 #define PFNC_U3V_YCBCR12_CBYCR 0x02300085 #define PFNC_U3V_YCBCR601_10_CBYCR 0x02300089 #define PFNC_U3V_YCBCR601_12_CBYCR 0x0230008B #define PFNC_U3V_YCBCR709_10_CBYCR 0x02300091 #define PFNC_U3V_YCBCR709_12_CBYCR 0x02300093 #define PFNC_U3V_COORD3D_ABC16 0x023000B9 #define PFNC_U3V_COORD3D_ABC16_PLANAR 0x023000BA #define PFNC_U3V_BGRA10 0x0240004C #define PFNC_U3V_BGRA12 0x0240004E #define PFNC_U3V_BGRA14 0x02400050 #define PFNC_U3V_BGRA16 0x02400051 #define PFNC_U3V_RGBA10 0x0240005F #define PFNC_U3V_RGBA12 0x02400061 #define PFNC_U3V_RGBA14 0x02400063 #define PFNC_U3V_RGBA16 0x02400064 #define PFNC_U3V_COORD3D_AC32F 0x024000C2 #define PFNC_U3V_COORD3D_AC32F_PLANAR 0x024000C3 #define PFNC_U3V_COORD3D_ABC32F 0x026000C0 #define PFNC_U3V_COORD3D_ABC32F_PLANAR 0x026000C1 /* Payload Types */ #define U3V_STREAM_PAYLOAD_IMAGE 0x0001 #define U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK 0x4001 #define U3V_STREAM_PAYLOAD_CHUNK 0x4000 void proto_register_u3v(void); void proto_reg_handoff_u3v(void); /* Define the u3v protocol */ static int proto_u3v = -1; /* GenCP transaction tracking * the protocol only allows strict sequential * communication. * * we track the current cmd/ack/pend_ack information * in a struct that is created per GenCP communication * * in each request/response packet we add pointers * to this information, that allow navigation between packets * and dissection of addresses */ typedef struct _gencp_transaction_t { guint32 cmd_frame; guint32 ack_frame; nstime_t cmd_time; /* list of pending acknowledges */ wmem_array_t *pend_ack_frame_list; /* current requested address */ guint64 address; /* current requested count read/write */ guint32 count; } gencp_transaction_t; typedef struct _u3v_conv_info_t { guint64 abrm_addr; guint64 sbrm_addr; guint64 sirm_addr; guint64 eirm_addr; guint64 iidc2_addr; guint64 manifest_addr; guint32 ep_stream; gencp_transaction_t *trans_info; } u3v_conv_info_t; /* \brief IDs used for bootstrap dissection */ static int hf_u3v_gencp_prefix = -1; static int hf_u3v_flag = -1; static int hf_u3v_acknowledge_required_flag = -1; static int hf_u3v_command_id = -1; static int hf_u3v_length = -1; static int hf_u3v_request_id = -1; static int hf_u3v_status = -1; static int hf_u3v_address = -1; static int hf_u3v_count = -1; static int hf_u3v_eventcmd_id = -1; static int hf_u3v_eventcmd_error_id = -1; static int hf_u3v_eventcmd_device_specific_id = -1; static int hf_u3v_eventcmd_timestamp = -1; static int hf_u3v_eventcmd_data = -1; static int hf_u3v_time_to_completion = -1; static int hf_u3v_payloaddata = -1; static int hf_u3v_reserved = -1; static int hf_u3v_bootstrap_GenCP_Version = -1; static int hf_u3v_bootstrap_Manufacturer_Name = -1; static int hf_u3v_bootstrap_Model_Name = -1; static int hf_u3v_bootstrap_Family_Name = -1; static int hf_u3v_bootstrap_Device_Version = -1; static int hf_u3v_bootstrap_Manufacturer_Info = -1; static int hf_u3v_bootstrap_Serial_Number = -1; static int hf_u3v_bootstrap_User_Defined_Name = -1; static int hf_u3v_bootstrap_Device_Capability = -1; static int hf_u3v_bootstrap_Maximum_Device_Response_Time = -1; static int hf_u3v_bootstrap_Manifest_Table_Address = -1; static int hf_u3v_bootstrap_SBRM_Address = -1; static int hf_u3v_bootstrap_Device_Configuration = -1; static int hf_u3v_bootstrap_Heartbeat_Timeout = -1; static int hf_u3v_bootstrap_Message_Channel_channel_id = -1; static int hf_u3v_bootstrap_Timestamp = -1; static int hf_u3v_bootstrap_Timestamp_Latch = -1; static int hf_u3v_bootstrap_Timestamp_Increment = -1; static int hf_u3v_bootstrap_Access_Privilege = -1; static int hf_u3v_bootstrap_Protocol_Endianess = -1; static int hf_u3v_bootstrap_Implementation_Endianess = -1; static int hf_u3v_bootstrap_U3V_Version = -1; static int hf_u3v_bootstrap_U3VCP_Capability_Register = -1; static int hf_u3v_bootstrap_U3VCP_Configuration_Register = -1; static int hf_u3v_bootstrap_Maximum_Command_Transfer_Length = -1; static int hf_u3v_bootstrap_Maximum_Acknowledge_Transfer_Length = -1; static int hf_u3v_bootstrap_Number_of_Stream_Channels = -1; static int hf_u3v_bootstrap_SIRM_Address = -1; static int hf_u3v_bootstrap_SIRM_Length = -1; static int hf_u3v_bootstrap_EIRM_Address = -1; static int hf_u3v_bootstrap_EIRM_Length = -1; static int hf_u3v_bootstrap_IIDC2_Address = -1; static int hf_u3v_bootstrap_Current_Speed = -1; static int hf_u3v_bootstrap_SI_Info = -1; static int hf_u3v_bootstrap_SI_Control = -1; static int hf_u3v_bootstrap_SI_Required_Payload_Size = -1; static int hf_u3v_bootstrap_SI_Required_Leader_Size = -1; static int hf_u3v_bootstrap_SI_Required_Trailer_Size = -1; static int hf_u3v_bootstrap_SI_Maximum_Leader_Size = -1; static int hf_u3v_bootstrap_SI_Payload_Transfer_Size = -1; static int hf_u3v_bootstrap_SI_Payload_Transfer_Count = -1; static int hf_u3v_bootstrap_SI_Payload_Final_Transfer1_Size = -1; static int hf_u3v_bootstrap_SI_Payload_Final_Transfer2_Size = -1; static int hf_u3v_bootstrap_SI_Maximum_Trailer_Size = -1; static int hf_u3v_bootstrap_EI_Control = -1; static int hf_u3v_bootstrap_Maximum_Event_Transfer_Length = -1; static int hf_u3v_bootstrap_Event_Test_Control = -1; static int hf_u3v_custom_memory_addr = -1; static int hf_u3v_custom_memory_data = -1; static int hf_u3v_scd_readmem_cmd = -1; static int hf_u3v_scd_writemem_cmd = -1; static int hf_u3v_scd_event_cmd = -1; static int hf_u3v_scd_ack_readmem_ack = -1; static int hf_u3v_scd_writemem_ack = -1; static int hf_u3v_ccd_pending_ack = -1; static int hf_u3v_stream_leader = -1; static int hf_u3v_stream_trailer = -1; static int hf_u3v_stream_payload = -1; static int hf_u3v_ccd_cmd = -1; static int hf_u3v_ccd_ack = -1; static int hf_u3v_device_info_descriptor = -1; /* stream elements */ static int hf_u3v_stream_reserved = -1; static int hf_u3v_stream_leader_size = -1; static int hf_u3v_stream_prefix = -1; static int hf_u3v_stream_trailer_size = -1; static int hf_u3v_stream_block_id = -1; static int hf_u3v_stream_payload_type = -1; static int hf_u3v_stream_status = -1; static int hf_u3v_stream_valid_payload_size = -1; static int hf_u3v_stream_timestamp = -1; static int hf_u3v_stream_pixel_format = -1; static int hf_u3v_stream_size_x = -1; static int hf_u3v_stream_size_y = -1; static int hf_u3v_stream_offset_x = -1; static int hf_u3v_stream_offset_y = -1; static int hf_u3v_stream_padding_x = -1; static int hf_u3v_stream_chunk_layout_id = -1; static int hf_u3v_stream_data = -1; /* U3V device info descriptor */ static int hf_u3v_device_info_descriptor_bLength = -1; static int hf_u3v_device_info_descriptor_bDescriptorType = -1; static int hf_u3v_device_info_descriptor_bDescriptorSubtype = -1; static int hf_u3v_device_info_descriptor_bGenCPVersion = -1; static int hf_u3v_device_info_descriptor_bGenCPVersion_minor = -1; static int hf_u3v_device_info_descriptor_bGenCPVersion_major = -1; static int hf_u3v_device_info_descriptor_bU3VVersion = -1; static int hf_u3v_device_info_descriptor_bU3VVersion_minor = -1; static int hf_u3v_device_info_descriptor_bU3VVersion_major = -1; static int hf_u3v_device_info_descriptor_iDeviceGUID = -1; static int hf_u3v_device_info_descriptor_iVendorName = -1; static int hf_u3v_device_info_descriptor_iModelName = -1; static int hf_u3v_device_info_descriptor_iFamilyName = -1; static int hf_u3v_device_info_descriptor_iDeviceVersion = -1; static int hf_u3v_device_info_descriptor_iManufacturerInfo = -1; static int hf_u3v_device_info_descriptor_iSerialNumber = -1; static int hf_u3v_device_info_descriptor_iUserDefinedName = -1; static int hf_u3v_device_info_descriptor_bmSpeedSupport = -1; static int hf_u3v_device_info_descriptor_bmSpeedSupport_low_speed = -1; static int hf_u3v_device_info_descriptor_bmSpeedSupport_full_speed = -1; static int hf_u3v_device_info_descriptor_bmSpeedSupport_high_speed = -1; static int hf_u3v_device_info_descriptor_bmSpeedSupport_super_speed = -1; static int hf_u3v_device_info_descriptor_bmSpeedSupport_reserved = -1; /*Define the tree for u3v*/ static int ett_u3v = -1; static int ett_u3v_cmd = -1; static int ett_u3v_flags = -1; static int ett_u3v_ack = -1; static int ett_u3v_payload_cmd = -1; static int ett_u3v_payload_ack = -1; static int ett_u3v_payload_cmd_subtree = -1; static int ett_u3v_payload_ack_subtree = -1; static int ett_u3v_bootstrap_fields = -1; static int ett_u3v_stream_leader = -1; static int ett_u3v_stream_trailer = -1; static int ett_u3v_stream_payload = -1; static int ett_u3v_device_info_descriptor = -1; static int ett_u3v_device_info_descriptor_speed_support = -1; static int ett_u3v_device_info_descriptor_gencp_version = -1; static int ett_u3v_device_info_descriptor_u3v_version = -1; static const value_string command_names[] = { { U3V_READMEM_CMD, "READMEM_CMD" }, { U3V_WRITEMEM_CMD, "WRITEMEM_CMD" }, { U3V_EVENT_CMD, "EVENT_CMD" }, { U3V_READMEM_ACK, "READMEM_ACK" }, { U3V_WRITEMEM_ACK, "WRITEMEM_ACK" }, { U3V_PENDING_ACK, "PENDING_ACK" }, { U3V_EVENT_ACK, "EVENT_ACK" }, { 0, NULL } }; static const value_string event_id_names[] = { { U3V_EVENT_TESTEVENT, "U3V_EVENT_TESTEVENT" }, { 0, NULL } }; static const value_string status_names[] = { { U3V_STATUS_GENCP_SUCCESS, "U3V_STATUS_GENCP_SUCCESS" }, { U3V_STATUS_GENCP_NOT_IMPLEMENTED, "U3V_STATUS_GENCP_NOT_IMPLEMENTED" }, { U3V_STATUS_GENCP_INVALID_PARAMETER, "U3V_STATUS_GENCP_INVALID_PARAMETER" }, { U3V_STATUS_GENCP_INVALID_ADDRESS, "U3V_STATUS_GENCP_INVALID_ADDRESS" }, { U3V_STATUS_GENCP_WRITE_PROTECT, "U3V_STATUS_GENCP_WRITE_PROTECT" }, { U3V_STATUS_GENCP_BAD_ALIGNMENT, "U3V_STATUS_GENCP_BAD_ALIGNMENT" }, { U3V_STATUS_GENCP_ACCESS_DENIED, "U3V_STATUS_GENCP_ACCESS_DENIED" }, { U3V_STATUS_GENCP_BUSY, "U3V_STATUS_GENCP_BUSY" }, { U3V_STATUS_GENCP_WRONG_CONFIG, "U3V_STATUS_GENCP_WRONG_CONFIG" }, { U3V_STATUS_RESEND_NOT_SUPPORTED, "U3V_STATUS_RESEND_NOT_SUPPORTED" }, { U3V_STATUS_DSI_ENDPOINT_HALTED, "U3V_STATUS_DSI_ENDPOINT_HALTED" }, { U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED, "U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED" }, { U3V_STATUS_SI_REGISTERS_INCONSISTENT, "U3V_STATUS_SI_REGISTERS_INCONSISTENT" }, { U3V_STATUS_DATA_DISCARDED, "U3V_STATUS_DATA_DISCARDED" }, { 0, NULL } }; static const value_string status_names_short[] = { { U3V_STATUS_GENCP_SUCCESS, "" }, { U3V_STATUS_GENCP_NOT_IMPLEMENTED, "U3V_STATUS_GENCP_NOT_IMPLEMENTED" }, { U3V_STATUS_GENCP_INVALID_PARAMETER, "U3V_STATUS_GENCP_INVALID_PARAMETER" }, { U3V_STATUS_GENCP_INVALID_ADDRESS, "U3V_STATUS_GENCP_INVALID_ADDRESS" }, { U3V_STATUS_GENCP_WRITE_PROTECT, "U3V_STATUS_GENCP_WRITE_PROTECT" }, { U3V_STATUS_GENCP_BAD_ALIGNMENT, "U3V_STATUS_GENCP_BAD_ALIGNMENT" }, { U3V_STATUS_GENCP_ACCESS_DENIED, "U3V_STATUS_GENCP_ACCESS_DENIED" }, { U3V_STATUS_GENCP_BUSY, "U3V_STATUS_GENCP_BUSY" }, { U3V_STATUS_GENCP_WRONG_CONFIG, "U3V_STATUS_GENCP_WRONG_CONFIG" }, { U3V_STATUS_RESEND_NOT_SUPPORTED, "U3V_STATUS_RESEND_NOT_SUPPORTED" }, { U3V_STATUS_DSI_ENDPOINT_HALTED, "U3V_STATUS_DSI_ENDPOINT_HALTED" }, { U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED, "U3V_STATUS_SI_PAYLOAD_SIZE_NOT_ALIGNED" }, { U3V_STATUS_SI_REGISTERS_INCONSISTENT, "U3V_STATUS_SI_REGISTERS_INCONSISTENT" }, { U3V_STATUS_DATA_DISCARDED, "U3V_STATUS_DATA_DISCARDED" }, { 0, NULL } }; /* \brief Register name to address mappings */ static const value_string bootstrap_register_names_abrm[] = { { U3V_ABRM_GENCP_VERSION, "[GenCP_Version]" }, { U3V_ABRM_MANUFACTURER_NAME, "[Manufacturer_Name]" }, { U3V_ABRM_MODEL_NAME, "[Model_Name]" }, { U3V_ABRM_FAMILY_NAME, "[Family_Name]" }, { U3V_ABRM_DEVICE_VERSION, "[Device_Version]" }, { U3V_ABRM_MANUFACTURER_INFO, "[Manufacturer_Info]" }, { U3V_ABRM_SERIAL_NUMBER, "[Serial_Number]" }, { U3V_ABRM_USER_DEFINED_NAME, "[User_Defined_Name]" }, { U3V_ABRM_DEVICE_CAPABILITY, "[Device_Capability]" }, { U3V_ABRM_MAXIMUM_DEVICE_RESPONSE_TIME, "[Maximum_Device_Response_Time]" }, { U3V_ABRM_MANIFEST_TABLE_ADDRESS, "[Manifest_Table_Address]" }, { U3V_ABRM_SBRM_ADDRESS, "[SBRM_Address]" }, { U3V_ABRM_DEVICE_CONFIGURATION, "[Device_Configuration]" }, { U3V_ABRM_HEARTBEAT_TIMEOUT, "[Heartbeat_Timeout]" }, { U3V_ABRM_MESSAGE_CHANNEL_CHANNEL_ID, "[Message_Channel_channel_id]" }, { U3V_ABRM_TIMESTAMP, "[Timestamp]" }, { U3V_ABRM_TIMESTAMP_LATCH, "[Timestamp_Latch]" }, { U3V_ABRM_TIMESTAMP_INCREMENT, "[Timestamp_Increment]" }, { U3V_ABRM_ACCESS_PRIVILEGE, "[Access_Privilege]" }, { U3V_ABRM_PROTOCOL_ENDIANESS, "[Protocol_Endianess]" }, { U3V_ABRM_IMPLEMENTATION_ENDIANESS, "[Implementation_Endianess]" }, { 0, NULL } }; static const value_string bootstrap_register_names_sbrm[] = { { U3V_SBRM_U3V_VERSION, "[U3V_Version]" }, { U3V_SBRM_U3VCP_CAPABILITY_REGISTER, "[U3VCP_Capability_Register]" }, { U3V_SBRM_U3VCP_CONFIGURATION_REGISTER, "[U3VCP_Configuration_Register]" }, { U3V_SBRM_MAXIMUM_COMMAND_TRANSFER_LENGTH, "[Maximum_Command_Transfer_Length]" }, { U3V_SBRM_MAXIMUM_ACKNOWLEDGE_TRANSFER_LENGTH, "[Maximum_Acknowledge_Transfer_Length]" }, { U3V_SBRM_NUMBER_OF_STREAM_CHANNELS, "[Number_of_Stream_Channels]" }, { U3V_SBRM_SIRM_ADDRESS, "[SIRM_Address]" }, { U3V_SBRM_SIRM_LENGTH, "[SIRM_Length]" }, { U3V_SBRM_EIRM_ADDRESS, "[EIRM_Address]" }, { U3V_SBRM_EIRM_LENGTH, "[EIRM_Length]" }, { U3V_SBRM_IIDC2_ADDRESS, "[IIDC2_Address]" }, { U3V_SBRM_CURRENT_SPEED, "[Current_Speed]" }, { 0, NULL } }; static const value_string bootstrap_register_names_sirm[] = { { U3V_SIRM_SI_INFO, "[SI_Info]" }, { U3V_SIRM_SI_CONTROL, "[SI_Control]" }, { U3V_SIRM_SI_REQUIRED_PAYLOAD_SIZE, "[SI_Required_Payload_Size]" }, { U3V_SIRM_SI_REQUIRED_LEADER_SIZE, "[SI_Required_Leader_Size]" }, { U3V_SIRM_SI_REQUIRED_TRAILER_SIZE, "[SI_Required_Trailer_Size]" }, { U3V_SIRM_SI_MAXIMUM_LEADER_SIZE, "[SI_Maximum_Leader_Size]" }, { U3V_SIRM_SI_PAYLOAD_TRANSFER_SIZE, "[SI_Payload_Transfer_Size]" }, { U3V_SIRM_SI_PAYLOAD_TRANSFER_COUNT, "[SI_Payload_Transfer_Count]" }, { U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER1_SIZE, "[SI_Payload_Final_Transfer1_Size]" }, { U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER2_SIZE, "[SI_Payload_Final_Transfer2_Size]" }, { U3V_SIRM_SI_MAXIMUM_TRAILER_SIZE, "[SI_Maximum_Trailer_Size]" }, { 0, NULL } }; static const value_string bootstrap_register_names_eirm[] = { { U3V_EIRM_EI_CONTROL, "[EI_Control]" }, { U3V_EIRM_MAXIMUM_EVENT_TRANSFER_LENGTH, "[Maximum_Event_Transfer_Length]" }, { U3V_EIRM_EVENT_TEST_CONTROL, "[Event_Test_Control]" }, { 0, NULL } }; static const value_string pixel_format_names[] = { { PFNC_U3V_MONO1P, "Mono1p" }, { PFNC_U3V_CONFIDENCE1P, "CONFIDENCE1p" }, { PFNC_U3V_MONO2P, "Mono2p" }, { PFNC_U3V_MONO4P, "Mono4p" }, { PFNC_U3V_MONO8, "Mono8" }, { PFNC_U3V_MONO8S, "Mono8s" }, { PFNC_U3V_BAYERGR8, "BayerGR8" }, { PFNC_U3V_BAYERRG8, "BayerRG8" }, { PFNC_U3V_BAYERGB8, "BayerGB8" }, { PFNC_U3V_BAYERBG8, "BayerBG8" }, { PFNC_U3V_SCF1WBWG8, "SCF1WBWG8" }, { PFNC_U3V_SCF1WGWB8, "SCF1WGWB8" }, { PFNC_U3V_SCF1WGWR8, "SCF1WGWR8" }, { PFNC_U3V_SCF1WRWG8, "SCF1WRWG8" }, { PFNC_U3V_COORD3D_A8, "Coord3D_A8" }, { PFNC_U3V_COORD3D_B8, "Coord3D_B8" }, { PFNC_U3V_COORD3D_C8, "Coord3D_C8" }, { PFNC_U3V_CONFIDENCE1, "CONFIDENCE1" }, { PFNC_U3V_CONFIDENCE8, "CONFIDENCE8" }, { PFNC_U3V_R8, "R8" }, { PFNC_U3V_G8, "G8" }, { PFNC_U3V_B8, "B8" }, { PFNC_U3V_MONO10P, "Mono10p" }, { PFNC_U3V_BAYERBG10P, "BayerBG10p" }, { PFNC_U3V_BAYERGB10P, "BayerGB10p" }, { PFNC_U3V_BAYERGR10P, "BayerGR10p" }, { PFNC_U3V_BAYERRG10P, "BayerRG10p" }, { PFNC_U3V_SCF1WBWG10P, "SCF1WBWG10p" }, { PFNC_U3V_SCF1WGWB10P, "SCF1WGWB10p" }, { PFNC_U3V_SCF1WGWR10P, "SCF1WGWR10p" }, { PFNC_U3V_SCF1WRWG10P, "SCF1WRWG10p" }, { PFNC_U3V_R10, "R10" }, { PFNC_U3V_G10, "G10" }, { PFNC_U3V_B10, "B10" }, { PFNC_U3V_COORD3D_A10P, "Coord3D_A10p" }, { PFNC_U3V_COORD3D_B10P, "Coord3D_B10p" }, { PFNC_U3V_COORD3D_C10P, "Coord3D_C10p" }, { PFNC_U3V_MONO10PACKED, "Mono10Packed" }, { PFNC_U3V_MONO12PACKED, "Mono12Packed" }, { PFNC_U3V_BAYERGR10PACKED, "BayerGR10Packed" }, { PFNC_U3V_BAYERRG10PACKED, "BayerRG10Packed" }, { PFNC_U3V_BAYERGB10PACKED, "BayerGB10Packed" }, { PFNC_U3V_BAYERBG10PACKED, "BayerBG10Packed" }, { PFNC_U3V_BAYERGR12PACKED, "BayerGR12Packed" }, { PFNC_U3V_BAYERRG12PACKED, "BayerRG12Packed" }, { PFNC_U3V_BAYERGB12PACKED, "BayerGB12Packed" }, { PFNC_U3V_BAYERBG12PACKED, "BayerBG12Packed" }, { PFNC_U3V_MONO12P, "Mono12p" }, { PFNC_U3V_BAYERBG12P, "BayerBG12p" }, { PFNC_U3V_BAYERGB12P, "BayerGB12p" }, { PFNC_U3V_BAYERGR12P, "BayerGR12p" }, { PFNC_U3V_BAYERRG12P, "BayerRG12p" }, { PFNC_U3V_SCF1WBWG12P, "SCF1WBWG12p" }, { PFNC_U3V_SCF1WGWB12P, "SCF1WGWB12p" }, { PFNC_U3V_SCF1WGWR12P, "SCF1WGWR12p" }, { PFNC_U3V_SCF1WRWG12P, "SCF1WRWG12p" }, { PFNC_U3V_R12, "R12" }, { PFNC_U3V_G12, "G12" }, { PFNC_U3V_B12, "B12" }, { PFNC_U3V_COORD3D_A12P, "Coord3D_A12p" }, { PFNC_U3V_COORD3D_B12P, "Coord3D_B12p" }, { PFNC_U3V_COORD3D_C12P, "Coord3D_C12p" }, { PFNC_U3V_MONO10, "Mono10" }, { PFNC_U3V_MONO12, "Mono12" }, { PFNC_U3V_MONO16, "Mono16" }, { PFNC_U3V_BAYERGR10, "BayerGR10" }, { PFNC_U3V_BAYERRG10, "BayerRG10" }, { PFNC_U3V_BAYERGB10, "BayerGB10" }, { PFNC_U3V_BAYERBG10, "BayerBG10" }, { PFNC_U3V_BAYERGR12, "BayerGR12" }, { PFNC_U3V_BAYERRG12, "BayerRG12" }, { PFNC_U3V_BAYERGB12, "BayerGB12" }, { PFNC_U3V_BAYERBG12, "BayerBG12" }, { PFNC_U3V_MONO14, "Mono14" }, { PFNC_U3V_BAYERGR16, "BayerGR16" }, { PFNC_U3V_BAYERRG16, "BayerRG16" }, { PFNC_U3V_BAYERGB16, "BayerGB16" }, { PFNC_U3V_BAYERBG16, "BayerBG16" }, { PFNC_U3V_SCF1WBWG10, "SCF1WBWG10" }, { PFNC_U3V_SCF1WBWG12, "SCF1WBWG12" }, { PFNC_U3V_SCF1WBWG14, "SCF1WBWG14" }, { PFNC_U3V_SCF1WBWG16, "SCF1WBWG16" }, { PFNC_U3V_SCF1WGWB10, "SCF1WGWB10" }, { PFNC_U3V_SCF1WGWB12, "SCF1WGWB12" }, { PFNC_U3V_SCF1WGWB14, "SCF1WGWB14" }, { PFNC_U3V_SCF1WGWB16, "SCF1WGWB16" }, { PFNC_U3V_SCF1WGWR10, "SCF1WGWR10" }, { PFNC_U3V_SCF1WGWR12, "SCF1WGWR12" }, { PFNC_U3V_SCF1WGWR14, "SCF1WGWR14" }, { PFNC_U3V_SCF1WGWR16, "SCF1WGWR16" }, { PFNC_U3V_SCF1WRWG10, "SCF1WRWG10" }, { PFNC_U3V_SCF1WRWG12, "SCF1WRWG12" }, { PFNC_U3V_SCF1WRWG14, "SCF1WRWG14" }, { PFNC_U3V_SCF1WRWG16, "SCF1WRWG16" }, { PFNC_U3V_COORD3D_A16, "Coord3D_A16" }, { PFNC_U3V_COORD3D_B16, "Coord3D_B16" }, { PFNC_U3V_COORD3D_C16, "Coord3D_C16" }, { PFNC_U3V_CONFIDENCE16, "CONFIDENCE16" }, { PFNC_U3V_R16, "R16" }, { PFNC_U3V_G16, "G16" }, { PFNC_U3V_B16, "B16" }, { PFNC_U3V_COORD3D_A32F, "Coord3D_A32F" }, { PFNC_U3V_COORD3D_B32F, "Coord3D_B32F" }, { PFNC_U3V_COORD3D_C32F, "Coord3D_C32F" }, { PFNC_U3V_CONFIDENCE32F, "CONFIDENCE32F" }, { PFNC_U3V_YUV411_8_UYYVYY, "YUV411_8_UYYVYY" }, { PFNC_U3V_YCBCR411_8_CBYYCRYY, "YCbCr411_8_CBYYCRYY" }, { PFNC_U3V_YCBCR601_411_8_CBYYCRYY, "YCbCr601_411_8_CBYYCRYY" }, { PFNC_U3V_YCBCR709_411_8_CBYYCRYY, "YCbCr709_411_8_CBYYCRYY" }, { PFNC_U3V_YCBCR411_8, "YCbCr411_8" }, { PFNC_U3V_YUV422_8_UYVY, "YUV422_8_UYVY" }, { PFNC_U3V_YUV422_8, "YUV422_8" }, { PFNC_U3V_RGB565P, "RGB565p" }, { PFNC_U3V_BGR565P, "BGR565p" }, { PFNC_U3V_YCBCR422_8, "YCbCr422_8" }, { PFNC_U3V_YCBCR601_422_8, "YCbCr601_422_8" }, { PFNC_U3V_YCBCR709_422_8, "YCbCr709_422_8" }, { PFNC_U3V_YCBCR422_8_CBYCRY, "YCbCr422_8_CBYCRY" }, { PFNC_U3V_YCBCR601_422_8_CBYCRY, "YCbCr601_422_8_CBYCRY" }, { PFNC_U3V_YCBCR709_422_8_CBYCRY, "YCbCr709_422_8_CBYCRY" }, { PFNC_U3V_BICOLORRGBG8, "BICOLORRGBG8" }, { PFNC_U3V_BICOLORBGRG8, "BICOLORBGRG8" }, { PFNC_U3V_COORD3D_AC8, "Coord3D_AC8" }, { PFNC_U3V_COORD3D_AC8_PLANAR, "Coord3D_AC8_Planar" }, { PFNC_U3V_YCBCR422_10P, "YCbCr422_10p" }, { PFNC_U3V_YCBCR601_422_10P, "YCbCr601_422_10p" }, { PFNC_U3V_YCBCR709_422_10P, "YCbCr709_422_10p" }, { PFNC_U3V_YCBCR422_10P_CBYCRY, "YCbCr422_10P_CBYCRY" }, { PFNC_U3V_YCBCR601_422_10P_CBYCRY, "YCbCr601_422_10P_CBYCRY" }, { PFNC_U3V_YCBCR709_422_10P_CBYCRY, "YCbCr709_422_10P_CBYCRY" }, { PFNC_U3V_BICOLORRGBG10P, "BICOLORRGBG10p" }, { PFNC_U3V_BICOLORBGRG10P, "BICOLORBGRG10p" }, { PFNC_U3V_COORD3D_AC10P, "Coord3D_AC10p" }, { PFNC_U3V_COORD3D_AC10P_PLANAR, "Coord3D_AC10P_Planar" }, { PFNC_U3V_RGB8, "RGB8" }, { PFNC_U3V_BGR8, "BGR8" }, { PFNC_U3V_YUV8_UYV, "YUV8_UYV" }, { PFNC_U3V_RGB8_PLANAR, "RGB8_Planar" }, { PFNC_U3V_YCBCR8_CBYCR, "YCbCr8_CBYCR" }, { PFNC_U3V_YCBCR601_8_CBYCR, "YCbCr601_8_CBYCR" }, { PFNC_U3V_YCBCR709_8_CBYCR, "YCbCr709_8_CBYCR" }, { PFNC_U3V_YCBCR8, "YCbCr8" }, { PFNC_U3V_YCBCR422_12P, "YCbCr422_12p" }, { PFNC_U3V_YCBCR601_422_12P, "YCbCr601_422_12p" }, { PFNC_U3V_YCBCR709_422_12P, "YCbCr709_422_12p" }, { PFNC_U3V_YCBCR422_12P_CBYCRY, "YCbCr422_12P_CBYCRY" }, { PFNC_U3V_YCBCR601_422_12P_CBYCRY, "YCbCr601_422_12P_CBYCRY" }, { PFNC_U3V_YCBCR709_422_12P_CBYCRY, "YCbCr709_422_12P_CBYCRY" }, { PFNC_U3V_BICOLORRGBG12P, "BICOLORRGBG12p" }, { PFNC_U3V_BICOLORBGRG12P, "BICOLORBGRG12p" }, { PFNC_U3V_COORD3D_ABC8, "Coord3D_ABC8" }, { PFNC_U3V_COORD3D_ABC8_PLANAR, "Coord3D_ABC8_Planar" }, { PFNC_U3V_COORD3D_AC12P, "Coord3D_AC12p" }, { PFNC_U3V_COORD3D_AC12P_PLANAR, "Coord3D_AC12P_Planar" }, { PFNC_U3V_BGR10P, "BGR10p" }, { PFNC_U3V_RGB10P, "RGB10p" }, { PFNC_U3V_YCBCR10P_CBYCR, "YCbCr10P_CBYCR" }, { PFNC_U3V_YCBCR601_10P_CBYCR, "YCbCr601_10P_CBYCR" }, { PFNC_U3V_YCBCR709_10P_CBYCR, "YCbCr709_10P_CBYCR" }, { PFNC_U3V_COORD3D_ABC10P, "Coord3D_ABC10p" }, { PFNC_U3V_COORD3D_ABC10P_PLANAR, "Coord3D_ABC10P_Planar" }, { PFNC_U3V_RGBA8, "RGBA8" }, { PFNC_U3V_BGRA8, "BGRA8" }, { PFNC_U3V_RGB10V1PACKED, "RGB10V1Packed" }, { PFNC_U3V_RGB10P32, "RGB10P32" }, { PFNC_U3V_YCBCR422_10, "YCbCr422_10" }, { PFNC_U3V_YCBCR422_12, "YCbCr422_12" }, { PFNC_U3V_YCBCR601_422_10, "YCbCr601_422_10" }, { PFNC_U3V_YCBCR601_422_12, "YCbCr601_422_12" }, { PFNC_U3V_YCBCR709_422_10, "YCbCr709_422_10" }, { PFNC_U3V_YCBCR709_422_12, "YCbCr709_422_12" }, { PFNC_U3V_YCBCR422_10_CBYCRY, "YCbCr422_10_CBYCRY" }, { PFNC_U3V_YCBCR422_12_CBYCRY, "YCbCr422_12_CBYCRY" }, { PFNC_U3V_YCBCR601_422_10_CBYCRY, "YCbCr601_422_10_CBYCRY" }, { PFNC_U3V_YCBCR601_422_12_CBYCRY, "YCbCr601_422_12_CBYCRY" }, { PFNC_U3V_YCBCR709_422_10_CBYCRY, "YCbCr709_422_10_CBYCRY" }, { PFNC_U3V_YCBCR709_422_12_CBYCRY, "YCbCr709_422_12_CBYCRY" }, { PFNC_U3V_BICOLORRGBG10, "BICOLORRGBG10" }, { PFNC_U3V_BICOLORBGRG10, "BICOLORBGRG10" }, { PFNC_U3V_BICOLORRGBG12, "BICOLORRGBG12" }, { PFNC_U3V_BICOLORBGRG12, "BICOLORBGRG12" }, { PFNC_U3V_COORD3D_AC16, "Coord3D_AC16" }, { PFNC_U3V_COORD3D_AC16_PLANAR, "Coord3D_AC16_Planar" }, { PFNC_U3V_RGB12V1PACKED, "RGB12V1Packed" }, { PFNC_U3V_BGR12P, "BGR12p" }, { PFNC_U3V_RGB12P, "RGB12p" }, { PFNC_U3V_YCBCR12P_CBYCR, "YCbCr12P_CBYCR" }, { PFNC_U3V_YCBCR601_12P_CBYCR, "YCbCr601_12P_CBYCR" }, { PFNC_U3V_YCBCR709_12P_CBYCR, "YCbCr709_12P_CBYCR" }, { PFNC_U3V_COORD3D_ABC12P, "Coord3D_ABC12p" }, { PFNC_U3V_COORD3D_ABC12P_PLANAR, "Coord3D_ABC12P_Planar" }, { PFNC_U3V_BGRA10P, "BGRA10p" }, { PFNC_U3V_RGBA10P, "RGBA10p" }, { PFNC_U3V_RGB10, "RGB10" }, { PFNC_U3V_BGR10, "BGR10" }, { PFNC_U3V_RGB12, "RGB12" }, { PFNC_U3V_BGR12, "BGR12" }, { PFNC_U3V_RGB10_PLANAR, "RGB10_Planar" }, { PFNC_U3V_RGB12_PLANAR, "RGB12_Planar" }, { PFNC_U3V_RGB16_PLANAR, "RGB16_Planar" }, { PFNC_U3V_RGB16, "RGB16" }, { PFNC_U3V_BGR14, "BGR14" }, { PFNC_U3V_BGR16, "BGR16" }, { PFNC_U3V_BGRA12P, "BGRA12p" }, { PFNC_U3V_RGB14, "RGB14" }, { PFNC_U3V_RGBA12P, "RGBA12p" }, { PFNC_U3V_YCBCR10_CBYCR, "YCbCr10_CBYCR" }, { PFNC_U3V_YCBCR12_CBYCR, "YCbCr12_CBYCR" }, { PFNC_U3V_YCBCR601_10_CBYCR, "YCbCr601_10_CBYCR" }, { PFNC_U3V_YCBCR601_12_CBYCR, "YCbCr601_12_CBYCR" }, { PFNC_U3V_YCBCR709_10_CBYCR, "YCbCr709_10_CBYCR" }, { PFNC_U3V_YCBCR709_12_CBYCR, "YCbCr709_12_CBYCR" }, { PFNC_U3V_COORD3D_ABC16, "Coord3D_ABC16" }, { PFNC_U3V_COORD3D_ABC16_PLANAR, "Coord3D_ABC16_Planar" }, { PFNC_U3V_BGRA10, "BGRA10" }, { PFNC_U3V_BGRA12, "BGRA12" }, { PFNC_U3V_BGRA14, "BGRA14" }, { PFNC_U3V_BGRA16, "BGRA16" }, { PFNC_U3V_RGBA10, "RGBA10" }, { PFNC_U3V_RGBA12, "RGBA12" }, { PFNC_U3V_RGBA14, "RGBA14" }, { PFNC_U3V_RGBA16, "RGBA16" }, { PFNC_U3V_COORD3D_AC32F, "Coord3D_AC32F" }, { PFNC_U3V_COORD3D_AC32F_PLANAR, "Coord3D_AC32F_Planar" }, { PFNC_U3V_COORD3D_ABC32F, "Coord3D_ABC32F" }, { PFNC_U3V_COORD3D_ABC32F_PLANAR, "Coord3D_ABC32F_Planar" }, { 0, NULL } }; static value_string_ext pixel_format_names_ext = VALUE_STRING_EXT_INIT(pixel_format_names); static const value_string payload_type_names[] = { { U3V_STREAM_PAYLOAD_IMAGE, "Image" }, { U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK, "Image Extended Chunk" }, { U3V_STREAM_PAYLOAD_CHUNK, "Chunk" }, { 0, NULL } }; static const value_string u3v_descriptor_subtypes[] = { { DESCRIPTOR_SUBTYPE_U3V_DEVICE_INFO, "U3V DEVICE INFO" }, { 0, NULL } }; static const int *speed_support_fields[] = { &hf_u3v_device_info_descriptor_bmSpeedSupport_low_speed, &hf_u3v_device_info_descriptor_bmSpeedSupport_full_speed, &hf_u3v_device_info_descriptor_bmSpeedSupport_high_speed, &hf_u3v_device_info_descriptor_bmSpeedSupport_super_speed, &hf_u3v_device_info_descriptor_bmSpeedSupport_reserved, NULL }; /* \brief Returns a register name based on its address */ static const gchar* get_register_name_from_address(guint64 addr, gboolean* is_custom_register, u3v_conv_info_t * u3v_conv_info) { const gchar* address_string = NULL; guint32 offset_address; if (is_custom_register != NULL) { *is_custom_register = FALSE; } /* check if this is the access to one of the base address registers */ if ( addr < 0x10000 ) { offset_address = (guint32)addr; address_string = try_val_to_str(offset_address, bootstrap_register_names_abrm); } if ( u3v_conv_info && u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) { offset_address = (guint32)( addr - u3v_conv_info->sbrm_addr); address_string = try_val_to_str(offset_address, bootstrap_register_names_sbrm); } if ( u3v_conv_info && u3v_conv_info->sirm_addr != 0 && (addr >= u3v_conv_info->sirm_addr)) { offset_address = (guint32)( addr - u3v_conv_info->sirm_addr); address_string = try_val_to_str(offset_address, bootstrap_register_names_sirm); } if ( u3v_conv_info && u3v_conv_info->eirm_addr != 0 && (addr >= u3v_conv_info->eirm_addr)) { offset_address = (guint32)( addr - u3v_conv_info->eirm_addr); address_string = try_val_to_str(offset_address, bootstrap_register_names_eirm); } if (!address_string) { address_string = wmem_strdup_printf(wmem_packet_scope(), "[Addr:0x%016" G_GINT64_MODIFIER "X]", addr); if (is_custom_register != NULL) { *is_custom_register = TRUE; } } return address_string; } /* \brief Returns true if a register (identified by its address) is a known bootstrap register */ static int is_known_bootstrap_register(guint64 addr, u3v_conv_info_t * u3v_conv_info) { const gchar* address_string = NULL; guint32 offset_address; /* check if this is the access to one of the base address registers */ if ( addr < 0x10000 ) { offset_address = (guint32)addr; address_string = try_val_to_str(offset_address, bootstrap_register_names_abrm); } if ( u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) { offset_address = (guint32)( addr - u3v_conv_info->sbrm_addr); address_string = try_val_to_str(offset_address, bootstrap_register_names_sbrm); } if ( u3v_conv_info->sirm_addr != 0 && (addr >= u3v_conv_info->sirm_addr)) { offset_address = (guint32)( addr - u3v_conv_info->sirm_addr); address_string = try_val_to_str(offset_address, bootstrap_register_names_sirm); } if ( u3v_conv_info->eirm_addr != 0 && (addr >= u3v_conv_info->eirm_addr)) { offset_address = (guint32)( addr - u3v_conv_info->eirm_addr); address_string = try_val_to_str(offset_address, bootstrap_register_names_eirm); } return address_string != NULL; } /* \brief Identify Base Address Pointer */ static void dissect_u3v_register_bases(guint64 addr, tvbuff_t *tvb, gint offset, u3v_conv_info_t * u3v_conv_info) { if ( addr < 0x10000 ) { switch (addr) { case U3V_ABRM_SBRM_ADDRESS: u3v_conv_info->sbrm_addr = tvb_get_letoh64(tvb, offset); break; case U3V_ABRM_MANIFEST_TABLE_ADDRESS: u3v_conv_info->manifest_addr = tvb_get_letoh64(tvb, offset); break; } } if ( u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) { addr -= u3v_conv_info->sbrm_addr; switch(addr) { case U3V_SBRM_SIRM_ADDRESS: u3v_conv_info->sirm_addr = tvb_get_letoh64(tvb, offset); break; case U3V_SBRM_EIRM_ADDRESS: u3v_conv_info->eirm_addr = tvb_get_letoh64(tvb, offset); break; case U3V_SBRM_IIDC2_ADDRESS: u3v_conv_info->iidc2_addr = tvb_get_letoh64(tvb, offset); break; } } } /* \brief Attempt to dissect a bootstrap register */ static int dissect_u3v_register(guint64 addr, proto_tree *branch, tvbuff_t *tvb, gint offset, gint length, u3v_conv_info_t * u3v_conv_info) { gint isABRM = FALSE, isSBRM = FALSE, isSIRM = FALSE,isEIRM = FALSE; /* check if this is the access to one of the base address registers */ if ( addr < 0x10000 ) { isABRM = TRUE; switch (addr) { case U3V_ABRM_GENCP_VERSION: proto_tree_add_item(branch, hf_u3v_bootstrap_GenCP_Version, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_MANUFACTURER_NAME: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_Manufacturer_Name, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_MODEL_NAME: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_Model_Name, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_FAMILY_NAME: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_Family_Name, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_DEVICE_VERSION: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_Device_Version, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_MANUFACTURER_INFO: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_Manufacturer_Info, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_SERIAL_NUMBER: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_Serial_Number, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_USER_DEFINED_NAME: if ( length <= 64 ) { proto_tree_add_item(branch, hf_u3v_bootstrap_User_Defined_Name, tvb, offset, length, ENC_ASCII|ENC_NA); } break; case U3V_ABRM_DEVICE_CAPABILITY: proto_tree_add_item(branch, hf_u3v_bootstrap_Device_Capability, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_MAXIMUM_DEVICE_RESPONSE_TIME: proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Device_Response_Time, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_MANIFEST_TABLE_ADDRESS: proto_tree_add_item(branch, hf_u3v_bootstrap_Manifest_Table_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_SBRM_ADDRESS: proto_tree_add_item(branch, hf_u3v_bootstrap_SBRM_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_DEVICE_CONFIGURATION: proto_tree_add_item(branch, hf_u3v_bootstrap_Device_Configuration, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_HEARTBEAT_TIMEOUT: proto_tree_add_item(branch, hf_u3v_bootstrap_Heartbeat_Timeout, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_MESSAGE_CHANNEL_CHANNEL_ID: proto_tree_add_item(branch, hf_u3v_bootstrap_Message_Channel_channel_id, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_TIMESTAMP: proto_tree_add_item(branch, hf_u3v_bootstrap_Timestamp, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_TIMESTAMP_LATCH: proto_tree_add_item(branch, hf_u3v_bootstrap_Timestamp_Latch, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_TIMESTAMP_INCREMENT: proto_tree_add_item(branch, hf_u3v_bootstrap_Timestamp_Increment, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_ACCESS_PRIVILEGE: proto_tree_add_item(branch, hf_u3v_bootstrap_Access_Privilege, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_PROTOCOL_ENDIANESS: proto_tree_add_item(branch, hf_u3v_bootstrap_Protocol_Endianess, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_ABRM_IMPLEMENTATION_ENDIANESS: proto_tree_add_item(branch, hf_u3v_bootstrap_Implementation_Endianess, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; default: isABRM = FALSE; break; } } if ( u3v_conv_info->sbrm_addr != 0 && (addr >= u3v_conv_info->sbrm_addr)) { guint64 map_offset = addr - u3v_conv_info->sbrm_addr; isSBRM = TRUE; switch(map_offset) { case U3V_SBRM_U3V_VERSION: proto_tree_add_item(branch, hf_u3v_bootstrap_U3V_Version, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_U3VCP_CAPABILITY_REGISTER: proto_tree_add_item(branch, hf_u3v_bootstrap_U3VCP_Capability_Register, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_U3VCP_CONFIGURATION_REGISTER: proto_tree_add_item(branch, hf_u3v_bootstrap_U3VCP_Configuration_Register, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_MAXIMUM_COMMAND_TRANSFER_LENGTH: proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Command_Transfer_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_MAXIMUM_ACKNOWLEDGE_TRANSFER_LENGTH: proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Acknowledge_Transfer_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_NUMBER_OF_STREAM_CHANNELS: proto_tree_add_item(branch, hf_u3v_bootstrap_Number_of_Stream_Channels, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_SIRM_ADDRESS: proto_tree_add_item(branch, hf_u3v_bootstrap_SIRM_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_SIRM_LENGTH: proto_tree_add_item(branch, hf_u3v_bootstrap_SIRM_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_EIRM_ADDRESS: proto_tree_add_item(branch, hf_u3v_bootstrap_EIRM_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_EIRM_LENGTH: proto_tree_add_item(branch, hf_u3v_bootstrap_EIRM_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_IIDC2_ADDRESS: proto_tree_add_item(branch, hf_u3v_bootstrap_IIDC2_Address, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_SBRM_CURRENT_SPEED: proto_tree_add_item(branch, hf_u3v_bootstrap_Current_Speed, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; default: isSBRM = FALSE; break; } } if ( u3v_conv_info->sirm_addr != 0 && (addr >= u3v_conv_info->sirm_addr)) { guint64 map_offset = addr - u3v_conv_info->sirm_addr; isSIRM = TRUE; switch(map_offset) { case U3V_SIRM_SI_INFO: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Info, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_CONTROL: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Control, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_REQUIRED_PAYLOAD_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Required_Payload_Size, tvb, offset, 8, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_REQUIRED_LEADER_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Required_Leader_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_REQUIRED_TRAILER_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Required_Trailer_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_MAXIMUM_LEADER_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Maximum_Leader_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_PAYLOAD_TRANSFER_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Transfer_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_PAYLOAD_TRANSFER_COUNT: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Transfer_Count, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER1_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Final_Transfer1_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_PAYLOAD_FINAL_TRANSFER2_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Payload_Final_Transfer2_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_SIRM_SI_MAXIMUM_TRAILER_SIZE: proto_tree_add_item(branch, hf_u3v_bootstrap_SI_Maximum_Trailer_Size, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; default: isSIRM = FALSE; break; } } if ( u3v_conv_info->eirm_addr != 0 && (addr >= u3v_conv_info->eirm_addr)) { guint64 map_offset = addr -u3v_conv_info->eirm_addr; isEIRM=TRUE; switch(map_offset) { case U3V_EIRM_EI_CONTROL: proto_tree_add_item(branch, hf_u3v_bootstrap_EI_Control, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_EIRM_MAXIMUM_EVENT_TRANSFER_LENGTH: proto_tree_add_item(branch, hf_u3v_bootstrap_Maximum_Event_Transfer_Length, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; case U3V_EIRM_EVENT_TEST_CONTROL: proto_tree_add_item(branch, hf_u3v_bootstrap_Event_Test_Control, tvb, offset, 4, ENC_LITTLE_ENDIAN); break; default: isEIRM = FALSE; break; } } if(isABRM || isSBRM || isSIRM || isEIRM ) { return 1; } return 0; } /* \brief DISSECT: Read memory command */ static void dissect_u3v_read_mem_cmd(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info, gencp_transaction_t * gencp_trans) { guint64 addr = 0; const gchar* address_string = NULL; gboolean is_custom_register = FALSE; guint16 count = 0; gint offset = startoffset; proto_item *item = NULL; addr = tvb_get_letoh64(tvb, offset); gencp_trans->address = addr; address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info); count = tvb_get_letohs(tvb, offset + 10); /* Number of bytes to read from memory */ gencp_trans->count = count; if ( 0xffffffff00000000 & addr ) { col_append_fstr(pinfo->cinfo, COL_INFO, " (0x%016" G_GINT64_MODIFIER "X (%d) bytes) %s", addr, count, address_string); } else { col_append_fstr(pinfo->cinfo, COL_INFO, " (0x%08X (%d) bytes)", (guint32)addr, count); } item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_readmem_cmd, tvb, offset, length, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd); /* address */ if (is_known_bootstrap_register(addr, u3v_conv_info)) { item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, offset, 8, addr); proto_item_append_text(item, " %s", address_string); } else { proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_addr, tvb, offset, 8, ENC_LITTLE_ENDIAN); } offset += 8; /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA); offset += 2; /* count */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_count, tvb, offset, 2, ENC_LITTLE_ENDIAN); } /* \brief DISSECT: Write memory command */ static void dissect_u3v_write_mem_cmd(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info, gencp_transaction_t *gencp_trans) { const gchar* address_string = NULL; gboolean is_custom_register = FALSE; guint64 addr = 0; guint byte_count = 0; proto_item *item = NULL; guint offset = startoffset + 8; addr = tvb_get_letoh64(tvb, startoffset); byte_count = length - 8; address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info); gencp_trans->address = addr; gencp_trans->count = byte_count; /* fill in Info column in Wireshark GUI */ col_append_fstr(pinfo->cinfo, COL_INFO, "%s: %d bytes", address_string, byte_count); /* Subtree initialization for Payload Data: WRITEMEM_CMD */ item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_writemem_cmd, tvb, startoffset, length, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd); if (is_known_bootstrap_register(addr, u3v_conv_info)) { item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, startoffset, 8, addr); proto_item_append_text(item, " %s", address_string); dissect_u3v_register(addr, u3v_telegram_tree, tvb, offset, byte_count, u3v_conv_info); } else { proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_addr, tvb, startoffset, 8, ENC_LITTLE_ENDIAN); proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_data, tvb, startoffset + 8, byte_count, ENC_NA); } } /* * \brief DISSECT: Event command */ static void dissect_u3v_event_cmd(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length) { gint32 eventid; gint offset = startoffset; proto_item *item = NULL; /* Get event ID */ eventid = tvb_get_letohs(tvb, offset + 2); /* fill in Info column in Wireshark GUI */ col_append_fstr(pinfo->cinfo, COL_INFO, "[ID: 0x%04X]", eventid); item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_event_cmd, tvb, offset, length, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd); offset += 2; /* Use range to determine type of event */ if ((eventid >= 0x0000) && (eventid <= 0x8000)) { /* Standard ID */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_id, tvb, offset, 2, ENC_LITTLE_ENDIAN); } else if ((eventid >= 0x8001) && (eventid <= 0x8FFF)) { /* Error */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_error_id, tvb, offset, 2, ENC_LITTLE_ENDIAN); } else if ((eventid >= 0x9000) && (eventid <= 0xFFFF)) { /* Device specific */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_device_specific_id, tvb, offset, 2, ENC_LITTLE_ENDIAN); } offset += 2; /* Timestamp (64 bit) associated with event */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_timestamp, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; /* Data */ if (length > offset ) { proto_tree_add_item(u3v_telegram_tree, hf_u3v_eventcmd_data, tvb, offset, length - 12, ENC_NA); } } /* \brief DISSECT: Read memory acknowledge */ static void dissect_u3v_read_mem_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info, gencp_transaction_t * gencp_trans) { guint64 addr = 0; const gchar *address_string = NULL; gboolean is_custom_register = FALSE; gboolean have_address = (0 != gencp_trans->cmd_frame); proto_item *item = NULL; guint offset = startoffset; guint byte_count = (length); addr = gencp_trans->address; dissect_u3v_register_bases(addr, tvb, startoffset, u3v_conv_info); if (have_address) { address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info); /* Fill in Wireshark GUI Info column */ col_append_fstr(pinfo->cinfo, COL_INFO, "%s", address_string); } /* Subtree initialization for Payload Data: READMEM_ACK */ item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_ack_readmem_ack, tvb, startoffset, length, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd); /* Bootstrap register known address */ if (have_address) { item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, 0,0 , addr); PROTO_ITEM_SET_GENERATED(item); if (is_known_bootstrap_register(addr, u3v_conv_info)) { dissect_u3v_register(addr, u3v_telegram_tree, tvb, offset, byte_count, u3v_conv_info); } else { proto_tree_add_item(u3v_telegram_tree, hf_u3v_custom_memory_data, tvb, startoffset, length, ENC_NA); } } } /* \brief DISSECT: Write memory acknowledge */ static void dissect_u3v_write_mem_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info , gencp_transaction_t * gencp_trans) { guint64 addr = 0; gint offset = startoffset; const gchar *address_string = NULL; gboolean is_custom_register = FALSE; gboolean have_address = (0 != gencp_trans->cmd_frame); proto_item *item = NULL; addr = gencp_trans->address; if (have_address) { address_string = get_register_name_from_address(addr, &is_custom_register, u3v_conv_info); /* Fill in Wireshark GUI Info column */ col_append_fstr(pinfo->cinfo, COL_INFO, "%s", address_string); } item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_scd_writemem_ack, tvb, startoffset, length, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd); if (have_address) { item = proto_tree_add_uint64(u3v_telegram_tree, hf_u3v_address, tvb, 0,0 , addr); PROTO_ITEM_SET_GENERATED(item); } /* Number of bytes successfully written to the device register map */ if ( length == 4 ) { /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA); offset += 2; proto_tree_add_item(u3v_telegram_tree, hf_u3v_count, tvb, offset, 2, ENC_LITTLE_ENDIAN); } } /* \brief DISSECT: Pending acknowledge */ static void dissect_u3v_pending_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo _U_, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info _U_, gencp_transaction_t *gencp_trans _U_) { proto_item *item = NULL; guint offset = startoffset; /* Fill in Wireshark GUI Info column */ col_append_fstr(pinfo->cinfo, COL_INFO, " %d ms", tvb_get_letohs(tvb, startoffset+2)); item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_ccd_pending_ack, tvb, startoffset, length, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd); /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA); offset += 2; proto_tree_add_item(u3v_telegram_tree, hf_u3v_time_to_completion, tvb, offset, 2, ENC_LITTLE_ENDIAN); } /* \brief DISSECT: Stream Leader */ static void dissect_u3v_stream_leader(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, usb_conv_info_t *usb_conv_info _U_) { guint32 offset = 0; guint32 payload_type = 0; guint64 block_id = 0; proto_item *item = NULL; /* Subtree initialization for Stream Leader */ item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_leader, tvb, 0, -1, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_stream_leader); /* Add the prefix code: */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA); offset += 2; /* leader size */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_leader_size, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; /* block id */ block_id = tvb_get_letoh64(tvb, offset); proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_block_id, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA); offset += 2; /* payload type */ payload_type = tvb_get_letohs(tvb, offset); proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_payload_type, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; /* Add payload type to information string */ col_append_fstr(pinfo->cinfo, COL_INFO, "Stream Leader [ Block ID: %" G_GINT64_MODIFIER "u , Type %s]", block_id, val_to_str(payload_type, payload_type_names, "Unknown Payload Type")); if (payload_type == U3V_STREAM_PAYLOAD_IMAGE || payload_type == U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK || payload_type == U3V_STREAM_PAYLOAD_CHUNK) { /* timestamp */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_timestamp, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; } if (payload_type == U3V_STREAM_PAYLOAD_IMAGE || payload_type == U3V_STREAM_PAYLOAD_IMAGE_EXT_CHUNK ) { /* pixel format */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_pixel_format, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* size_x */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_size_x, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* size_y */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_size_y, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* offset_x */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_offset_x, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* offset_x */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_offset_y, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* padding_x */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_padding_x, tvb, offset, 2, ENC_LITTLE_ENDIAN); /* offset += 2; */ /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA); /* offset += 2; */ } } /* \brief DISSECT: Stream Trailer */ static void dissect_u3v_stream_trailer(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, usb_conv_info_t *usb_conv_info _U_) { gint offset = 0; guint64 block_id; proto_item *item = NULL; /* Subtree initialization for Stream Leader */ item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_trailer, tvb, 0, -1, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_stream_trailer); /* Add the prefix code: */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA); offset += 2; /* trailer size */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_trailer_size, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; /* block id */ block_id = tvb_get_letoh64(tvb, offset); proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_block_id, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; /* status*/ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_status, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; /* reserved field */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_reserved, tvb, offset, 2, ENC_NA); offset += 2; /* block id */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_valid_payload_size, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; /* Add payload type to information string */ col_append_fstr(pinfo->cinfo, COL_INFO, "Stream Trailer [ Block ID: %" G_GINT64_MODIFIER "u]", block_id); if (tvb_captured_length_remaining(tvb,offset) >=4 ) { /* size_y */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_size_y, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; } if (tvb_captured_length_remaining(tvb,offset) >=4 ) { /* chunk layout id */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_chunk_layout_id, tvb, offset, 4, ENC_LITTLE_ENDIAN); /* offset += 4; */ } } /* \brief DISSECT: Stream Payload */ static void dissect_u3v_stream_payload(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo, usb_conv_info_t *usb_conv_info _U_) { proto_item *item = NULL; /* Subtree initialization for Stream Leader */ item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_payload, tvb, 0, -1, ENC_NA); u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_stream_payload); /* Data */ proto_tree_add_item(u3v_telegram_tree, hf_u3v_stream_data, tvb, 0, -1, ENC_NA); /* Add payload type to information string */ col_append_fstr(pinfo->cinfo, COL_INFO, "Stream Payload"); } /* \brief Point of entry of all U3V packet dissection */ static int dissect_u3v(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data) { gint offset = 0; proto_tree *u3v_tree = NULL, *ccd_tree_flag, *u3v_telegram_tree = NULL, *ccd_tree = NULL; gint data_length = 0; gint req_id = 0; gint command_id = -1; gint status = 0; guint prefix = 0; proto_item *ti = NULL; proto_item *item = NULL; const char *command_string; usb_conv_info_t *usb_conv_info; gint stream_detected = FALSE; gint control_detected = FALSE; u3v_conv_info_t *u3v_conv_info = NULL; gencp_transaction_t *gencp_trans = NULL; usb_conv_info = (usb_conv_info_t *)data; /* decide if this packet belongs to U3V protocol */ u3v_conv_info = (u3v_conv_info_t *)usb_conv_info->class_data; if (!u3v_conv_info) { u3v_conv_info = wmem_new0(wmem_file_scope(), u3v_conv_info_t); usb_conv_info->class_data = u3v_conv_info; } prefix = tvb_get_letohl(tvb, 0); if ((tvb_reported_length(tvb) >= 4) && ( ( U3V_CONTROL_PREFIX == prefix ) || ( U3V_EVENT_PREFIX == prefix ) ) ) { control_detected = TRUE; } if (((tvb_reported_length(tvb) >= 4) && (( U3V_STREAM_LEADER_PREFIX == prefix ) || ( U3V_STREAM_TRAILER_PREFIX == prefix ))) || (usb_conv_info->endpoint == u3v_conv_info->ep_stream)) { stream_detected = TRUE; } /* initialize interface class/subclass in case no descriptors have been dissected yet */ if ( control_detected || stream_detected){ if ( usb_conv_info->interfaceClass == IF_CLASS_UNKNOWN && usb_conv_info->interfaceSubclass == IF_SUBCLASS_UNKNOWN){ usb_conv_info->interfaceClass = IF_CLASS_MISCELLANEOUS; usb_conv_info->interfaceSubclass = IF_SUBCLASS_MISC_U3V; } } if ( control_detected ) { /* Set the protocol column */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "U3V"); /* Clear out stuff in the info column */ col_clear(pinfo->cinfo, COL_INFO); /* Adds "USB3Vision" heading to protocol tree */ /* We will add fields to this using the u3v_tree pointer */ ti = proto_tree_add_item(tree, proto_u3v, tvb, offset, -1, ENC_NA); u3v_tree = proto_item_add_subtree(ti, ett_u3v); prefix = tvb_get_letohl(tvb, offset); command_id = tvb_get_letohs(tvb, offset+6); /* decode CCD ( DCI/DCE command data layout) */ if ((prefix == U3V_CONTROL_PREFIX || prefix == U3V_EVENT_PREFIX) && ((command_id % 2) == 0)) { command_string = val_to_str(command_id,command_names,"Unknown Command (0x%x)"); item = proto_tree_add_item(u3v_tree, hf_u3v_ccd_cmd, tvb, offset, 8, ENC_NA); proto_item_append_text(item, ": %s", command_string); ccd_tree = proto_item_add_subtree(item, ett_u3v_cmd); /* Add the prefix code: */ proto_tree_add_item(ccd_tree, hf_u3v_gencp_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* Add the flags */ item = proto_tree_add_item(ccd_tree, hf_u3v_flag, tvb, offset, 2, ENC_LITTLE_ENDIAN); ccd_tree_flag = proto_item_add_subtree(item, ett_u3v_flags); proto_tree_add_item(ccd_tree_flag, hf_u3v_acknowledge_required_flag, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, "> %s ", command_string); } else if (prefix == U3V_CONTROL_PREFIX && ((command_id % 2) == 1)) { command_string = val_to_str(command_id,command_names,"Unknown Acknowledge (0x%x)"); item = proto_tree_add_item(u3v_tree, hf_u3v_ccd_ack, tvb, offset, 8, ENC_NA); proto_item_append_text(item, ": %s", command_string); ccd_tree = proto_item_add_subtree(item, ett_u3v_ack); /* Add the prefix code: */ proto_tree_add_item(ccd_tree, hf_u3v_gencp_prefix, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* Add the status: */ proto_tree_add_item(ccd_tree, hf_u3v_status, tvb, offset, 2,ENC_LITTLE_ENDIAN); status = tvb_get_letohs(tvb, offset); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, "< %s %s", command_string, val_to_str(status, status_names_short, "Unknown status (0x%04X)")); } else { return 0; } /* Add the command id*/ proto_tree_add_item(ccd_tree, hf_u3v_command_id, tvb, offset, 2,ENC_LITTLE_ENDIAN); offset += 2; /* Parse the second part of both the command and the acknowledge header: 0 15 16 31 -------- -------- -------- -------- | status | acknowledge | -------- -------- -------- -------- | length | req_id | -------- -------- -------- -------- Add the data length Number of valid data bytes in this message, not including this header. This represents the number of bytes of payload appended after this header */ proto_tree_add_item(ccd_tree, hf_u3v_length, tvb, offset, 2, ENC_LITTLE_ENDIAN); data_length = tvb_get_letohs(tvb, offset); offset += 2; /* Add the request ID */ proto_tree_add_item(ccd_tree, hf_u3v_request_id, tvb, offset, 2, ENC_LITTLE_ENDIAN); req_id = tvb_get_letohs(tvb, offset); offset += 2; /* Add telegram subtree */ u3v_telegram_tree = proto_item_add_subtree(u3v_tree, ett_u3v); if (!PINFO_FD_VISITED(pinfo)) { if ((command_id % 2) == 0) { /* This is a command */ gencp_trans = wmem_new(wmem_file_scope(), gencp_transaction_t); gencp_trans->cmd_frame = pinfo->fd->num; gencp_trans->ack_frame = 0; gencp_trans->cmd_time = pinfo->fd->abs_ts; /* add reference to current packet */ p_add_proto_data(wmem_file_scope(), pinfo, proto_u3v, req_id, gencp_trans); /* add reference to current */ u3v_conv_info->trans_info = gencp_trans; } else { gencp_trans = u3v_conv_info->trans_info; if (gencp_trans) { gencp_trans->ack_frame = pinfo->fd->num; /* add reference to current packet */ p_add_proto_data(wmem_file_scope(), pinfo, proto_u3v, req_id, gencp_trans); } } } else { gencp_trans = (gencp_transaction_t*)p_get_proto_data(wmem_file_scope(),pinfo, proto_u3v, req_id); } if (!gencp_trans) { /* create a "fake" gencp_trans structure */ gencp_trans = wmem_new(wmem_packet_scope(), gencp_transaction_t); gencp_trans->cmd_frame = 0; gencp_trans->ack_frame = 0; gencp_trans->cmd_time = pinfo->fd->abs_ts; } /* dissect depending on command? */ switch (command_id) { case U3V_READMEM_CMD: dissect_u3v_read_mem_cmd(u3v_telegram_tree, tvb, pinfo, offset, data_length,u3v_conv_info,gencp_trans); break; case U3V_WRITEMEM_CMD: dissect_u3v_write_mem_cmd(u3v_telegram_tree, tvb, pinfo, offset, data_length,u3v_conv_info,gencp_trans); break; case U3V_EVENT_CMD: dissect_u3v_event_cmd(u3v_telegram_tree, tvb, pinfo, offset, data_length); break; case U3V_READMEM_ACK: if ( U3V_STATUS_GENCP_SUCCESS == status ) { dissect_u3v_read_mem_ack(u3v_telegram_tree, tvb, pinfo, offset, data_length,u3v_conv_info,gencp_trans); } break; case U3V_WRITEMEM_ACK: dissect_u3v_write_mem_ack(u3v_telegram_tree, tvb, pinfo, offset, data_length, u3v_conv_info,gencp_trans); break; case U3V_PENDING_ACK: dissect_u3v_pending_ack(u3v_telegram_tree, tvb, pinfo, offset, data_length, u3v_conv_info,gencp_trans); break; default: proto_tree_add_item(u3v_telegram_tree, hf_u3v_payloaddata, tvb, offset, data_length, ENC_NA); break; } return data_length + 12; } else if ( stream_detected ) { /* this is streaming data */ /* init this stream configuration */ u3v_conv_info = (u3v_conv_info_t *)usb_conv_info->class_data; u3v_conv_info->ep_stream = usb_conv_info->endpoint; /* Set the protocol column */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "U3V"); /* Clear out stuff in the info column */ col_clear(pinfo->cinfo, COL_INFO); /* Adds "USB3Vision" heading to protocol tree */ /* We will add fields to this using the u3v_tree pointer */ ti = proto_tree_add_item(tree, proto_u3v, tvb, offset, -1, ENC_NA); u3v_tree = proto_item_add_subtree(ti, ett_u3v); if(tvb_captured_length(tvb) >=4) { prefix = tvb_get_letohl(tvb, offset); switch (prefix) { case U3V_STREAM_LEADER_PREFIX: dissect_u3v_stream_leader(u3v_tree, tvb, pinfo, usb_conv_info); break; case U3V_STREAM_TRAILER_PREFIX: dissect_u3v_stream_trailer(u3v_tree, tvb, pinfo, usb_conv_info); break; default: dissect_u3v_stream_payload(u3v_tree, tvb, pinfo, usb_conv_info); break; } } return tvb_captured_length(tvb); } return 0; } static gboolean dissect_u3v_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data) { guint32 prefix; usb_conv_info_t *usb_conv_info; /* all control and meta data packets of U3V contain at least the prefix */ if (tvb_reported_length(tvb) < 4) return FALSE; prefix = tvb_get_letohl(tvb, 0); /* check if stream endpoint has been already set up for this conversation */ usb_conv_info = (usb_conv_info_t *)data; if (!usb_conv_info) return FALSE; /* either right prefix or the endpoint of the interface descriptor set the correct class and subclass */ if ((U3V_STREAM_LEADER_PREFIX == prefix) || (U3V_STREAM_TRAILER_PREFIX == prefix) || (U3V_CONTROL_PREFIX == prefix) || (U3V_EVENT_PREFIX == prefix) || ((usb_conv_info->interfaceClass == IF_CLASS_MISCELLANEOUS && usb_conv_info->interfaceSubclass == IF_SUBCLASS_MISC_U3V))) { dissect_u3v(tvb, pinfo, tree, data); return TRUE; } return FALSE; } static gint dissect_u3v_descriptors(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, void *data _U_) { guint8 type; gint offset = 0; proto_item * ti; proto_tree * sub_tree; guint32 version; /* The descriptor must at least have a length and type field. */ if (tvb_reported_length(tvb) < 2) { return 0; } /* skip len */ type = tvb_get_guint8(tvb, 1); /* Check for U3V device info descriptor. */ if (type != DESCRIPTOR_TYPE_U3V_INTERFACE) { return 0; } ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor, tvb, offset, -1, ENC_NA); tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor); /* bLength */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bLength, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* bDescriptorType */ ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorType, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_item_append_text(ti, " (U3V INTERFACE)"); offset++; /* bDescriptorSubtype */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorSubtype, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* bGenCPVersion */ if (!tvb_bytes_exist(tvb, offset, 4)) { /* Version not completely in buffer -> break dissection here. */ return offset; } version = tvb_get_letohl(tvb, offset); ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bGenCPVersion, tvb, offset, 4, ENC_NA); proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF); sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_gencp_version); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* bU3VVersion */ if (!tvb_bytes_exist(tvb, offset, 4)) { /* Version not completely in buffer -> break dissection here. */ return offset; } version = tvb_get_letohl(tvb, offset); ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bU3VVersion, tvb, offset, 4, ENC_NA); proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF); sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_u3v_version); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* iDeviceGUID */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceGUID, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iVendorName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iVendorName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iModelName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iModelName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iFamilyName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iFamilyName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iDeviceVersion */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceVersion, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iManufacturerInfo */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iManufacturerInfo, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iSerialNumber */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iSerialNumber, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iUserDefinedName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iUserDefinedName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* bmSpeedSupport */ proto_tree_add_bitmask(tree, tvb, offset, hf_u3v_device_info_descriptor_bmSpeedSupport, ett_u3v_device_info_descriptor_speed_support, speed_support_fields, ENC_LITTLE_ENDIAN); offset++; return offset; } /* \brief Structures for register dissection */ static hf_register_info hf[] = { /* Common U3V data */ { &hf_u3v_gencp_prefix, { "Prefix", "u3v.gencp.prefix", FT_UINT8, BASE_HEX, NULL, 0x0, "U3V GenCP Prefix", HFILL } }, { &hf_u3v_flag, { "Flags", "u3v.gencp.flags", FT_UINT16, BASE_HEX, NULL, 0x0, "U3V Flags", HFILL } }, { &hf_u3v_acknowledge_required_flag, { "Acknowledge Required", "u3v.gencp.flag.acq_required", FT_BOOLEAN, 16, NULL, 0x4000, "U3V Acknowledge Required", HFILL } }, { &hf_u3v_command_id, { "Command", "u3v.gencp.command_id", FT_UINT16, BASE_HEX, VALS( command_names ), 0x0, "U3V Command", HFILL } }, { &hf_u3v_length, { "Payload Length", "u3v.gencp.payloadlength", FT_UINT16, BASE_HEX_DEC, NULL, 0x0, "U3V Payload Length", HFILL } }, { &hf_u3v_request_id, { "Request ID", "u3v.gencp.req_id", FT_UINT16, BASE_HEX, NULL, 0x0, "U3V Request ID", HFILL } }, { &hf_u3v_payloaddata, { "Payload Data", "u3v.gencp.payloaddata", FT_BYTES, BASE_NONE, NULL, 0x0, "U3V Payload", HFILL } }, { &hf_u3v_status, { "Status", "u3v.gencp.status", FT_UINT16, BASE_HEX, VALS( status_names ), 0x0, "U3V Status", HFILL } }, /* Read memory */ { &hf_u3v_address, { "Address", "u3v.gencp.address", FT_UINT64, BASE_HEX, NULL, 0x0, "U3V Address", HFILL } }, { &hf_u3v_count, { "Count", "u3v.gencp.count", FT_UINT16, BASE_HEX_DEC, NULL, 0x0, "U3V Count", HFILL } }, /* Event */ { &hf_u3v_eventcmd_id, { "ID", "u3v.cmd.event.id", FT_UINT16, BASE_HEX_DEC, VALS( event_id_names ), 0x0, "U3V Event ID", HFILL } }, { &hf_u3v_eventcmd_error_id, { "Error ID", "u3v.cmd.event.errorid", FT_UINT16, BASE_HEX_DEC, NULL, 0x0, "U3V Event Error ID", HFILL } }, { &hf_u3v_eventcmd_device_specific_id, { "Device Specific ID", "u3v.cmd.event.devicespecificid", FT_UINT16, BASE_HEX_DEC, NULL, 0x0, "U3V Event Device Specific ID", HFILL } }, { &hf_u3v_eventcmd_timestamp, { "Timestamp", "u3v.cmd.event.timestamp", FT_UINT64, BASE_HEX_DEC, NULL, 0x0, "U3V Event Timestamp", HFILL } }, { &hf_u3v_eventcmd_data, { "Data", "u3v.cmd.event.data", FT_BYTES, BASE_NONE, NULL, 0x0, "U3V Event Data", HFILL } }, /* Pending acknowledge */ { &hf_u3v_time_to_completion, { "Time to completion", "u3v.gencp.timetocompletion", FT_UINT16, BASE_DEC, NULL, 0x0, "U3V Time to completion [ms]", HFILL } }, { &hf_u3v_reserved, { "Reserved", "u3v.reserved", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, /* Custom */ { &hf_u3v_custom_memory_addr, { "Custom Memory Address", "u3v.gencp.custom_addr", FT_UINT64, BASE_HEX, NULL, 0x0, "U3V Custom Memory Address", HFILL } }, { &hf_u3v_custom_memory_data, { "Custom Memory Data", "u3v.gencp.custom_data", FT_BYTES, BASE_NONE, NULL, 0x0, "U3V Custom Memory Data", HFILL } }, /* Bootstrap Defines */ { &hf_u3v_bootstrap_GenCP_Version, { "GenCP Version", "u3v.bootstrap.GenCP_Version", FT_UINT32, BASE_DEC, NULL, 0x0, "Complying GenCP Version", HFILL } }, { &hf_u3v_bootstrap_Manufacturer_Name, { "Manufacturer Name", "u3v.bootstrap.Manufacturer_Name", FT_STRING, BASE_NONE, NULL, 0x0, "String containing the self-describing name of the manufacturer", HFILL } }, { &hf_u3v_bootstrap_Model_Name, { "Model Name", "u3v.bootstrap.Model_Name", FT_STRING, BASE_NONE, NULL, 0x0, "String containing the self-describing name of the device model", HFILL } }, { &hf_u3v_bootstrap_Family_Name, { "Family Name", "u3v.bootstrap.Family_Name", FT_STRING, BASE_NONE, NULL, 0x0, "String containing the name of the family of this device", HFILL } }, { &hf_u3v_bootstrap_Device_Version, { "Device Version", "u3v.bootstrap.Device_Version", FT_STRING, BASE_NONE, NULL, 0x0, "String containing the version of this device", HFILL } }, { &hf_u3v_bootstrap_Manufacturer_Info, { "Manufacturer Information", "u3v.bootstrap.Manufacturer_Info", FT_STRING, BASE_NONE, NULL, 0x0, "String containing additional manufacturer information", HFILL } }, { &hf_u3v_bootstrap_Serial_Number, { "Serial Number", "u3v.bootstrap.Serial_Number", FT_STRING, BASE_NONE, NULL, 0x0, "String containing the serial number of the device", HFILL } }, { &hf_u3v_bootstrap_User_Defined_Name, { "User Defined Name", "u3v.bootstrap.User_Defined_Name", FT_STRING, BASE_NONE, NULL, 0x0, "String containing the user defined name of the device", HFILL } }, { &hf_u3v_bootstrap_Device_Capability, { "Device Capabilities", "u3v.bootstrap.Device_Capability", FT_UINT64, BASE_DEC, NULL, 0x0, "Bit field describing the device?s capabilities", HFILL } }, { &hf_u3v_bootstrap_Maximum_Device_Response_Time, { "Device Maximum response time in ms", "u3v.bootstrap.Maximum_Device_Response_Time", FT_UINT32, BASE_DEC, NULL, 0x0, "Maximum response time in ms", HFILL } }, { &hf_u3v_bootstrap_Manifest_Table_Address, { "Pointer to the Manifest Table", "u3v.bootstrap.Manifest_Table_Address", FT_UINT64, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_bootstrap_SBRM_Address, { "Pointer to the SBRM", "u3v.bootstrap.SBRM_Address", FT_UINT64, BASE_HEX, NULL, 0x0, "Pointer to the Technology Specific Bootstrap Register Map", HFILL } }, { &hf_u3v_bootstrap_Device_Configuration, { "Device Configuration", "u3v.bootstrap.Device_Configuration", FT_UINT64, BASE_DEC, NULL, 0x0, "Bit field describing the device?s configuration", HFILL } }, { &hf_u3v_bootstrap_Heartbeat_Timeout, { "Heartbeat Timeout in ms.", "u3v.bootstrap.Heartbeat_Timeout", FT_UINT32, BASE_DEC, NULL, 0x0, "Heartbeat Timeout in ms. Not used for these specification.", HFILL } }, { &hf_u3v_bootstrap_Message_Channel_channel_id, { "Message channel id", "u3v.bootstrap.Message_Channel_channel_id", FT_UINT32, BASE_DEC, NULL, 0x0, "channel_id use for the message channel", HFILL } }, { &hf_u3v_bootstrap_Timestamp, { "Timestamp", "u3v.bootstrap.Timestamp", FT_UINT64, BASE_DEC, NULL, 0x0, "Current device time in ns", HFILL } }, { &hf_u3v_bootstrap_Timestamp_Latch, { "Latch Timestamp", "u3v.bootstrap.Timestamp_Latch", FT_UINT32, BASE_DEC, NULL, 0x0, "Timestamp Latch", HFILL } }, { &hf_u3v_bootstrap_Timestamp_Increment, { "Timestamp Increment Value", "u3v.bootstrap.Timestamp_Increment", FT_UINT64, BASE_DEC, NULL, 0x0, "Timestamp Increment", HFILL } }, { &hf_u3v_bootstrap_Access_Privilege, { "Access Privilege.", "u3v.bootstrap.Access_Privilege", FT_UINT32, BASE_DEC, NULL, 0x0, "Access Privilege. Not used for these specification.", HFILL } }, { &hf_u3v_bootstrap_Protocol_Endianess, { "Protocol Endianess", "u3v.bootstrap.Protocol_Endianess", FT_UINT32, BASE_DEC, NULL, 0x0, "Endianess of protocol fields and bootstrap registers. Only little endian is supported by these specification.", HFILL } }, { &hf_u3v_bootstrap_Implementation_Endianess, { "Device Endianess", "u3v.bootstrap.Implementation_Endianess", FT_UINT32, BASE_DEC, NULL, 0x0, "Endianess of device implementation registers. Only little endian is supported by these specification.", HFILL } }, { &hf_u3v_bootstrap_U3V_Version, { "TL Version", "u3v.bootstrap.U3V_Version", FT_UINT32, BASE_DEC, NULL, 0x0, "Version of the TL specification", HFILL } }, { &hf_u3v_bootstrap_U3VCP_Capability_Register, { "Control channel capabilities", "u3v.bootstrap.U3VCP_Capability_Register", FT_UINT64, BASE_DEC, NULL, 0x0, "Indicates additional features on the control channel", HFILL } }, { &hf_u3v_bootstrap_U3VCP_Configuration_Register, { "Control channel configuration", "u3v.bootstrap.U3VCP_Configuration_Register", FT_UINT64, BASE_DEC, NULL, 0x0, "Configures additional features on the control channel", HFILL } }, { &hf_u3v_bootstrap_Maximum_Command_Transfer_Length, { "Maximum Command Transfer Length", "u3v.bootstrap.Maximum_Command_Transfer_Length", FT_UINT32, BASE_DEC, NULL, 0x0, "Specifies the maximum supported command transfer length of the device", HFILL } }, { &hf_u3v_bootstrap_Maximum_Acknowledge_Transfer_Length, { "Maximum Acknowledge Transfer Length", "u3v.bootstrap.Maximum_Acknowledge_Transfer_Length", FT_UINT32, BASE_DEC, NULL, 0x0, "Specifies the maximum supported acknowledge transfer length of the device", HFILL } }, { &hf_u3v_bootstrap_Number_of_Stream_Channels, { "Number of Stream Channels", "u3v.bootstrap.Number_of_Stream_Channels", FT_UINT32, BASE_DEC, NULL, 0x0, "Number of Stream Channels and its corresponding Streaming Interface Register Maps (SIRM)", HFILL } }, { &hf_u3v_bootstrap_SIRM_Address, { "Pointer to the first SIRM", "u3v.bootstrap.SIRM_Address", FT_UINT64, BASE_HEX, NULL, 0x0, "Pointer to the first Streaming Interface Register Map.", HFILL } }, { &hf_u3v_bootstrap_SIRM_Length, { "Length of SIRM", "u3v.bootstrap.SIRM_Length", FT_UINT32, BASE_HEX, NULL, 0x0, "Specifies the length of each SIRM", HFILL } }, { &hf_u3v_bootstrap_EIRM_Address, { "Pointer to the EIRM", "u3v.bootstrap.EIRM_Address", FT_UINT64, BASE_HEX, NULL, 0x0, "Pointer to the Event Interface Register Map.", HFILL } }, { &hf_u3v_bootstrap_EIRM_Length, { "Length of EIRM", "u3v.bootstrap.EIRM_Length", FT_UINT32, BASE_DEC, NULL, 0x0, "Specifies the length of the EIRM", HFILL } }, { &hf_u3v_bootstrap_IIDC2_Address, { "Pointer to the IIDC2", "u3v.bootstrap.IIDC2_Address", FT_UINT64, BASE_HEX, NULL, 0x0, "Pointer to the IIDC2 register set.", HFILL } }, { &hf_u3v_bootstrap_Current_Speed, { "LinkSpeed", "u3v.bootstrap.Current_Speed", FT_UINT32, BASE_DEC, NULL, 0x0, "Specifies the current speed of the USB link.", HFILL } }, { &hf_u3v_bootstrap_SI_Info, { "Stream Info", "u3v.bootstrap.SI_Info", FT_UINT32, BASE_DEC, NULL, 0x0, "Device reports information about stream interface", HFILL } }, { &hf_u3v_bootstrap_SI_Control, { "Stream Control", "u3v.bootstrap.SI_Control", FT_UINT32, BASE_DEC, NULL, 0x0, "Stream interface Operation Control", HFILL } }, { &hf_u3v_bootstrap_SI_Required_Payload_Size, { "Stream Max Required Payload Size", "u3v.bootstrap.SI_Required_Payload_Size", FT_UINT64, BASE_DEC, NULL, 0x0, "Device reports maximum payload size with current settings", HFILL } }, { &hf_u3v_bootstrap_SI_Required_Leader_Size, { "Stream Max Required Leader Size", "u3v.bootstrap.SI_Required_Leader_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Device reports maximum leader size it will use", HFILL } }, { &hf_u3v_bootstrap_SI_Required_Trailer_Size, { "Stream Max Required Trailer Size", "u3v.bootstrap.SI_Required_Trailer_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Device reports maximum trailer size it will use", HFILL } }, { &hf_u3v_bootstrap_SI_Maximum_Leader_Size, { "Stream Max leader size", "u3v.bootstrap.SI_Maximum_Leader_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Maximum leader size", HFILL } }, { &hf_u3v_bootstrap_SI_Payload_Transfer_Size, { "Stream transfer size", "u3v.bootstrap.SI_Payload_Transfer_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Expected Size of a single Payload Transfer", HFILL } }, { &hf_u3v_bootstrap_SI_Payload_Transfer_Count, { "Stream transfer count", "u3v.bootstrap.SI_Payload_Transfer_Count", FT_UINT32, BASE_DEC, NULL, 0x0, "Expected Number of Payload Transfers", HFILL } }, { &hf_u3v_bootstrap_SI_Payload_Final_Transfer1_Size, { "Stream final transfer 1 size", "u3v.bootstrap.SI_Payload_Final_Transfer1_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Size of first final Payload transfer", HFILL } }, { &hf_u3v_bootstrap_SI_Payload_Final_Transfer2_Size, { "Stream final transfer 2 size", "u3v.bootstrap.SI_Payload_Final_Transfer2_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Size of second final Payload transfer", HFILL } }, { &hf_u3v_bootstrap_SI_Maximum_Trailer_Size, { "Stream Max trailer size", "u3v.bootstrap.SI_Maximum_Trailer_Size", FT_UINT32, BASE_DEC, NULL, 0x0, "Maximum trailer size", HFILL } }, { &hf_u3v_bootstrap_EI_Control, { "Event Interface Control", "u3v.bootstrap.EI_Control", FT_UINT32, BASE_DEC, NULL, 0x0, "Event Interface Control Register", HFILL } }, { &hf_u3v_bootstrap_Maximum_Event_Transfer_Length, { "Event max Transfer size", "u3v.bootstrap.Maximum_Event_Transfer_Length", FT_UINT32, BASE_DEC, NULL, 0x0, "Specifies the maximum supported event command transfer length of the device.", HFILL } }, { &hf_u3v_bootstrap_Event_Test_Control, { "Event test event control", "u3v.bootstrap.Event_Test_Control", FT_UINT32, BASE_DEC, NULL, 0x0, "Control the generation of test events.", HFILL } }, { &hf_u3v_stream_prefix, { "Stream Prefix", "u3v.stream.prefix", FT_UINT32, BASE_HEX, NULL, 0, "U3V stream prefix", HFILL } }, { &hf_u3v_stream_reserved, { "Reserved", "u3v.stream.reserved", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_u3v_stream_leader_size, { "Leader Size", "u3v.stream.leader_size", FT_UINT16, BASE_DEC, NULL, 0x0, "U3V stream leader size", HFILL } }, { &hf_u3v_stream_trailer_size, { "Trailer Size", "u3v.stream.trailer_size", FT_UINT16, BASE_DEC, NULL, 0x0, "U3V stream trailer size", HFILL } }, { &hf_u3v_stream_block_id, { "Block ID", "u3v.stream.block_id", FT_UINT64, BASE_DEC, NULL, 0x0, "U3V stream block id", HFILL } }, { &hf_u3v_stream_payload_type, { "Payload Type", "u3v.stream.payload_type", FT_UINT16, BASE_HEX, VALS( payload_type_names ), 0x0, "U3V Payload Type", HFILL } }, { &hf_u3v_stream_timestamp, { "Timestamp", "u3v.stream.timestamp", FT_UINT64, BASE_HEX_DEC, NULL, 0x0, "U3V Stream Timestamp", HFILL } }, { &hf_u3v_stream_pixel_format, { "Pixel Format", "u3v.stream.pixel_format", FT_UINT32, BASE_HEX|BASE_EXT_STRING, VALS_EXT_PTR( &pixel_format_names_ext ), 0x0, "U3V Stream Pixel Format", HFILL } }, { &hf_u3v_stream_size_x, { "Size X", "u3v.stream.sizex", FT_UINT32, BASE_DEC, NULL, 0x0, "U3V Stream Size X", HFILL } }, { &hf_u3v_stream_size_y, { "Size Y", "u3v.stream.sizey", FT_UINT32, BASE_DEC, NULL, 0x0, "U3V Stream Size Y", HFILL } }, { &hf_u3v_stream_offset_x, { "Offset X", "u3v.stream.offsetx", FT_UINT32, BASE_DEC, NULL, 0x0, "U3V Stream Offset X", HFILL } }, { &hf_u3v_stream_offset_y, { "Offset Y", "u3v.stream.offsety", FT_UINT32, BASE_DEC, NULL, 0x0, "U3V Stream Offset Y", HFILL } }, { &hf_u3v_stream_padding_x, { "Padding X", "u3v.stream.paddingx", FT_UINT16, BASE_DEC, NULL, 0x0, "U3V Stream Padding X", HFILL } }, { &hf_u3v_stream_chunk_layout_id, { "Chunk Layout ID", "u3v.stream.chunk_layout_id", FT_UINT32, BASE_HEX, NULL, 0x0, "U3V Stream Chunk Layout ID", HFILL } }, { &hf_u3v_stream_valid_payload_size, { "Valid Payload Size", "u3v.stream.valid_payload_size", FT_UINT64, BASE_HEX, NULL, 0x0, "U3V Stream Valid Payload Size", HFILL } }, { &hf_u3v_stream_status, { "Status", "u3v.stream.status", FT_UINT16, BASE_HEX, VALS( status_names ), 0x0, "U3V Stream Status", HFILL } }, { &hf_u3v_stream_data, { "Payload Data", "u3v.stream.data", FT_BYTES, BASE_NONE, NULL, 0x0, "U3V Stream Payload Data", HFILL } }, /* U3V device info descriptor */ { &hf_u3v_device_info_descriptor_bLength, { "bLength", "u3v.device_info.bLength", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bDescriptorType, { "bDescriptorType", "u3v.device_info.bDescriptorType", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bDescriptorSubtype, { "bDescriptorSubtype", "u3v.device_info.bDescriptorSubtype", FT_UINT8, BASE_HEX, VALS( u3v_descriptor_subtypes ), 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bGenCPVersion, { "bGenCPVersion", "u3v.device_info.bGenCPVersion", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bGenCPVersion_minor, { "Minor Version", "u3v.device_info.bGenCPVersion.minor", FT_UINT32, BASE_DEC, NULL, 0x0000FFFF, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bGenCPVersion_major, { "Major Version", "u3v.device_info.bGenCPVersion.major", FT_UINT32, BASE_DEC, NULL, 0xFFFF0000, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bU3VVersion, { "bU3VVersion", "u3v.device_info.bU3VVersion", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bU3VVersion_minor, { "Minor Version", "u3v.device_info.bU3VVersion.minor", FT_UINT32, BASE_DEC, NULL, 0x0000FFFF, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bU3VVersion_major, { "Major Version", "u3v.device_info.bU3VVersion.major", FT_UINT32, BASE_DEC, NULL, 0xFFFF0000, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iDeviceGUID, { "iDeviceGUID", "u3v.device_info.iDeviceGUID", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iVendorName, { "iVendorName", "u3v.device_info.iVendorName", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iModelName, { "iModelName", "u3v.device_info.iModelName", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iFamilyName, { "iFamilyName", "u3v.device_info.iFamilyName", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iDeviceVersion, { "iDeviceVersion", "u3v.device_info.iDeviceVersion", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iManufacturerInfo, { "iManufacturerInfo", "u3v.device_info.iManufacturerInfo", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iSerialNumber, { "iSerialNumber", "u3v.device_info.iSerialNumber", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_iUserDefinedName, { "iVendorName", "u3v.device_info.iUserDefinedName", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bmSpeedSupport, { "bmSpeedSupport", "u3v.device_info.bmSpeedSupport", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bmSpeedSupport_low_speed, { "Low-Speed", "u3v.device_info.bmSpeedSupport.lowSpeed", FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x01, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bmSpeedSupport_full_speed, { "Full-Speed", "u3v.device_info.bmSpeedSupport.fullSpeed", FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x02, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bmSpeedSupport_high_speed, { "High-Speed", "u3v.device_info.bmSpeedSupport.highSpeed", FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x04, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bmSpeedSupport_super_speed, { "Super-Speed", "u3v.device_info.bmSpeedSupport.superSpeed", FT_BOOLEAN, 8, TFS(&tfs_supported_not_supported), 0x08, NULL, HFILL } }, { &hf_u3v_device_info_descriptor_bmSpeedSupport_reserved, { "Reserved", "u3v.device_info.bmSpeedSupport.reserved", FT_UINT8, BASE_HEX, NULL, 0xF0, NULL, HFILL } }, { &hf_u3v_scd_readmem_cmd, { "SCD: READMEM_CMD", "u3v.scd_readmem_cmd", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_scd_writemem_cmd, { "SCD: WRITEMEM_CMD", "u3v.scd_writemem_cmd", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_scd_event_cmd, { "SCD: EVENT_CMD", "u3v.scd_event_cmd", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_scd_ack_readmem_ack, { "SCD: READMEM_ACK", "u3v.scd_ack_readmem_ack", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_scd_writemem_ack, { "SCD: WRITEMEM_ACK", "u3v.scd_writemem_ack", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_ccd_pending_ack, { "CCD: PENDING_ACK", "u3v.ccd_pending_ack", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_stream_leader, { "Stream: Leader", "u3v.stream_leader", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_stream_trailer, { "Stream: Trailer", "u3v.stream_trailer", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_stream_payload, { "Stream: Payload", "u3v.stream_payload", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_ccd_cmd, { "CCD", "u3v.ccd_cmd", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_ccd_ack, { "CCD", "u3v.ccd_ack", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_u3v_device_info_descriptor, { "U3V DEVICE INFO DESCRIPTOR", "u3v.device_info_descriptor", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } } }; void proto_register_u3v(void) { static gint *ett[] = { &ett_u3v, &ett_u3v_cmd, &ett_u3v_flags, &ett_u3v_ack, &ett_u3v_payload_cmd, &ett_u3v_payload_ack, &ett_u3v_payload_ack_subtree, &ett_u3v_payload_cmd_subtree, &ett_u3v_bootstrap_fields, &ett_u3v_stream_leader, &ett_u3v_stream_trailer, &ett_u3v_stream_payload, &ett_u3v_device_info_descriptor, &ett_u3v_device_info_descriptor_speed_support, &ett_u3v_device_info_descriptor_gencp_version, &ett_u3v_device_info_descriptor_u3v_version, }; proto_u3v = proto_register_protocol("USB 3 Vision", "U3V", "u3v"); proto_register_field_array(proto_u3v, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); register_dissector("u3v", dissect_u3v, proto_u3v); } void proto_reg_handoff_u3v(void) { dissector_handle_t u3v_handle = NULL; dissector_handle_t u3v_descr_handle = NULL; u3v_handle = find_dissector("u3v"); dissector_add_uint("usb.bulk", IF_CLASS_MISCELLANEOUS, u3v_handle); heur_dissector_add("usb.bulk", dissect_u3v_heur, "USB3Vision Protocol", "u3v", proto_u3v,HEURISTIC_ENABLE); u3v_descr_handle = create_dissector_handle(dissect_u3v_descriptors, proto_u3v); dissector_add_uint("usb.descriptor", IF_CLASS_MISCELLANEOUS, u3v_descr_handle); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5108_0
crossvul-cpp_data_good_216_0
/* * MPEG-4 decoder * Copyright (c) 2000,2001 Fabrice Bellard * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at> * * 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 */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/internal.h" #include "libavutil/opt.h" #include "error_resilience.h" #include "hwaccel.h" #include "idctdsp.h" #include "internal.h" #include "mpegutils.h" #include "mpegvideo.h" #include "mpegvideodata.h" #include "mpeg4video.h" #include "h263.h" #include "profiles.h" #include "thread.h" #include "xvididct.h" /* The defines below define the number of bits that are read at once for * reading vlc values. Changing these may improve speed and data cache needs * be aware though that decreasing them may need the number of stages that is * passed to get_vlc* to be increased. */ #define SPRITE_TRAJ_VLC_BITS 6 #define DC_VLC_BITS 9 #define MB_TYPE_B_VLC_BITS 4 #define STUDIO_INTRA_BITS 9 static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb); static VLC dc_lum, dc_chrom; static VLC sprite_trajectory; static VLC mb_type_b_vlc; static const int mb_type_b_map[4] = { MB_TYPE_DIRECT2 | MB_TYPE_L0L1, MB_TYPE_L0L1 | MB_TYPE_16x16, MB_TYPE_L1 | MB_TYPE_16x16, MB_TYPE_L0 | MB_TYPE_16x16, }; /** * Predict the ac. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir the ac prediction direction */ void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir) { int i; int16_t *ac_val, *ac_val1; int8_t *const qscale_table = s->current_picture.qscale_table; /* find prediction */ ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16; ac_val1 = ac_val; if (s->ac_pred) { if (dir == 0) { const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride; /* left prediction */ ac_val -= 16; if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ac_val[i]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale); } } else { const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride; /* top prediction */ ac_val -= 16 * s->block_wrap[n]; if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ac_val[i + 8]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale); } } } /* left copy */ for (i = 1; i < 8; i++) ac_val1[i] = block[s->idsp.idct_permutation[i << 3]]; /* top copy */ for (i = 1; i < 8; i++) ac_val1[8 + i] = block[s->idsp.idct_permutation[i]]; } /** * check if the next stuff is a resync marker or the end. * @return 0 if not */ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int bits_count = get_bits_count(&s->gb); int v = show_bits(&s->gb, 16); if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker) return 0; while (v <= 0xFF) { if (s->pict_type == AV_PICTURE_TYPE_B || (v >> (8 - s->pict_type) != 1) || s->partitioned_frame) break; skip_bits(&s->gb, 8 + s->pict_type); bits_count += 8 + s->pict_type; v = show_bits(&s->gb, 16); } if (bits_count + 8 >= s->gb.size_in_bits) { v >>= 8; v |= 0x7F >> (7 - (bits_count & 7)); if (v == 0x7F) return s->mb_num; } else { if (v == ff_mpeg4_resync_prefix[bits_count & 7]) { int len, mb_num; int mb_num_bits = av_log2(s->mb_num - 1) + 1; GetBitContext gb = s->gb; skip_bits(&s->gb, 1); align_get_bits(&s->gb); for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; mb_num = get_bits(&s->gb, mb_num_bits); if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits) mb_num= -1; s->gb = gb; if (len >= ff_mpeg4_get_video_packet_prefix_length(s)) return mb_num; } } return 0; } static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; int64_t sprite_offset[2][2]; int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; /* the decoder was not properly initialized and we cannot continue */ if (sprite_trajectory.table == NULL) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) check_marker(s->avctx, gb, "before sprite_trajectory"); length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) y = get_xbits(gb, length); check_marker(s->avctx, gb, "after sprite_trajectory"); ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the MPEG-4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* This is mostly identical to the MPEG-4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: sprite_offset[0][0] = sprite_offset[0][1] = sprite_offset[1][0] = sprite_offset[1][1] = 0; sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && sprite_delta[0][1] == 0 && sprite_delta[1][0] == 0 && sprite_delta[1][1] == a << ctx->sprite_shift[0]) { sprite_offset[0][0] >>= ctx->sprite_shift[0]; sprite_offset[0][1] >>= ctx->sprite_shift[0]; sprite_offset[1][0] >>= ctx->sprite_shift[1]; sprite_offset[1][1] >>= ctx->sprite_shift[1]; sprite_delta[0][0] = a; sprite_delta[0][1] = 0; sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { if (shift_c < 0 || shift_y < 0 || FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y ) { avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); goto overflow; } } for (i = 0; i < 2; i++) { sprite_offset[0][i] *= 1 << shift_y; sprite_offset[1][i] *= 1 << shift_c; sprite_delta[0][i] *= 1 << shift_y; sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; } for (i = 0; i < 2; i++) { int64_t sd[2] = { sprite_delta[i][0] - a * (1LL<<16), sprite_delta[i][1] - a * (1LL<<16) }; if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX || llabs(sd[0]) >= INT_MAX || llabs(sd[1]) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX ) { avpriv_request_sample(s->avctx, "Overflow on sprite points"); goto overflow; } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } for (i = 0; i < 4; i++) { s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; } return 0; overflow: memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int len = FFMIN(ctx->time_increment_bits + 3, 15); get_bits(gb, len); if (get_bits1(gb)) get_bits(gb, len); check_marker(s->avctx, gb, "after new_pred"); return 0; } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return AVERROR_INVALIDDATA; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return AVERROR_INVALIDDATA; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return AVERROR_INVALIDDATA; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; } static void reset_studio_dc_predictors(MpegEncContext *s) { /* Reset DC Predictors */ s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1); } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; GetBitContext *gb = &s->gb; unsigned vlc_len; uint16_t mb_num; if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) { vlc_len = av_log2(s->mb_width * s->mb_height) + 1; mb_num = get_bits(gb, vlc_len); if (mb_num >= s->mb_num) return AVERROR_INVALIDDATA; s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) s->qscale = mpeg_get_qscale(s); if (get_bits1(gb)) { /* slice_extension_flag */ skip_bits1(gb); /* intra_slice */ skip_bits1(gb); /* slice_VOP_id_enable */ skip_bits(gb, 6); /* slice_VOP_id */ while (get_bits1(gb)) /* extra_bit_slice */ skip_bits(gb, 8); /* extra_information_slice */ } reset_studio_dc_predictors(s); } else { return AVERROR_INVALIDDATA; } return 0; } /** * Get the average motion vector for a GMC MB. * @param n either 0 for the x component or 1 for y * @return the average MV for a GMC MB */ static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; } /** * Decode the dc value. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir_ptr the prediction direction will be stored here * @return the quantized dc */ static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr) { int level, code; if (n < 4) code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1); else code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1); if (code < 0 || code > 9 /* && s->nbit < 9 */) { av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n"); return AVERROR_INVALIDDATA; } if (code == 0) { level = 0; } else { if (IS_3IV1) { if (code == 1) level = 2 * get_bits1(&s->gb) - 1; else { if (get_bits1(&s->gb)) level = get_bits(&s->gb, code - 1) + (1 << (code - 1)); else level = -get_bits(&s->gb, code - 1) - (1 << (code - 1)); } } else { level = get_xbits(&s->gb, code); } if (code > 8) { if (get_bits1(&s->gb) == 0) { /* marker */ if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) { av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n"); return AVERROR_INVALIDDATA; } } } } return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0); } /** * Decode first partition. * @return number of MBs decoded or <0 if an error occurred */ static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; /* decode first partition */ s->first_slice_line = 1; for (; s->mb_y < s->mb_height; s->mb_y++) { ff_init_block_index(s); for (; s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; int cbpc; int dir = 0; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int i; do { if (show_bits_long(&s->gb, 19) == DC_MARKER) return mb_num - 1; cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); s->cbp_table[xy] = cbpc & 3; s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mb_intra = 1; if (cbpc & 4) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->mbintra_table[xy] = 1; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->pred_dir_table[xy] = dir; } else { /* P/S_TYPE */ int mx, my, pred_x, pred_y, bits; int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]]; const int stride = s->b8_stride * 2; try_again: bits = show_bits(&s->gb, 17); if (bits == MOTION_MARKER) return mb_num - 1; skip_bits1(&s->gb); if (bits & 0x10000) { /* skip mb */ if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; mx = my = 0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); continue; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (cbpc == 20) goto try_again; s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) { s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mbintra_table[xy] = 1; mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = 0; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = 0; } else { if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; if ((cbpc & 16) == 0) { /* 16x16 motion prediction */ ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); if (!s->mcsel) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; } else { mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; } else { int i; s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; for (i = 0; i < 4; i++) { int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; mot_val[0] = mx; mot_val[1] = my; } } } } } s->mb_x = 0; } return mb_num; } /** * decode second partition. * @return <0 if an error occurred */ static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count) { int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; s->mb_x = s->resync_mb_x; s->first_slice_line = 1; for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) { ff_init_block_index(s); for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; } else { /* P || S_TYPE */ if (IS_INTRA(s->current_picture.mb_type[xy])) { int i; int dir = 0; int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; s->pred_dir_table[xy] = dir; } else if (IS_SKIP(s->current_picture.mb_type[xy])) { s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] = 0; } else { int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= (cbpy ^ 0xf) << 2; } } } if (mb_num >= mb_count) return 0; s->mb_x = 0; } return 0; } /** * Decode the first and second partition. * @return <0 if error (and sets error type in the error_status_table) */ int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num; int ret; const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR; const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END; mb_num = mpeg4_decode_partition_a(ctx); if (mb_num <= 0) { ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return mb_num ? mb_num : AVERROR_INVALIDDATA; } if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n"); ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return AVERROR_INVALIDDATA; } s->mb_num_left = mb_num; if (s->pict_type == AV_PICTURE_TYPE_I) { while (show_bits(&s->gb, 9) == 1) skip_bits(&s->gb, 9); if (get_bits_long(&s->gb, 19) != DC_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } else { while (show_bits(&s->gb, 10) == 1) skip_bits(&s->gb, 10); if (get_bits(&s->gb, 17) != MOTION_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, part_a_end); ret = mpeg4_decode_partition_b(s, mb_num); if (ret < 0) { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_DC_ERROR); return ret; } else { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, ER_DC_END); } return 0; } /** * Decode a block. * @return <0 if an error occurred */ static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block, int n, int coded, int intra, int rvlc) { MpegEncContext *s = &ctx->m; int level, i, last, run, qmul, qadd; int av_uninit(dc_pred_dir); RLTable *rl; RL_VLC_ELEM *rl_vlc; const uint8_t *scan_table; // Note intra & rvlc should be optimized away if this is inlined if (intra) { if (ctx->use_intra_dc_vlc) { /* DC coef */ if (s->partitioned_frame) { level = s->dc_val[0][s->block_index[n]]; if (n < 4) level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale); else level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale); dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32; } else { level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return level; } block[0] = level; i = 0; } else { i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if (rvlc) { rl = &ff_rvlc_rl_intra; rl_vlc = ff_rvlc_rl_intra.rl_vlc[0]; } else { rl = &ff_mpeg4_rl_intra; rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; /* left */ else scan_table = s->intra_h_scantable.permutated; /* top */ } else { scan_table = s->intra_scantable.permutated; } qmul = 1; qadd = 0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if (rvlc) rl = &ff_rvlc_rl_inter; else rl = &ff_h263_rl_inter; scan_table = s->intra_scantable.permutated; if (s->mpeg_quant) { qmul = 1; qadd = 0; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[0]; else rl_vlc = ff_h263_rl_inter.rl_vlc[0]; } else { qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale]; else rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale]; } } { OPEN_READER(re, &s->gb); for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level == 0) { /* escape */ if (rvlc) { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if (SHOW_UBITS(re, &s->gb, 5) != 0x10) { av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 5); level = level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1); i += run + 1; if (last) i += 192; } else { int cache; cache = GET_CACHE(re, &s->gb); if (IS_3IV1) cache ^= 0xC0000000; if (cache & 0x80000000) { if (cache & 0x40000000) { /* third escape */ SKIP_CACHE(re, &s->gb, 2); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (IS_3IV1) { level = SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); } else { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_COUNTER(re, &s->gb, 1 + 12 + 1); } #if 0 if (s->error_recognition >= FF_ER_COMPLIANT) { const int abs_level= FFABS(level); if (abs_level<=MAX_LEVEL && run<=MAX_RUN) { const int run1= run - rl->max_run[last][abs_level] - 1; if (abs_level <= rl->max_level[last][run]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return AVERROR_INVALIDDATA; } if (s->error_recognition > FF_ER_COMPLIANT) { if (abs_level <= rl->max_level[last][run]*2) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return AVERROR_INVALIDDATA; } if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return AVERROR_INVALIDDATA; } } } } #endif if (level > 0) level = level * qmul + qadd; else level = level * qmul - qadd; if ((unsigned)(level + 2048) > 4095) { if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) { if (level > 2560 || level < -2560) { av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return AVERROR_INVALIDDATA; } } level = level < 0 ? -2048 : 2047; } i += run + 1; if (last) i += 192; } else { /* second escape */ SKIP_BITS(re, &s->gb, 2); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { /* first escape */ SKIP_BITS(re, &s->gb, 1); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run; level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i += run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62); if (i > 62) { i -= 192; if (i & (~63)) { av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if (!ctx->use_intra_dc_vlc) { block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i >> 31; // if (i == -1) i = 0; } ff_mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) i = 63; // FIXME not optimal } s->block_last_index[n] = i; return 0; } /** * decode partition C of one MB. * @return <0 if an error occurred */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (s->current_picture.qscale_table[xy] != s->qscale) ff_set_qscale(s, s->current_picture.qscale_table[xy]); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { int i; for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; } s->mb_intra = IS_INTRA(mb_type); if (IS_SKIP(mb_type)) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->mcsel = 1; s->mb_skipped = 0; } else { s->mcsel = 0; s->mb_skipped = 1; } } else if (s->mb_intra) { s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } else if (!s->mb_intra) { // s->mcsel = 0; // FIXME do we need to init that? s->mv_dir = MV_DIR_FORWARD; if (IS_8X8(mb_type)) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } } } else { /* I-Frame */ s->mb_intra = 1; s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } if (!IS_SKIP(mb_type)) { int i; s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra); return AVERROR_INVALIDDATA; } cbp += cbp; } } /* per-MB end of slice check */ if (--s->mb_num_left <= 0) { if (mpeg4_is_resync(ctx)) return SLICE_END; else return SLICE_NOEND; } else { if (mpeg4_is_resync(ctx)) { const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; if (s->cbp_table[xy + delta]) return SLICE_END; } return SLICE_OK; } } static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { do { if (get_bits1(&s->gb)) { /* skip mb */ s->mb_intra = 0; for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 1; s->mv[0][0][0] = get_amv(ctx, 0); s->mv[0][0][1] = get_amv(ctx, 1); s->mb_skipped = 0; } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 0; s->mv[0][0][0] = 0; s->mv[0][0][1] = 0; s->mb_skipped = 1; } goto end; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 20); s->bdsp.clear_blocks(s->block[0]); dquant = cbpc & 8; s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) goto intra; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F; if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if ((!s->progressive_sequence) && (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE))) s->interlaced_dct = get_bits1(&s->gb); s->mv_dir = MV_DIR_FORWARD; if ((cbpc & 16) == 0) { if (s->mcsel) { s->current_picture.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 global motion prediction */ s->mv_type = MV_TYPE_16X16; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) { s->current_picture.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; /* 16x8 field motion prediction */ s->mv_type = MV_TYPE_FIELD; s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y / 2, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 motion prediction */ s->mv_type = MV_TYPE_16X16; ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; s->mv_type = MV_TYPE_8X8; for (i = 0; i < 4; i++) { mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; mot_val[0] = mx; mot_val[1] = my; } } } else if (s->pict_type == AV_PICTURE_TYPE_B) { int modb1; // first bit of modb int modb2; // second bit of modb int mb_type; s->mb_intra = 0; // B-frames never contain intra blocks s->mcsel = 0; // ... true gmc blocks if (s->mb_x == 0) { for (i = 0; i < 2; i++) { s->last_mv[i][0][0] = s->last_mv[i][0][1] = s->last_mv[i][1][0] = s->last_mv[i][1][1] = 0; } ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0); } /* if we skipped it in the future P-frame than skip it now too */ s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC if (s->mb_skipped) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->mv[0][0][1] = s->mv[1][0][0] = s->mv[1][0][1] = 0; s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; goto end; } modb1 = get_bits1(&s->gb); if (modb1) { // like MB_TYPE_B_DIRECT but no vectors coded mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; cbp = 0; } else { modb2 = get_bits1(&s->gb); mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1); if (mb_type < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n"); return AVERROR_INVALIDDATA; } mb_type = mb_type_b_map[mb_type]; if (modb2) { cbp = 0; } else { s->bdsp.clear_blocks(s->block[0]); cbp = get_bits(&s->gb, 6); } if ((!IS_DIRECT(mb_type)) && cbp) { if (get_bits1(&s->gb)) ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2); } if (!s->progressive_sequence) { if (cbp) s->interlaced_dct = get_bits1(&s->gb); if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) { mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; mb_type &= ~MB_TYPE_16x16; if (USES_LIST(mb_type, 0)) { s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); } if (USES_LIST(mb_type, 1)) { s->field_select[1][0] = get_bits1(&s->gb); s->field_select[1][1] = get_bits1(&s->gb); } } } s->mv_dir = 0; if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) { s->mv_type = MV_TYPE_16X16; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code); s->last_mv[0][1][0] = s->last_mv[0][0][0] = s->mv[0][0][0] = mx; s->last_mv[0][1][1] = s->last_mv[0][0][1] = s->mv[0][0][1] = my; } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code); s->last_mv[1][1][0] = s->last_mv[1][0][0] = s->mv[1][0][0] = mx; s->last_mv[1][1][1] = s->last_mv[1][0][1] = s->mv[1][0][1] = my; } } else if (!IS_DIRECT(mb_type)) { s->mv_type = MV_TYPE_FIELD; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code); s->last_mv[0][i][0] = s->mv[0][i][0] = mx; s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2; } } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code); s->last_mv[1][i][0] = s->mv[1][i][0] = mx; s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2; } } } } if (IS_DIRECT(mb_type)) { if (IS_SKIP(mb_type)) { mx = my = 0; } else { mx = ff_h263_decode_motion(s, 0, 1); my = ff_h263_decode_motion(s, 0, 1); } s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT; mb_type |= ff_mpeg4_set_direct_mv(s, mx, my); } s->current_picture.mb_type[xy] = mb_type; } else { /* I-Frame */ do { cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); dquant = cbpc & 4; s->mb_intra = 1; intra: s->ac_pred = get_bits1(&s->gb); if (s->ac_pred) s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED; else s->current_picture.mb_type[xy] = MB_TYPE_INTRA; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if (!s->progressive_sequence) s->interlaced_dct = get_bits1(&s->gb); s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } goto end; } /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } end: /* per-MB end of slice check */ if (s->codec_id == AV_CODEC_ID_MPEG4) { int next = mpeg4_is_resync(ctx); if (next) { if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) { return AVERROR_INVALIDDATA; } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next) return SLICE_END; if (s->pict_type == AV_PICTURE_TYPE_B) { const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1; ff_thread_await_progress(&s->next_picture_ptr->tf, (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y + 1, s->mb_height - 1) : s->mb_y, 0); if (s->next_picture.mbskip_table[xy + delta]) return SLICE_OK; } return SLICE_END; } } return SLICE_OK; } /* As per spec, studio start code search isn't the same as the old type of start code */ static void next_start_code_studio(GetBitContext *gb) { align_get_bits(gb); while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) { get_bits(gb, 8); } } /* additional_code, vlc index */ static const uint8_t ac_state_tab[22][2] = { {0, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {0, 11} }; static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64]) { int i; /* StudioMacroblock */ /* Assumes I-VOP */ s->mb_intra = 1; if (get_bits1(&s->gb)) { /* compression_mode */ /* DCT */ /* macroblock_type, 1 or 2-bit VLC */ if (!get_bits1(&s->gb)) { skip_bits1(&s->gb); s->qscale = mpeg_get_qscale(s); } for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) { if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0) return AVERROR_INVALIDDATA; } } else { /* DPCM */ check_marker(s->avctx, &s->gb, "DPCM block start"); avpriv_request_sample(s->avctx, "DPCM encoded block"); next_start_code_studio(&s->gb); return SLICE_ERROR; } if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) { next_start_code_studio(&s->gb); return SLICE_END; } return SLICE_OK; } static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb) { int hours, minutes, seconds; if (!show_bits(gb, 23)) { av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n"); return AVERROR_INVALIDDATA; } hours = get_bits(gb, 5); minutes = get_bits(gb, 6); check_marker(s->avctx, gb, "in gop_header"); seconds = get_bits(gb, 6); s->time_base = seconds + 60*(minutes + 60*hours); skip_bits1(gb); skip_bits1(gb); return 0; } static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); // for Simple profile, level 0 if (*profile == 0 && *level == 8) { *level = 0; } return 0; } static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb) { int visual_object_type; int is_visual_object_identifier = get_bits1(gb); if (is_visual_object_identifier) { skip_bits(gb, 4+3); } visual_object_type = get_bits(gb, 4); if (visual_object_type == VOT_VIDEO_ID || visual_object_type == VOT_STILL_TEXTURE_ID) { int video_signal_type = get_bits1(gb); if (video_signal_type) { int video_range, color_description; skip_bits(gb, 3); // video_format video_range = get_bits1(gb); color_description = get_bits1(gb); s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (color_description) { s->avctx->color_primaries = get_bits(gb, 8); s->avctx->color_trc = get_bits(gb, 8); s->avctx->colorspace = get_bits(gb, 8); } } } return 0; } static void mpeg4_load_default_matrices(MpegEncContext *s) { int i, v; /* load default matrices */ for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } } static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); /* If we are in studio profile (per vo_type), check if its all consistent * and if so continue pass control to decode_studio_vol_header(). * elIf something is inconsistent, error out * else continue with (non studio) vol header decpoding. */ if (s->vo_type == CORE_STUDIO_VO_TYPE || s->vo_type == SIMPLE_STUDIO_VO_TYPE) { if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO) return AVERROR_INVALIDDATA; s->studio_profile = 1; s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO; return decode_studio_vol_header(ctx, gb); } else if (s->studio_profile) { return AVERROR_PATCHWELCOME; } if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ check_marker(s->avctx, gb, "after first_half_bitrate"); get_bits(gb, 15); /* latter_half_bitrate */ check_marker(s->avctx, gb, "after latter_half_bitrate"); get_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ check_marker(s->avctx, gb, "after first_half_vbv_occupancy"); get_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection will not be overridden. */ if (s->picture_number == 0) { switch(s->vo_type) { case SIMPLE_VO_TYPE: case ADV_SIMPLE_VO_TYPE: s->low_delay = 1; break; default: s->low_delay = 0; } } } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(s->avctx, gb, "before time_increment_resolution"); s->avctx->framerate.num = get_bits(gb, 16); if (!s->avctx->framerate.num) { av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n"); return AVERROR_INVALIDDATA; } ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(s->avctx, gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits); else s->avctx->framerate.den = 1; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before width"); width = get_bits(gb, 13); check_marker(s->avctx, gb, "before height"); height = get_bits(gb, 13); check_marker(s->avctx, gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG-4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width check_marker(s->avctx, gb, "after sprite_width"); skip_bits(gb, 13); // sprite_height check_marker(s->avctx, gb, "after sprite_height"); skip_bits(gb, 13); // sprite_left check_marker(s->avctx, gb, "after sprite_left"); skip_bits(gb, 13); // sprite_top check_marker(s->avctx, gb, "after sprite_top"); } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return AVERROR_INVALIDDATA; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; mpeg4_load_default_matrices(s); /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (get_bits_left(gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n"); return AVERROR_INVALIDDATA; } if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n", s->avctx->framerate.den, s->avctx->framerate.num, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, s->low_delay, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } /** * Decode the user data stuff in the header. * Also initializes divx/xvid/lavc_version/build. */ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; char buf[256]; int i; int e; int ver = 0, build = 0, ver2 = 0, ver3 = 0; char last; for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) { if (show_bits(gb, 23) == 0) break; buf[i] = get_bits(gb, 8); } buf[i] = 0; /* divx detection */ e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last); if (e < 2) e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last); if (e >= 2) { ctx->divx_version = ver; ctx->divx_build = build; s->divx_packed = e == 3 && last == 'p'; } /* libavcodec detection */ e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3; if (e != 4) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; if (e > 1) { if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { av_log(s->avctx, AV_LOG_WARNING, "Unknown Lavc version string encountered, %d.%d.%d; " "clamping sub-version values to 8-bits.\n", ver, ver2, ver3); } build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) ctx->lavc_build = 4600; } if (e == 4) ctx->lavc_build = build; /* Xvid detection */ e = sscanf(buf, "XviD%d", &build); if (e == 1) ctx->xvid_build = build; return 0; } int ff_mpeg4_workaround_bugs(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) { if (s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") || s->codec_tag == AV_RL32("RMP4") || s->codec_tag == AV_RL32("ZMP4") || s->codec_tag == AV_RL32("SIPP")) ctx->xvid_build = 0; } if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 && ctx->vol_control_parameters == 0) ctx->divx_version = 400; // divx 4 if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) { ctx->divx_version = ctx->divx_build = -1; } if (s->workaround_bugs & FF_BUG_AUTODETECT) { if (s->codec_tag == AV_RL32("XVIX")) s->workaround_bugs |= FF_BUG_XVID_ILACE; if (s->codec_tag == AV_RL32("UMP4")) s->workaround_bugs |= FF_BUG_UMP4; if (ctx->divx_version >= 500 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->divx_version > 502 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA2; if (ctx->xvid_build <= 3U) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->xvid_build <= 1U) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->xvid_build <= 12U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->xvid_build <= 32U) s->workaround_bugs |= FF_BUG_DC_CLIP; #define SET_QPEL_FUNC(postfix1, postfix2) \ s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \ s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \ s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2; if (ctx->lavc_build < 4653U) s->workaround_bugs |= FF_BUG_STD_QPEL; if (ctx->lavc_build < 4655U) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->lavc_build < 4670U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->lavc_build <= 4712U) s->workaround_bugs |= FF_BUG_DC_CLIP; if ((ctx->lavc_build&0xFF) >= 100) { if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 && (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+ ) s->workaround_bugs |= FF_BUG_IEDGE; } if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->divx_version == 501 && ctx->divx_build == 20020416) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->divx_version < 500U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_HPEL_CHROMA; } if (s->workaround_bugs & FF_BUG_STD_QPEL) { SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c) } if (avctx->debug & FF_DEBUG_BUGS) av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n", s->workaround_bugs, ctx->lavc_build, ctx->xvid_build, ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : ""); if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 && s->codec_id == AV_CODEC_ID_MPEG4 && avctx->idct_algo == FF_IDCT_AUTO) { avctx->idct_algo = FF_IDCT_XVID; ff_mpv_idct_init(s); return 1; } return 0; } static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int time_incr, time_increment; int64_t pts; s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n"); s->low_delay = 0; } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; if (s->partitioned_frame) s->decode_mb = mpeg4_decode_partitioned_mb; else s->decode_mb = mpeg4_decode_mb; time_incr = 0; while (get_bits1(gb) != 0) time_incr++; check_marker(s->avctx, gb, "before time_increment"); if (ctx->time_increment_bits == 0 || !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) { av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits); for (ctx->time_increment_bits = 1; ctx->time_increment_bits < 16; ctx->time_increment_bits++) { if (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE)) { if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30) break; } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18) break; } av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits); if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) { s->avctx->framerate.num = 1<<ctx->time_increment_bits; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); } } if (IS_3IV1) time_increment = get_bits1(gb); // FIXME investigate further else time_increment = get_bits(gb, ctx->time_increment_bits); if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, * trying to workaround */ s->time_base++; s->time += s->avctx->framerate.num; } } s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0) { /* messed up order, maybe after seeking? skipping current B-frame */ return FRAME_SKIPPED; } ff_mpeg4_init_direct_mv(s); if (ctx->t_frame == 0) ctx->t_frame = s->pb_time; if (ctx->t_frame == 0) ctx->t_frame = 1; // 1/0 protection s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) { s->pb_field_time = 2; s->pp_field_time = 4; if (!s->progressive_sequence) return FRAME_SKIPPED; } } if (s->avctx->framerate.den) pts = ROUNDED_DIV(s->time, s->avctx->framerate.den); else pts = AV_NOPTS_VALUE; ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts); check_marker(s->avctx, gb, "before vop_coded"); /* vop coded */ if (get_bits1(gb) != 1) { if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n"); return FRAME_SKIPPED; } if (ctx->new_pred) decode_new_pred(ctx, gb); if (ctx->shape != BIN_ONLY_SHAPE && (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE))) { /* rounding type for motion estimation */ s->no_rounding = get_bits1(gb); } else { s->no_rounding = 0; } // FIXME reduced res stuff if (ctx->shape != RECT_SHAPE) { if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) { skip_bits(gb, 13); /* width */ check_marker(s->avctx, gb, "after width"); skip_bits(gb, 13); /* height */ check_marker(s->avctx, gb, "after height"); skip_bits(gb, 13); /* hor_spat_ref */ check_marker(s->avctx, gb, "after hor_spat_ref"); skip_bits(gb, 13); /* ver_spat_ref */ } skip_bits1(gb); /* change_CR_disable */ if (get_bits1(gb) != 0) skip_bits(gb, 8); /* constant_alpha_value */ } // FIXME complexity estimation stuff if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits_long(gb, ctx->cplx_estimation_trash_i); if (s->pict_type != AV_PICTURE_TYPE_I) skip_bits_long(gb, ctx->cplx_estimation_trash_p); if (s->pict_type == AV_PICTURE_TYPE_B) skip_bits_long(gb, ctx->cplx_estimation_trash_b); if (get_bits_left(gb) < 3) { av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n"); return AVERROR_INVALIDDATA; } ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)]; if (!s->progressive_sequence) { s->top_field_first = get_bits1(gb); s->alternate_scan = get_bits1(gb); } else s->alternate_scan = 0; } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } if (s->pict_type == AV_PICTURE_TYPE_S) { if((ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE)) { if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) return AVERROR_INVALIDDATA; if (ctx->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); } else { memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); } } if (ctx->shape != BIN_ONLY_SHAPE) { s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision); if (s->qscale == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (qscale=0)\n"); return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } if (s->pict_type != AV_PICTURE_TYPE_I) { s->f_code = get_bits(gb, 3); /* fcode_for */ if (s->f_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (f_code=0)\n"); s->f_code = 1; return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } } else s->f_code = 1; if (s->pict_type == AV_PICTURE_TYPE_B) { s->b_code = get_bits(gb, 3); if (s->b_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (b_code=0)\n"); s->b_code=1; return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly } } else s->b_code = 1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n", s->qscale, s->f_code, s->b_code, s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")), gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first, s->quarter_sample ? "q" : "h", s->data_partitioning, ctx->resync_marker, ctx->num_sprite_warping_points, s->sprite_warping_accuracy, 1 - s->no_rounding, s->vo_type, ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold, ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p, ctx->cplx_estimation_trash_b, s->time, time_increment ); } if (!ctx->scalability) { if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I) skip_bits1(gb); // vop shape coding type } else { if (ctx->enhancement_type) { int load_backward_shape = get_bits1(gb); if (load_backward_shape) av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n"); } skip_bits(gb, 2); // ref_select_code } } /* detect buggy encoders which don't set the low_delay flag * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames * easily (although it's buggy too) */ if (s->vo_type == 0 && ctx->vol_control_parameters == 0 && ctx->divx_version == -1 && s->picture_number == 0) { av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n"); s->low_delay = 1; } s->picture_number++; // better than pic number==0 always ;) // FIXME add short header support s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table; if (s->workaround_bugs & FF_BUG_EDGE) { s->h_edge_pos = s->width; s->v_edge_pos = s->height; } return 0; } static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id) { uint32_t startcode; uint8_t extension_type; startcode = show_bits_long(gb, 32); if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) { if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) { skip_bits_long(gb, 32); extension_type = get_bits(gb, 4); if (extension_type == QUANT_MATRIX_EXT_ID) read_quant_matrix_ext(s, gb); } } } static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; skip_bits(gb, 16); /* Time_code[63..48] */ check_marker(s->avctx, gb, "after Time_code[63..48]"); skip_bits(gb, 16); /* Time_code[47..32] */ check_marker(s->avctx, gb, "after Time_code[47..32]"); skip_bits(gb, 16); /* Time_code[31..16] */ check_marker(s->avctx, gb, "after Time_code[31..16]"); skip_bits(gb, 16); /* Time_code[15..0] */ check_marker(s->avctx, gb, "after Time_code[15..0]"); skip_bits(gb, 4); /* reserved_bits */ } /** * Decode the next studio vop header. * @return <0 if something went wrong */ static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int visual_object_type; skip_bits(gb, 4); /* visual_object_verid */ visual_object_type = get_bits(gb, 4); if (visual_object_type != VOT_VIDEO_ID) { avpriv_request_sample(s->avctx, "VO type %u", visual_object_type); return AVERROR_PATCHWELCOME; } next_start_code_studio(gb); extension_and_user_data(s, gb, 1); return 0; } static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height; int bits_per_raw_sample; // random_accessible_vol and video_object_type_indication have already // been read by the caller decode_vol_header() skip_bits(gb, 4); /* video_object_layer_verid */ ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */ skip_bits(gb, 4); /* video_object_layer_shape_extension */ skip_bits1(gb); /* progressive_sequence */ if (ctx->shape != BIN_ONLY_SHAPE) { ctx->rgb = get_bits1(gb); /* rgb_components */ s->chroma_format = get_bits(gb, 2); /* chroma_format */ if (!s->chroma_format) { av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); return AVERROR_INVALIDDATA; } bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */ if (bits_per_raw_sample == 10) { if (ctx->rgb) { s->avctx->pix_fmt = AV_PIX_FMT_GBRP10; } else { s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10; } } else { avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample); return AVERROR_PATCHWELCOME; } s->avctx->bits_per_raw_sample = bits_per_raw_sample; } if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before video_object_layer_width"); width = get_bits(gb, 14); /* video_object_layer_width */ check_marker(s->avctx, gb, "before video_object_layer_height"); height = get_bits(gb, 14); /* video_object_layer_height */ check_marker(s->avctx, gb, "after video_object_layer_height"); /* Do the same check as non-studio profile */ if (width && height) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } skip_bits(gb, 4); /* frame_rate_code */ skip_bits(gb, 15); /* first_half_bit_rate */ check_marker(s->avctx, gb, "after first_half_bit_rate"); skip_bits(gb, 15); /* latter_half_bit_rate */ check_marker(s->avctx, gb, "after latter_half_bit_rate"); skip_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 3); /* latter_half_vbv_buffer_size */ skip_bits(gb, 11); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); s->low_delay = get_bits1(gb); s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */ next_start_code_studio(gb); extension_and_user_data(s, gb, 2); return 0; } /** * Decode MPEG-4 headers. * @return <0 if no VOP found (or a damaged one) * FRAME_SKIPPED if a not coded VOP is found * 0 if a VOP is found */ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { int profile, level; mpeg4_decode_profile_level(s, gb, &profile, &level); if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (level > 0 && level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } else if (s->studio_profile) { avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n"); return AVERROR_PATCHWELCOME; } s->avctx->profile = profile; s->avctx->level = level; } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO); if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } av_cold void ff_mpeg4videodec_static_init(void) { static int done = 0; if (!done) { ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]); ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]); ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]); INIT_VLC_RL(ff_mpeg4_rl_intra, 554); INIT_VLC_RL(ff_rvlc_rl_inter, 1072); INIT_VLC_RL(ff_rvlc_rl_intra, 1072); INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_lum[0][1], 2, 1, &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512); INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_chrom[0][1], 2, 1, &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512); INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15, &ff_sprite_trajectory_tab[0][1], 4, 2, &ff_sprite_trajectory_tab[0][0], 4, 2, 128); INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4, &ff_mb_type_b_tab[0][1], 2, 1, &ff_mb_type_b_tab[0][0], 2, 1, 16); done = 1; } } int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; /* divx 5.01+ bitstream reorder stuff */ /* Since this clobbers the input buffer and hwaccel codecs still need the * data during hwaccel->end_frame we should not do this any earlier */ if (s->divx_packed) { int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3); int startcode_found = 0; if (buf_size - current_pos > 7) { int i; for (i = current_pos; i < buf_size - 4; i++) if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1 && buf[i + 3] == 0xB6) { startcode_found = !(buf[i + 4] & 0x40); break; } } if (startcode_found) { if (!ctx->showed_packed_warning) { av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and " "wasteful way to store B-frames ('packed B-frames'). " "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n"); ctx->showed_packed_warning = 1; } av_fast_padded_malloc(&s->bitstream_buffer, &s->allocated_bitstream_buffer_size, buf_size - current_pos); if (!s->bitstream_buffer) { s->bitstream_buffer_size = 0; return AVERROR(ENOMEM); } memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos); s->bitstream_buffer_size = buf_size - current_pos; } } return 0; } #if HAVE_THREADS static int mpeg4_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { Mpeg4DecContext *s = dst->priv_data; const Mpeg4DecContext *s1 = src->priv_data; int init = s->m.context_initialized; int ret = ff_mpeg_update_thread_context(dst, src); if (ret < 0) return ret; memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext)); if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0) ff_xvid_idct_init(&s->m.idsp, dst); return 0; } #endif static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx) { int i, ret; for (i = 0; i < 12; i++) { ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22, &ff_mpeg4_studio_intra[i][0][1], 4, 2, &ff_mpeg4_studio_intra[i][0][0], 4, 2, 0); if (ret < 0) return ret; } ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_luma[0][1], 4, 2, &ff_mpeg4_studio_dc_luma[0][0], 4, 2, 0); if (ret < 0) return ret; ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_chroma[0][1], 4, 2, &ff_mpeg4_studio_dc_chroma[0][0], 4, 2, 0); if (ret < 0) return ret; return 0; } static av_cold int decode_init(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; int ret; ctx->divx_version = ctx->divx_build = ctx->xvid_build = ctx->lavc_build = -1; if ((ret = ff_h263_decode_init(avctx)) < 0) return ret; ff_mpeg4videodec_static_init(); if ((ret = init_studio_vlcs(ctx)) < 0) return ret; s->h263_pred = 1; s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */ s->decode_mb = mpeg4_decode_mb; ctx->time_increment_bits = 4; /* default value for broken headers */ avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; avctx->internal->allocate_progress = 1; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; int i; if (!avctx->internal->is_copy) { for (i = 0; i < 12; i++) ff_free_vlc(&ctx->studio_intra_tab[i]); ff_free_vlc(&ctx->studio_luma_dc); ff_free_vlc(&ctx->studio_chroma_dc); } return ff_h263_decode_end(avctx); } static const AVOption mpeg4_options[] = { {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {NULL} }; static const AVClass mpeg4_class = { .class_name = "MPEG4 Video Decoder", .item_name = av_default_item_name, .option = mpeg4_options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_mpeg4_decoder = { .name = "mpeg4", .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .priv_data_size = sizeof(Mpeg4DecContext), .init = decode_init, .close = decode_end, .decode = ff_h263_decode_frame, .capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, .flush = ff_mpeg_flush, .max_lowres = 3, .pix_fmts = ff_h263_hwaccel_pixfmt_list_420, .profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles), .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context), .priv_class = &mpeg4_class, .hw_configs = (const AVCodecHWConfigInternal*[]) { #if CONFIG_MPEG4_NVDEC_HWACCEL HWACCEL_NVDEC(mpeg4), #endif #if CONFIG_MPEG4_VAAPI_HWACCEL HWACCEL_VAAPI(mpeg4), #endif #if CONFIG_MPEG4_VDPAU_HWACCEL HWACCEL_VDPAU(mpeg4), #endif #if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL HWACCEL_VIDEOTOOLBOX(mpeg4), #endif NULL }, };
./CrossVul/dataset_final_sorted/CWE-476/c/good_216_0
crossvul-cpp_data_bad_1836_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO N N SSSSS TTTTT IIIII TTTTT U U TTTTT EEEEE % % C O O NN N SS T I T U U T E % % C O O N N N ESSS T I T U U T EEE % % C O O N NN SS T I T U U T E % % CCCC OOO N N SSSSS T IIIII T UUU T EEEEE % % % % % % MagickCore Methods to Consitute an Image % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright 1999-2015 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 "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/client.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/constitute-private.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/identify.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/timer.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n s t i t u t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConstituteImage() returns an image from the pixel data you supply. % The pixel data must be in scanline order top-to-bottom. The data can be % char, short int, int, float, or double. Float and double require the % pixels to be normalized [0..1], otherwise [0..QuantumRange]. For example, to % create a 640x480 image from unsigned red-green-blue character data, use: % % image = ConstituteImage(640,480,"RGB",CharPixel,pixels,&exception); % % The format of the ConstituteImage method is: % % Image *ConstituteImage(const size_t columns,const size_t rows, % const char *map,const StorageType storage,const void *pixels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o columns: width in pixels of the image. % % o rows: height in pixels of the image. % % o map: This string reflects the expected ordering of the pixel array. % It can be any combination or order of R = red, G = green, B = blue, % A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, % Y = yellow, M = magenta, K = black, I = intensity (for grayscale), % P = pad. % % o storage: Define the data type of the pixels. Float and double types are % expected to be normalized [0..1] otherwise [0..QuantumRange]. Choose % from these types: CharPixel, DoublePixel, FloatPixel, IntegerPixel, % LongPixel, QuantumPixel, or ShortPixel. % % o pixels: This array of values contain the pixel components as defined by % map and type. You must preallocate this array where the expected % length varies depending on the values of width, height, map, and type. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConstituteImage(const size_t columns,const size_t rows, const char *map,const StorageType storage,const void *pixels, ExceptionInfo *exception) { Image *image; MagickBooleanType status; /* Allocate image structure. */ assert(map != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",map); assert(pixels != (void *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage((ImageInfo *) NULL,exception); if (image == (Image *) NULL) return((Image *) NULL); if ((columns == 0) || (rows == 0)) ThrowImageException(OptionError,"NonZeroWidthAndHeightRequired"); image->columns=columns; image->rows=rows; (void) SetImageBackgroundColor(image,exception); status=ImportImagePixels(image,0,0,columns,rows,map,storage,pixels,exception); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P i n g I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PingImage() returns all the properties of an image or image sequence % except for the pixels. It is much faster and consumes far less memory % than ReadImage(). On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the PingImage method is: % % Image *PingImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Ping the image defined by the file or filename members of % this structure. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static size_t PingStream(const Image *magick_unused(image), const void *magick_unused(pixels),const size_t columns) { return(columns); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport Image *PingImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; ImageInfo *ping_info; assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); ping_info=CloneImageInfo(image_info); ping_info->ping=MagickTrue; image=ReadStream(ping_info,&PingStream,exception); if (image != (Image *) NULL) { ResetTimer(&image->timer); if (ping_info->verbose != MagickFalse) (void) IdentifyImage(image,stdout,MagickFalse,exception); } ping_info=DestroyImageInfo(ping_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P i n g I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PingImages() pings one or more images and returns them as an image list. % % The format of the PingImage method is: % % Image *PingImages(ImageInfo *image_info,const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o filename: the image filename. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PingImages(ImageInfo *image_info,const char *filename, ExceptionInfo *exception) { char ping_filename[MagickPathExtent]; Image *image, *images; ImageInfo *read_info; /* Ping image list from a file. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); (void) SetImageOption(image_info,"filename",filename); (void) CopyMagickString(image_info->filename,filename,MagickPathExtent); (void) InterpretImageFilename(image_info,(Image *) NULL,image_info->filename, (int) image_info->scene,ping_filename,exception); if (LocaleCompare(ping_filename,image_info->filename) != 0) { ExceptionInfo *sans; ssize_t extent, scene; /* Images of the form image-%d.png[1-5]. */ read_info=CloneImageInfo(image_info); sans=AcquireExceptionInfo(); (void) SetImageInfo(read_info,0,sans); sans=DestroyExceptionInfo(sans); if (read_info->number_scenes == 0) { read_info=DestroyImageInfo(read_info); return(PingImage(image_info,exception)); } (void) CopyMagickString(ping_filename,read_info->filename,MagickPathExtent); images=NewImageList(); extent=(ssize_t) (read_info->scene+read_info->number_scenes); for (scene=(ssize_t) read_info->scene; scene < (ssize_t) extent; scene++) { (void) InterpretImageFilename(image_info,(Image *) NULL,ping_filename, (int) scene,read_info->filename,exception); image=PingImage(read_info,exception); if (image == (Image *) NULL) continue; AppendImageToList(&images,image); } read_info=DestroyImageInfo(read_info); return(images); } return(PingImage(image_info,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadImage() reads an image or image sequence from a file or file handle. % The method returns a NULL if there is a memory shortage or if the image % cannot be read. On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the ReadImage method is: % % Image *ReadImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Read the image defined by the file or filename members of % this structure. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReadImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent], magick[MagickPathExtent], magick_filename[MagickPathExtent]; const char *value; const DelegateInfo *delegate_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; GeometryInfo geometry_info; Image *image, *next; ImageInfo *read_info; MagickStatusType flags; PolicyDomain domain; PolicyRights rights; /* Determine image type from filename prefix or suffix (e.g. image.jpg). */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image_info->filename != (char *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); read_info=CloneImageInfo(image_info); (void) CopyMagickString(magick_filename,read_info->filename,MagickPathExtent); (void) SetImageInfo(read_info,0,exception); (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) CopyMagickString(magick,read_info->magick,MagickPathExtent); domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,read_info->magick) == MagickFalse) { errno=EPERM; (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, "NotAuthorized","`%s'",read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } /* Call appropriate image reader based on image type. */ sans_exception=AcquireExceptionInfo(); magick_info=GetMagickInfo(read_info->magick,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (magick_info != (const MagickInfo *) NULL) { if (GetMagickEndianSupport(magick_info) == MagickFalse) read_info->endian=UndefinedEndian; else if ((image_info->endian == UndefinedEndian) && (GetMagickRawSupport(magick_info) != MagickFalse)) { unsigned long lsb_first; lsb_first=1; read_info->endian=(*(char *) &lsb_first) == 1 ? LSBEndian : MSBEndian; } } if ((magick_info != (const MagickInfo *) NULL) && (GetMagickSeekableStream(magick_info) != MagickFalse)) { MagickBooleanType status; image=AcquireImage(read_info,exception); (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return((Image *) NULL); } if (IsBlobSeekable(image) == MagickFalse) { /* Coder requires a seekable stream. */ *read_info->filename='\0'; status=ImageToFile(image,read_info->filename,exception); if (status == MagickFalse) { (void) CloseBlob(image); read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return((Image *) NULL); } read_info->temporary=MagickTrue; } (void) CloseBlob(image); image=DestroyImage(image); } image=NewImageList(); if ((magick_info == (const MagickInfo *) NULL) || (GetImageDecoder(magick_info) == (DecodeImageHandler *) NULL)) { delegate_info=GetDelegateInfo(read_info->magick,(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) SetImageInfo(read_info,0,exception); (void) CopyMagickString(read_info->filename,filename, MagickPathExtent); magick_info=GetMagickInfo(read_info->magick,exception); } } if ((magick_info != (const MagickInfo *) NULL) && (GetImageDecoder(magick_info) != (DecodeImageHandler *) NULL)) { if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); image=GetImageDecoder(magick_info)(read_info,exception); if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } else { delegate_info=GetDelegateInfo(read_info->magick,(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'", read_info->magick); if (read_info->temporary != MagickFalse) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } /* Let our decoding delegate process the image. */ image=AcquireImage(read_info,exception); if (image == (Image *) NULL) { read_info=DestroyImageInfo(read_info); return((Image *) NULL); } (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); *read_info->filename='\0'; if (GetDelegateThreadSupport(delegate_info) == MagickFalse) LockSemaphoreInfo(delegate_info->semaphore); (void) InvokeDelegate(read_info,image,read_info->magick,(char *) NULL, exception); if (GetDelegateThreadSupport(delegate_info) == MagickFalse) UnlockSemaphoreInfo(delegate_info->semaphore); image=DestroyImageList(image); read_info->temporary=MagickTrue; (void) SetImageInfo(read_info,0,exception); magick_info=GetMagickInfo(read_info->magick,exception); if ((magick_info == (const MagickInfo *) NULL) || (GetImageDecoder(magick_info) == (DecodeImageHandler *) NULL)) { if (IsPathAccessible(read_info->filename) != MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'", read_info->magick); else ThrowFileException(exception,FileOpenError,"UnableToOpenFile", read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); image=(Image *) (GetImageDecoder(magick_info))(read_info,exception); if (GetMagickDecoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } if (read_info->temporary != MagickFalse) { (void) RelinquishUniqueFileResource(read_info->filename); read_info->temporary=MagickFalse; if (image != (Image *) NULL) (void) CopyMagickString(image->filename,filename,MagickPathExtent); } if (image == (Image *) NULL) { read_info=DestroyImageInfo(read_info); return(image); } if (exception->severity >= ErrorException) (void) LogMagickEvent(ExceptionEvent,GetMagickModule(), "Coder (%s) generated an image despite an error (%d), " "notify the developers",image->magick,exception->severity); if (IsBlobTemporary(image) != MagickFalse) (void) RelinquishUniqueFileResource(read_info->filename); if ((GetNextImageInList(image) != (Image *) NULL) && (IsSceneGeometry(read_info->scenes,MagickFalse) != MagickFalse)) { Image *clones; clones=CloneImages(image,read_info->scenes,exception); if (clones == (Image *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SubimageSpecificationReturnsNoImages","`%s'",read_info->filename); else { image=DestroyImageList(image); image=GetFirstImageInList(clones); } } for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { char magick_path[MagickPathExtent], *property, timestamp[MagickPathExtent]; const char *option; const StringInfo *profile; next->taint=MagickFalse; GetPathComponent(magick_filename,MagickPath,magick_path); if (*magick_path == '\0' && *next->magick == '\0') (void) CopyMagickString(next->magick,magick,MagickPathExtent); (void) CopyMagickString(next->magick_filename,magick_filename, MagickPathExtent); if (IsBlobTemporary(image) != MagickFalse) (void) CopyMagickString(next->filename,filename,MagickPathExtent); if (next->magick_columns == 0) next->magick_columns=next->columns; if (next->magick_rows == 0) next->magick_rows=next->rows; value=GetImageProperty(next,"tiff:Orientation",exception); if (value == (char *) NULL) value=GetImageProperty(next,"exif:Orientation",exception); if (value != (char *) NULL) { next->orientation=(OrientationType) StringToLong(value); (void) DeleteImageProperty(next,"tiff:Orientation"); (void) DeleteImageProperty(next,"exif:Orientation"); } value=GetImageProperty(next,"exif:XResolution",exception); if (value != (char *) NULL) { geometry_info.rho=next->resolution.x; geometry_info.sigma=1.0; flags=ParseGeometry(value,&geometry_info); if (geometry_info.sigma != 0) next->resolution.x=geometry_info.rho/geometry_info.sigma; (void) DeleteImageProperty(next,"exif:XResolution"); } value=GetImageProperty(next,"exif:YResolution",exception); if (value != (char *) NULL) { geometry_info.rho=next->resolution.y; geometry_info.sigma=1.0; flags=ParseGeometry(value,&geometry_info); if (geometry_info.sigma != 0) next->resolution.y=geometry_info.rho/geometry_info.sigma; (void) DeleteImageProperty(next,"exif:YResolution"); } value=GetImageProperty(next,"tiff:ResolutionUnit",exception); if (value == (char *) NULL) value=GetImageProperty(next,"exif:ResolutionUnit",exception); if (value != (char *) NULL) { next->units=(ResolutionType) (StringToLong(value)-1); (void) DeleteImageProperty(next,"exif:ResolutionUnit"); (void) DeleteImageProperty(next,"tiff:ResolutionUnit"); } if (next->page.width == 0) next->page.width=next->columns; if (next->page.height == 0) next->page.height=next->rows; option=GetImageOption(read_info,"caption"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"caption",property,exception); property=DestroyString(property); } option=GetImageOption(read_info,"comment"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"comment",property,exception); property=DestroyString(property); } option=GetImageOption(read_info,"label"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"label",property,exception); property=DestroyString(property); } if (LocaleCompare(next->magick,"TEXT") == 0) (void) ParseAbsoluteGeometry("0x0+0+0",&next->page); if ((read_info->extract != (char *) NULL) && (read_info->stream == (StreamHandler) NULL)) { RectangleInfo geometry; flags=ParseAbsoluteGeometry(read_info->extract,&geometry); if ((next->columns != geometry.width) || (next->rows != geometry.height)) { if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { Image *crop_image; crop_image=CropImage(next,&geometry,exception); if (crop_image != (Image *) NULL) ReplaceImageInList(&next,crop_image); } else if (((flags & WidthValue) != 0) || ((flags & HeightValue) != 0)) { Image *size_image; flags=ParseRegionGeometry(next,read_info->extract,&geometry, exception); size_image=ResizeImage(next,geometry.width,geometry.height, next->filter,exception); if (size_image != (Image *) NULL) ReplaceImageInList(&next,size_image); } } } profile=GetImageProfile(next,"icc"); if (profile == (const StringInfo *) NULL) profile=GetImageProfile(next,"icm"); profile=GetImageProfile(next,"iptc"); if (profile == (const StringInfo *) NULL) profile=GetImageProfile(next,"8bim"); (void) FormatMagickTime(GetBlobProperties(next)->st_mtime,MagickPathExtent, timestamp); (void) SetImageProperty(next,"date:modify",timestamp,exception); (void) FormatMagickTime(GetBlobProperties(next)->st_ctime,MagickPathExtent, timestamp); (void) SetImageProperty(next,"date:create",timestamp,exception); option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (next->delay > (size_t) floor(geometry_info.rho+0.5)) next->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (next->delay < (size_t) floor(geometry_info.rho+0.5)) next->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else next->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) next->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) next->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); if (read_info->verbose != MagickFalse) (void) IdentifyImage(next,stderr,MagickFalse,exception); image=next; } read_info=DestroyImageInfo(read_info); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadImages() reads one or more images and returns them as an image list. % % The format of the ReadImage method is: % % Image *ReadImages(ImageInfo *image_info,const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o filename: the image filename. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReadImages(ImageInfo *image_info,const char *filename, ExceptionInfo *exception) { char read_filename[MagickPathExtent]; Image *image, *images; ImageInfo *read_info; /* Read image list from a file. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; (void) SetImageOption(read_info,"filename",filename); (void) CopyMagickString(read_info->filename,filename,MagickPathExtent); (void) InterpretImageFilename(read_info,(Image *) NULL,filename, (int) read_info->scene,read_filename,exception); if (LocaleCompare(read_filename,read_info->filename) != 0) { ExceptionInfo *sans; ssize_t extent, scene; /* Images of the form image-%d.png[1-5]. */ sans=AcquireExceptionInfo(); (void) SetImageInfo(read_info,0,sans); sans=DestroyExceptionInfo(sans); if (read_info->number_scenes == 0) { read_info=DestroyImageInfo(read_info); return(ReadImage(image_info,exception)); } (void) CopyMagickString(read_filename,read_info->filename,MagickPathExtent); images=NewImageList(); extent=(ssize_t) (read_info->scene+read_info->number_scenes); for (scene=(ssize_t) read_info->scene; scene < (ssize_t) extent; scene++) { (void) InterpretImageFilename(image_info,(Image *) NULL,read_filename, (int) scene,read_info->filename,exception); image=ReadImage(read_info,exception); if (image == (Image *) NULL) continue; AppendImageToList(&images,image); } read_info=DestroyImageInfo(read_info); return(images); } image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d I n l i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadInlineImage() reads a Base64-encoded inline image or image sequence. % The method returns a NULL if there is a memory shortage or if the image % cannot be read. On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the ReadInlineImage method is: % % Image *ReadInlineImage(const ImageInfo *image_info,const char *content, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o content: the image encoded in Base64. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReadInlineImage(const ImageInfo *image_info, const char *content,ExceptionInfo *exception) { Image *image; ImageInfo *read_info; unsigned char *blob; size_t length; register const char *p; /* Skip over header (e.g. data:image/gif;base64,). */ image=NewImageList(); for (p=content; (*p != ',') && (*p != '\0'); p++) ; if (*p == '\0') ThrowReaderException(CorruptImageError,"CorruptImage"); p++; length=0; blob=Base64Decode(p,&length); if (length == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); *read_info->filename='\0'; *read_info->magick='\0'; image=BlobToImage(read_info,blob,length,exception); blob=(unsigned char *) RelinquishMagickMemory(blob); read_info=DestroyImageInfo(read_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteImage() writes an image or an image sequence to a file or file handle. % If writing to a file is on disk, the name is defined by the filename member % of the image structure. WriteImage() returns MagickFalse is there is a % memory shortage or if the image cannot be written. Check the exception % member of image to determine the cause for any failure. % % The format of the WriteImage method is: % % MagickBooleanType WriteImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WriteImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; const char *option; const DelegateInfo *delegate_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType status, temporary; PolicyDomain domain; PolicyRights rights; /* Determine image type from filename prefix or suffix (e.g. image.jpg). */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); sans_exception=AcquireExceptionInfo(); write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,image->filename,MagickPathExtent); (void) SetImageInfo(write_info,1,sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); (void) CopyMagickString(image->filename,write_info->filename,MagickPathExtent); domain=CoderPolicyDomain; rights=WritePolicyRights; if (IsRightsAuthorized(domain,rights,write_info->magick) == MagickFalse) { sans_exception=DestroyExceptionInfo(sans_exception); write_info=DestroyImageInfo(write_info); errno=EPERM; ThrowBinaryException(PolicyError,"NotAuthorized",filename); } /* Call appropriate image reader based on image type. */ magick_info=GetMagickInfo(write_info->magick,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (magick_info != (const MagickInfo *) NULL) { if (GetMagickEndianSupport(magick_info) == MagickFalse) image->endian=UndefinedEndian; else if ((image_info->endian == UndefinedEndian) && (GetMagickRawSupport(magick_info) != MagickFalse)) { unsigned long lsb_first; lsb_first=1; image->endian=(*(char *) &lsb_first) == 1 ? LSBEndian : MSBEndian; } } (void) SyncImageProfiles(image); DisassociateImageStream(image); option=GetImageOption(image_info,"delegate:bimodal"); if ((IfMagickTrue(IsStringTrue(option))) && (write_info->page == (char *) NULL) && (GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) == (Image *) NULL) && (IfMagickFalse(IsTaintImage(image))) ) { delegate_info=GetDelegateInfo(image->magick,write_info->magick,exception); if ((delegate_info != (const DelegateInfo *) NULL) && (GetDelegateMode(delegate_info) == 0) && (IsPathAccessible(image->magick_filename) != MagickFalse)) { /* Process image with bi-modal delegate. */ (void) CopyMagickString(image->filename,image->magick_filename, MagickPathExtent); status=InvokeDelegate(write_info,image,image->magick, write_info->magick,exception); write_info=DestroyImageInfo(write_info); (void) CopyMagickString(image->filename,filename,MagickPathExtent); return(status); } } status=MagickFalse; temporary=MagickFalse; if ((magick_info != (const MagickInfo *) NULL) && (GetMagickSeekableStream(magick_info) != MagickFalse)) { char image_filename[MagickPathExtent]; (void) CopyMagickString(image_filename,image->filename,MagickPathExtent); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); (void) CopyMagickString(image->filename, image_filename,MagickPathExtent); if (status != MagickFalse) { if (IsBlobSeekable(image) == MagickFalse) { /* A seekable stream is required by the encoder. */ write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->filename,image->filename, MagickPathExtent); (void) AcquireUniqueFilename(image->filename); temporary=MagickTrue; } (void) CloseBlob(image); } } if ((magick_info != (const MagickInfo *) NULL) && (GetImageEncoder(magick_info) != (EncodeImageHandler *) NULL)) { /* Call appropriate image writer based on image type. */ if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); status=GetImageEncoder(magick_info)(write_info,image,exception); if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } else { delegate_info=GetDelegateInfo((char *) NULL,write_info->magick,exception); if (delegate_info != (DelegateInfo *) NULL) { /* Process the image with delegate. */ *write_info->filename='\0'; if (GetDelegateThreadSupport(delegate_info) == MagickFalse) LockSemaphoreInfo(delegate_info->semaphore); status=InvokeDelegate(write_info,image,(char *) NULL, write_info->magick,exception); if (GetDelegateThreadSupport(delegate_info) == MagickFalse) UnlockSemaphoreInfo(delegate_info->semaphore); (void) CopyMagickString(image->filename,filename,MagickPathExtent); } else { sans_exception=AcquireExceptionInfo(); magick_info=GetMagickInfo(write_info->magick,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if ((write_info->affirm == MagickFalse) && (magick_info == (const MagickInfo *) NULL)) { (void) CopyMagickString(write_info->magick,image->magick, MagickPathExtent); magick_info=GetMagickInfo(write_info->magick,exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetImageEncoder(magick_info) == (EncodeImageHandler *) NULL)) { char extension[MagickPathExtent]; GetPathComponent(image->filename,ExtensionPath,extension); if (*extension != '\0') magick_info=GetMagickInfo(extension,exception); else magick_info=GetMagickInfo(image->magick,exception); (void) CopyMagickString(image->filename,filename,MagickPathExtent); } if ((magick_info == (const MagickInfo *) NULL) || (GetImageEncoder(magick_info) == (EncodeImageHandler *) NULL)) { magick_info=GetMagickInfo(image->magick,exception); if ((magick_info == (const MagickInfo *) NULL) || (GetImageEncoder(magick_info) == (EncodeImageHandler *) NULL)) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoEncodeDelegateForThisImageFormat", "`%s'",write_info->magick); else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"NoEncodeDelegateForThisImageFormat", "`%s'",write_info->magick); } if ((magick_info != (const MagickInfo *) NULL) && (GetImageEncoder(magick_info) != (EncodeImageHandler *) NULL)) { /* Call appropriate image writer based on image type. */ if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) LockSemaphoreInfo(magick_info->semaphore); status=GetImageEncoder(magick_info)(write_info,image,exception); if (GetMagickEncoderThreadSupport(magick_info) == MagickFalse) UnlockSemaphoreInfo(magick_info->semaphore); } } } if (temporary != MagickFalse) { /* Copy temporary image file to permanent. */ status=OpenBlob(write_info,image,ReadBinaryBlobMode,exception); if (status != MagickFalse) { (void) RelinquishUniqueFileResource(write_info->filename); status=ImageToFile(image,write_info->filename,exception); } (void) CloseBlob(image); (void) RelinquishUniqueFileResource(image->filename); (void) CopyMagickString(image->filename,write_info->filename, MagickPathExtent); } if ((LocaleCompare(write_info->magick,"info") != 0) && (write_info->verbose != MagickFalse)) (void) IdentifyImage(image,stdout,MagickFalse,exception); write_info=DestroyImageInfo(write_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteImages() writes an image sequence into one or more files. While % WriteImage() can write an image sequence, it is limited to writing % the sequence into a single file using a format which supports multiple % frames. WriteImages(), however, does not have this limitation, instead it % generates multiple output files if necessary (or when requested). When % ImageInfo's adjoin flag is set to MagickFalse, the file name is expected % to include a printf-style formatting string for the frame number (e.g. % "image%02d.png"). % % The format of the WriteImages method is: % % MagickBooleanType WriteImages(const ImageInfo *image_info,Image *images, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o images: the image list. % % o filename: the image filename. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) if (p->scene >= GetNextImageInList(p)->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_1836_0
crossvul-cpp_data_good_4808_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_4808_0
crossvul-cpp_data_good_5337_0
/* Generic associative array implementation. * * See Documentation/assoc_array.txt for information. * * Copyright (C) 2013 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. */ //#define DEBUG #include <linux/rcupdate.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/assoc_array_priv.h> /* * Iterate over an associative array. The caller must hold the RCU read lock * or better. */ static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root, const struct assoc_array_ptr *stop, int (*iterator)(const void *leaf, void *iterator_data), void *iterator_data) { const struct assoc_array_shortcut *shortcut; const struct assoc_array_node *node; const struct assoc_array_ptr *cursor, *ptr, *parent; unsigned long has_meta; int slot, ret; cursor = root; begin_node: if (assoc_array_ptr_is_shortcut(cursor)) { /* Descend through a shortcut */ shortcut = assoc_array_ptr_to_shortcut(cursor); smp_read_barrier_depends(); cursor = ACCESS_ONCE(shortcut->next_node); } node = assoc_array_ptr_to_node(cursor); smp_read_barrier_depends(); slot = 0; /* We perform two passes of each node. * * The first pass does all the leaves in this node. This means we * don't miss any leaves if the node is split up by insertion whilst * we're iterating over the branches rooted here (we may, however, see * some leaves twice). */ has_meta = 0; for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); has_meta |= (unsigned long)ptr; if (ptr && assoc_array_ptr_is_leaf(ptr)) { /* We need a barrier between the read of the pointer * and dereferencing the pointer - but only if we are * actually going to dereference it. */ smp_read_barrier_depends(); /* Invoke the callback */ ret = iterator(assoc_array_ptr_to_leaf(ptr), iterator_data); if (ret) return ret; } } /* The second pass attends to all the metadata pointers. If we follow * one of these we may find that we don't come back here, but rather go * back to a replacement node with the leaves in a different layout. * * We are guaranteed to make progress, however, as the slot number for * a particular portion of the key space cannot change - and we * continue at the back pointer + 1. */ if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE)) goto finished_node; slot = 0; continue_node: node = assoc_array_ptr_to_node(cursor); smp_read_barrier_depends(); for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); if (assoc_array_ptr_is_meta(ptr)) { cursor = ptr; goto begin_node; } } finished_node: /* Move up to the parent (may need to skip back over a shortcut) */ parent = ACCESS_ONCE(node->back_pointer); slot = node->parent_slot; if (parent == stop) return 0; if (assoc_array_ptr_is_shortcut(parent)) { shortcut = assoc_array_ptr_to_shortcut(parent); smp_read_barrier_depends(); cursor = parent; parent = ACCESS_ONCE(shortcut->back_pointer); slot = shortcut->parent_slot; if (parent == stop) return 0; } /* Ascend to next slot in parent node */ cursor = parent; slot++; goto continue_node; } /** * assoc_array_iterate - Pass all objects in the array to a callback * @array: The array to iterate over. * @iterator: The callback function. * @iterator_data: Private data for the callback function. * * Iterate over all the objects in an associative array. Each one will be * presented to the iterator function. * * If the array is being modified concurrently with the iteration then it is * possible that some objects in the array will be passed to the iterator * callback more than once - though every object should be passed at least * once. If this is undesirable then the caller must lock against modification * for the duration of this function. * * The function will return 0 if no objects were in the array or else it will * return the result of the last iterator function called. Iteration stops * immediately if any call to the iteration function results in a non-zero * return. * * The caller should hold the RCU read lock or better if concurrent * modification is possible. */ int assoc_array_iterate(const struct assoc_array *array, int (*iterator)(const void *object, void *iterator_data), void *iterator_data) { struct assoc_array_ptr *root = ACCESS_ONCE(array->root); if (!root) return 0; return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data); } enum assoc_array_walk_status { assoc_array_walk_tree_empty, assoc_array_walk_found_terminal_node, assoc_array_walk_found_wrong_shortcut, }; struct assoc_array_walk_result { struct { struct assoc_array_node *node; /* Node in which leaf might be found */ int level; int slot; } terminal_node; struct { struct assoc_array_shortcut *shortcut; int level; int sc_level; unsigned long sc_segments; unsigned long dissimilarity; } wrong_shortcut; }; /* * Navigate through the internal tree looking for the closest node to the key. */ static enum assoc_array_walk_status assoc_array_walk(const struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *cursor, *ptr; unsigned long sc_segments, dissimilarity; unsigned long segments; int level, sc_level, next_sc_level; int slot; pr_devel("-->%s()\n", __func__); cursor = ACCESS_ONCE(array->root); if (!cursor) return assoc_array_walk_tree_empty; level = 0; /* Use segments from the key for the new leaf to navigate through the * internal tree, skipping through nodes and shortcuts that are on * route to the destination. Eventually we'll come to a slot that is * either empty or contains a leaf at which point we've found a node in * which the leaf we're looking for might be found or into which it * should be inserted. */ jumped: segments = ops->get_key_chunk(index_key, level); pr_devel("segments[%d]: %lx\n", level, segments); if (assoc_array_ptr_is_shortcut(cursor)) goto follow_shortcut; consider_node: node = assoc_array_ptr_to_node(cursor); smp_read_barrier_depends(); slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK); slot &= ASSOC_ARRAY_FAN_MASK; ptr = ACCESS_ONCE(node->slots[slot]); pr_devel("consider slot %x [ix=%d type=%lu]\n", slot, level, (unsigned long)ptr & 3); if (!assoc_array_ptr_is_meta(ptr)) { /* The node doesn't have a node/shortcut pointer in the slot * corresponding to the index key that we have to follow. */ result->terminal_node.node = node; result->terminal_node.level = level; result->terminal_node.slot = slot; pr_devel("<--%s() = terminal_node\n", __func__); return assoc_array_walk_found_terminal_node; } if (assoc_array_ptr_is_node(ptr)) { /* There is a pointer to a node in the slot corresponding to * this index key segment, so we need to follow it. */ cursor = ptr; level += ASSOC_ARRAY_LEVEL_STEP; if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) goto consider_node; goto jumped; } /* There is a shortcut in the slot corresponding to the index key * segment. We follow the shortcut if its partial index key matches * this leaf's. Otherwise we need to split the shortcut. */ cursor = ptr; follow_shortcut: shortcut = assoc_array_ptr_to_shortcut(cursor); smp_read_barrier_depends(); pr_devel("shortcut to %d\n", shortcut->skip_to_level); sc_level = level + ASSOC_ARRAY_LEVEL_STEP; BUG_ON(sc_level > shortcut->skip_to_level); do { /* Check the leaf against the shortcut's index key a word at a * time, trimming the final word (the shortcut stores the index * key completely from the root to the shortcut's target). */ if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0) segments = ops->get_key_chunk(index_key, sc_level); sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT]; dissimilarity = segments ^ sc_segments; if (round_up(sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE) > shortcut->skip_to_level) { /* Trim segments that are beyond the shortcut */ int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK; dissimilarity &= ~(ULONG_MAX << shift); next_sc_level = shortcut->skip_to_level; } else { next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE; next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); } if (dissimilarity != 0) { /* This shortcut points elsewhere */ result->wrong_shortcut.shortcut = shortcut; result->wrong_shortcut.level = level; result->wrong_shortcut.sc_level = sc_level; result->wrong_shortcut.sc_segments = sc_segments; result->wrong_shortcut.dissimilarity = dissimilarity; return assoc_array_walk_found_wrong_shortcut; } sc_level = next_sc_level; } while (sc_level < shortcut->skip_to_level); /* The shortcut matches the leaf's index to this point. */ cursor = ACCESS_ONCE(shortcut->next_node); if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) { level = sc_level; goto jumped; } else { level = sc_level; goto consider_node; } } /** * assoc_array_find - Find an object by index key * @array: The associative array to search. * @ops: The operations to use. * @index_key: The key to the object. * * Find an object in an associative array by walking through the internal tree * to the node that should contain the object and then searching the leaves * there. NULL is returned if the requested object was not found in the array. * * The caller must hold the RCU read lock or better. */ void *assoc_array_find(const struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key) { struct assoc_array_walk_result result; const struct assoc_array_node *node; const struct assoc_array_ptr *ptr; const void *leaf; int slot; if (assoc_array_walk(array, ops, index_key, &result) != assoc_array_walk_found_terminal_node) return NULL; node = result.terminal_node.node; smp_read_barrier_depends(); /* If the target key is available to us, it's has to be pointed to by * the terminal node. */ for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); if (ptr && assoc_array_ptr_is_leaf(ptr)) { /* We need a barrier between the read of the pointer * and dereferencing the pointer - but only if we are * actually going to dereference it. */ leaf = assoc_array_ptr_to_leaf(ptr); smp_read_barrier_depends(); if (ops->compare_object(leaf, index_key)) return (void *)leaf; } } return NULL; } /* * Destructively iterate over an associative array. The caller must prevent * other simultaneous accesses. */ static void assoc_array_destroy_subtree(struct assoc_array_ptr *root, const struct assoc_array_ops *ops) { struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *cursor, *parent = NULL; int slot = -1; pr_devel("-->%s()\n", __func__); cursor = root; if (!cursor) { pr_devel("empty\n"); return; } move_to_meta: if (assoc_array_ptr_is_shortcut(cursor)) { /* Descend through a shortcut */ pr_devel("[%d] shortcut\n", slot); BUG_ON(!assoc_array_ptr_is_shortcut(cursor)); shortcut = assoc_array_ptr_to_shortcut(cursor); BUG_ON(shortcut->back_pointer != parent); BUG_ON(slot != -1 && shortcut->parent_slot != slot); parent = cursor; cursor = shortcut->next_node; slot = -1; BUG_ON(!assoc_array_ptr_is_node(cursor)); } pr_devel("[%d] node\n", slot); node = assoc_array_ptr_to_node(cursor); BUG_ON(node->back_pointer != parent); BUG_ON(slot != -1 && node->parent_slot != slot); slot = 0; continue_node: pr_devel("Node %p [back=%p]\n", node, node->back_pointer); for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { struct assoc_array_ptr *ptr = node->slots[slot]; if (!ptr) continue; if (assoc_array_ptr_is_meta(ptr)) { parent = cursor; cursor = ptr; goto move_to_meta; } if (ops) { pr_devel("[%d] free leaf\n", slot); ops->free_object(assoc_array_ptr_to_leaf(ptr)); } } parent = node->back_pointer; slot = node->parent_slot; pr_devel("free node\n"); kfree(node); if (!parent) return; /* Done */ /* Move back up to the parent (may need to free a shortcut on * the way up) */ if (assoc_array_ptr_is_shortcut(parent)) { shortcut = assoc_array_ptr_to_shortcut(parent); BUG_ON(shortcut->next_node != cursor); cursor = parent; parent = shortcut->back_pointer; slot = shortcut->parent_slot; pr_devel("free shortcut\n"); kfree(shortcut); if (!parent) return; BUG_ON(!assoc_array_ptr_is_node(parent)); } /* Ascend to next slot in parent node */ pr_devel("ascend to %p[%d]\n", parent, slot); cursor = parent; node = assoc_array_ptr_to_node(cursor); slot++; goto continue_node; } /** * assoc_array_destroy - Destroy an associative array * @array: The array to destroy. * @ops: The operations to use. * * Discard all metadata and free all objects in an associative array. The * array will be empty and ready to use again upon completion. This function * cannot fail. * * The caller must prevent all other accesses whilst this takes place as no * attempt is made to adjust pointers gracefully to permit RCU readlock-holding * accesses to continue. On the other hand, no memory allocation is required. */ void assoc_array_destroy(struct assoc_array *array, const struct assoc_array_ops *ops) { assoc_array_destroy_subtree(array->root, ops); array->root = NULL; } /* * Handle insertion into an empty tree. */ static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit) { struct assoc_array_node *new_n0; pr_devel("-->%s()\n", __func__); new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); edit->leaf_p = &new_n0->slots[0]; edit->adjust_count_on = new_n0; edit->set[0].ptr = &edit->array->root; edit->set[0].to = assoc_array_node_to_ptr(new_n0); pr_devel("<--%s() = ok [no root]\n", __func__); return true; } /* * Handle insertion into a terminal node. */ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0; struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; int slot, next_slot, free_slot, i, j; node = result->terminal_node.node; level = result->terminal_node.level; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel("-->%s()\n", __func__); /* We arrived at a node which doesn't have an onward node or shortcut * pointer that we have to follow. This means that (a) the leaf we * want must go here (either by insertion or replacement) or (b) we * need to split this node and insert in one of the fragments. */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's * a matching one we should replace in place. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (!ptr) { free_slot = i; continue; } if (assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { pr_devel("replace in slot %d\n", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; pr_devel("<--%s() = ok [replace]\n", __func__); return true; } } /* If there is a free slot in this node then we can just insert the * leaf here. */ if (free_slot >= 0) { pr_devel("insert in free slot %d\n", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; pr_devel("<--%s() = ok [insert]\n", __func__); return true; } /* The node has no spare slots - so we're either going to have to split * it or insert another node before it. * * Whatever, we're going to need at least two new nodes - so allocate * those now. We may also need a new shortcut, but we deal with that * when we need it. */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n1) return false; edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); /* We need to find out how similar the leaves are. */ pr_devel("no spare slots\n"); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { edit->segment_cache[i] = 0xff; have_meta = true; continue; } base_seg = ops->get_object_key_chunk( assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } if (have_meta) { pr_devel("have meta\n"); goto split_node; } /* The node contains only leaves */ dissimilarity = 0; base_seg = edit->segment_cache[0]; for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) dissimilarity |= edit->segment_cache[i] ^ base_seg; pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { /* The old leaves all cluster in the same slot. We will need * to insert a shortcut if the new node wants to cluster with them. */ if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) goto all_leaves_cluster_together; /* Otherwise we can just insert a new node ahead of the old * one. */ goto present_leaves_cluster_but_not_new_leaf; } split_node: pr_devel("split node\n"); /* We need to split the current node; we know that the node doesn't * simply contain a full set of leaves that cluster together (it * contains meta pointers and/or non-clustering leaves). * * We need to expel at least two leaves out of a set consisting of the * leaves in the node and the new leaf. * * We need a new node (n0) to replace the current one and a new node to * take the expelled nodes (n1). */ edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: pr_devel("do_split_node\n"); new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; /* Begin by finding two matching leaves. There have to be at least two * that match - even if there are meta pointers - because any leaf that * would match a slot with a meta pointer in it must be somewhere * behind that meta pointer and cannot be here. Further, given N * remaining leaf slots, we now have N+1 leaves to go in them. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { slot = edit->segment_cache[i]; if (slot != 0xff) for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) if (edit->segment_cache[j] == slot) goto found_slot_for_multiple_occupancy; } found_slot_for_multiple_occupancy: pr_devel("same slot: %x %x [%02x]\n", i, j, slot); BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); new_n1->parent_slot = slot; /* Metadata pointers cannot change slot */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) if (assoc_array_ptr_is_meta(node->slots[i])) new_n0->slots[i] = node->slots[i]; else new_n0->slots[i] = NULL; BUG_ON(new_n0->slots[slot] != NULL); new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); /* Filter the leaf pointers between the new nodes */ free_slot = -1; next_slot = 0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (assoc_array_ptr_is_meta(node->slots[i])) continue; if (edit->segment_cache[i] == slot) { new_n1->slots[next_slot++] = node->slots[i]; new_n1->nr_leaves_on_branch++; } else { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); new_n0->slots[free_slot] = node->slots[i]; } } pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); edit->leaf_p = &new_n0->slots[free_slot]; edit->adjust_count_on = new_n0; } else { edit->leaf_p = &new_n1->slots[next_slot++]; edit->adjust_count_on = new_n1; } BUG_ON(next_slot <= 1); edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (edit->segment_cache[i] == 0xff) { ptr = node->slots[i]; BUG_ON(assoc_array_ptr_is_leaf(ptr)); if (assoc_array_ptr_is_node(ptr)) { side = assoc_array_ptr_to_node(ptr); edit->set_backpointers[i] = &side->back_pointer; } else { shortcut = assoc_array_ptr_to_shortcut(ptr); edit->set_backpointers[i] = &shortcut->back_pointer; } } } ptr = node->back_pointer; if (!ptr) edit->set[0].ptr = &edit->array->root; else if (assoc_array_ptr_is_node(ptr)) edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; else edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [split node]\n", __func__); return true; present_leaves_cluster_but_not_new_leaf: /* All the old leaves cluster in the same slot, but the new leaf wants * to go into a different slot, so we create a new node to hold the new * leaf and a pointer to a new node holding all the old leaves. */ pr_devel("present leaves cluster but not new leaf\n"); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = edit->segment_cache[0]; new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch; edit->adjust_count_on = new_n0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) new_n1->slots[i] = node->slots[i]; new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0); edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]]; edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot]; edit->set[0].to = assoc_array_node_to_ptr(new_n0); edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [insert node before]\n", __func__); return true; all_leaves_cluster_together: /* All the leaves, new and old, want to cluster together in this node * in the same slot, so we have to replace this node with a shortcut to * skip over the identical parts of the key and then place a pair of * nodes, one inside the other, at the end of the shortcut and * distribute the keys between them. * * Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * * We only need to make a single pass of N of the N+1 leaves because if * any keys differ between themselves at bit X then at least one of * them must also differ with the base key at bit X or before. */ pr_devel("all leaves cluster together\n"); diff = INT_MAX; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), index_key); if (x < diff) { BUG_ON(x < 0); diff = x; } } BUG_ON(diff == INT_MAX); BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel("skip_to_level = %d [diff %d]\n", level, diff); BUG_ON(level <= 0); for (i = 0; i < keylen; i++) new_s0->index_key[i] = ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); new_s0->index_key[keylen - 1] &= ~blank; /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; } /* * Handle insertion into the middle of a shortcut. */ static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0, *new_s1; struct assoc_array_node *node, *new_n0, *side; unsigned long sc_segments, dissimilarity, blank; size_t keylen; int level, sc_level, diff; int sc_slot; shortcut = result->wrong_shortcut.shortcut; level = result->wrong_shortcut.level; sc_level = result->wrong_shortcut.sc_level; sc_segments = result->wrong_shortcut.sc_segments; dissimilarity = result->wrong_shortcut.dissimilarity; pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n", __func__, level, dissimilarity, sc_level); /* We need to split a shortcut and insert a node between the two * pieces. Zero-length pieces will be dispensed with entirely. * * First of all, we need to find out in which level the first * difference was. */ diff = __ffs(dissimilarity); diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK; diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK; pr_devel("diff=%d\n", diff); if (!shortcut->back_pointer) { edit->set[0].ptr = &edit->array->root; } else if (assoc_array_ptr_is_node(shortcut->back_pointer)) { node = assoc_array_ptr_to_node(shortcut->back_pointer); edit->set[0].ptr = &node->slots[shortcut->parent_slot]; } else { BUG(); } edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut); /* Create a new node now since we're going to need it anyway */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); edit->adjust_count_on = new_n0; /* Insert a new shortcut before the new node if this segment isn't of * zero length - otherwise we just connect the new node directly to the * parent. */ level += ASSOC_ARRAY_LEVEL_STEP; if (diff > level) { pr_devel("pre-shortcut %d...%d\n", level, diff); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = shortcut->back_pointer; new_s0->parent_slot = shortcut->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_s0->skip_to_level = diff; new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; memcpy(new_s0->index_key, shortcut->index_key, keylen * sizeof(unsigned long)); blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); new_s0->index_key[keylen - 1] &= ~blank; } else { pr_devel("no pre-shortcut\n"); edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = shortcut->back_pointer; new_n0->parent_slot = shortcut->parent_slot; } side = assoc_array_ptr_to_node(shortcut->next_node); new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch; /* We need to know which slot in the new node is going to take a * metadata pointer. */ sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); sc_slot &= ASSOC_ARRAY_FAN_MASK; pr_devel("new slot %lx >> %d -> %d\n", sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot); /* Determine whether we need to follow the new node with a replacement * for the current shortcut. We could in theory reuse the current * shortcut if its parent slot number doesn't change - but that's a * 1-in-16 chance so not worth expending the code upon. */ level = diff + ASSOC_ARRAY_LEVEL_STEP; if (level < shortcut->skip_to_level) { pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level); keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s1 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s1) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1); new_s1->back_pointer = assoc_array_node_to_ptr(new_n0); new_s1->parent_slot = sc_slot; new_s1->next_node = shortcut->next_node; new_s1->skip_to_level = shortcut->skip_to_level; new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1); memcpy(new_s1->index_key, shortcut->index_key, keylen * sizeof(unsigned long)); edit->set[1].ptr = &side->back_pointer; edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1); } else { pr_devel("no post-shortcut\n"); /* We don't have to replace the pointed-to node as long as we * use memory barriers to make sure the parent slot number is * changed before the back pointer (the parent slot number is * irrelevant to the old parent shortcut). */ new_n0->slots[sc_slot] = shortcut->next_node; edit->set_parent_slot[0].p = &side->parent_slot; edit->set_parent_slot[0].to = sc_slot; edit->set[1].ptr = &side->back_pointer; edit->set[1].to = assoc_array_node_to_ptr(new_n0); } /* Install the new leaf in a spare slot in the new node. */ if (sc_slot == 0) edit->leaf_p = &new_n0->slots[1]; else edit->leaf_p = &new_n0->slots[0]; pr_devel("<--%s() = ok [split shortcut]\n", __func__); return edit; } /** * assoc_array_insert - Script insertion of an object into an associative array * @array: The array to insert into. * @ops: The operations to use. * @index_key: The key to insert at. * @object: The object to insert. * * Precalculate and preallocate a script for the insertion or replacement of an * object in an associative array. This results in an edit script that can * either be applied or cancelled. * * The function returns a pointer to an edit script or -ENOMEM. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ struct assoc_array_edit *assoc_array_insert(struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key, void *object) { struct assoc_array_walk_result result; struct assoc_array_edit *edit; pr_devel("-->%s()\n", __func__); /* The leaf pointer we're given must not have the bottom bit set as we * use those for type-marking the pointer. NULL pointers are also not * allowed as they indicate an empty slot but we have to allow them * here as they can be updated later. */ BUG_ON(assoc_array_ptr_is_meta(object)); edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return ERR_PTR(-ENOMEM); edit->array = array; edit->ops = ops; edit->leaf = assoc_array_leaf_to_ptr(object); edit->adjust_count_by = 1; switch (assoc_array_walk(array, ops, index_key, &result)) { case assoc_array_walk_tree_empty: /* Allocate a root node if there isn't one yet */ if (!assoc_array_insert_in_empty_tree(edit)) goto enomem; return edit; case assoc_array_walk_found_terminal_node: /* We found a node that doesn't have a node/shortcut pointer in * the slot corresponding to the index key that we have to * follow. */ if (!assoc_array_insert_into_terminal_node(edit, ops, index_key, &result)) goto enomem; return edit; case assoc_array_walk_found_wrong_shortcut: /* We found a shortcut that didn't match our key in a slot we * needed to follow. */ if (!assoc_array_insert_mid_shortcut(edit, ops, &result)) goto enomem; return edit; } enomem: /* Clean up after an out of memory error */ pr_devel("enomem\n"); assoc_array_cancel_edit(edit); return ERR_PTR(-ENOMEM); } /** * assoc_array_insert_set_object - Set the new object pointer in an edit script * @edit: The edit script to modify. * @object: The object pointer to set. * * Change the object to be inserted in an edit script. The object pointed to * by the old object is not freed. This must be done prior to applying the * script. */ void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object) { BUG_ON(!object); edit->leaf = assoc_array_leaf_to_ptr(object); } struct assoc_array_delete_collapse_context { struct assoc_array_node *node; const void *skip_leaf; int slot; }; /* * Subtree collapse to node iterator. */ static int assoc_array_delete_collapse_iterator(const void *leaf, void *iterator_data) { struct assoc_array_delete_collapse_context *collapse = iterator_data; if (leaf == collapse->skip_leaf) return 0; BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT); collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf); return 0; } /** * assoc_array_delete - Script deletion of an object from an associative array * @array: The array to search. * @ops: The operations to use. * @index_key: The key to the object. * * Precalculate and preallocate a script for the deletion of an object from an * associative array. This results in an edit script that can either be * applied or cancelled. * * The function returns a pointer to an edit script if the object was found, * NULL if the object was not found or -ENOMEM. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, const struct assoc_array_ops *ops, const void *index_key) { struct assoc_array_delete_collapse_context collapse; struct assoc_array_walk_result result; struct assoc_array_node *node, *new_n0; struct assoc_array_edit *edit; struct assoc_array_ptr *ptr; bool has_meta; int slot, i; pr_devel("-->%s()\n", __func__); edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return ERR_PTR(-ENOMEM); edit->array = array; edit->ops = ops; edit->adjust_count_by = -1; switch (assoc_array_walk(array, ops, index_key, &result)) { case assoc_array_walk_found_terminal_node: /* We found a node that should contain the leaf we've been * asked to remove - *if* it's in the tree. */ pr_devel("terminal_node\n"); node = result.terminal_node.node; for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = node->slots[slot]; if (ptr && assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) goto found_leaf; } case assoc_array_walk_tree_empty: case assoc_array_walk_found_wrong_shortcut: default: assoc_array_cancel_edit(edit); pr_devel("not found\n"); return NULL; } found_leaf: BUG_ON(array->nr_leaves_on_tree <= 0); /* In the simplest form of deletion we just clear the slot and release * the leaf after a suitable interval. */ edit->dead_leaf = node->slots[slot]; edit->set[0].ptr = &node->slots[slot]; edit->set[0].to = NULL; edit->adjust_count_on = node; /* If that concludes erasure of the last leaf, then delete the entire * internal array. */ if (array->nr_leaves_on_tree == 1) { edit->set[1].ptr = &array->root; edit->set[1].to = NULL; edit->adjust_count_on = NULL; edit->excised_subtree = array->root; pr_devel("all gone\n"); return edit; } /* However, we'd also like to clear up some metadata blocks if we * possibly can. * * We go for a simple algorithm of: if this node has FAN_OUT or fewer * leaves in it, then attempt to collapse it - and attempt to * recursively collapse up the tree. * * We could also try and collapse in partially filled subtrees to take * up space in this node. */ if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { struct assoc_array_node *parent, *grandparent; struct assoc_array_ptr *ptr; /* First of all, we need to know if this node has metadata so * that we don't try collapsing if all the leaves are already * here. */ has_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { has_meta = true; break; } } pr_devel("leaves: %ld [m=%d]\n", node->nr_leaves_on_branch - 1, has_meta); /* Look further up the tree to see if we can collapse this node * into a more proximal node too. */ parent = node; collapse_up: pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); ptr = parent->back_pointer; if (!ptr) goto do_collapse; if (assoc_array_ptr_is_shortcut(ptr)) { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); ptr = s->back_pointer; if (!ptr) goto do_collapse; } grandparent = assoc_array_ptr_to_node(ptr); if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { parent = grandparent; goto collapse_up; } do_collapse: /* There's no point collapsing if the original node has no meta * pointers to discard and if we didn't merge into one of that * node's ancestry. */ if (has_meta || parent != node) { node = parent; /* Create a new node to collapse into */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) goto enomem; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; edit->adjust_count_on = new_n0; collapse.node = new_n0; collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); collapse.slot = 0; assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), node->back_pointer, assoc_array_delete_collapse_iterator, &collapse); pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); if (!node->back_pointer) { edit->set[1].ptr = &array->root; } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { BUG(); } else if (assoc_array_ptr_is_node(node->back_pointer)) { struct assoc_array_node *p = assoc_array_ptr_to_node(node->back_pointer); edit->set[1].ptr = &p->slots[node->parent_slot]; } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(node->back_pointer); edit->set[1].ptr = &s->next_node; } edit->set[1].to = assoc_array_node_to_ptr(new_n0); edit->excised_subtree = assoc_array_node_to_ptr(node); } } return edit; enomem: /* Clean up after an out of memory error */ pr_devel("enomem\n"); assoc_array_cancel_edit(edit); return ERR_PTR(-ENOMEM); } /** * assoc_array_clear - Script deletion of all objects from an associative array * @array: The array to clear. * @ops: The operations to use. * * Precalculate and preallocate a script for the deletion of all the objects * from an associative array. This results in an edit script that can either * be applied or cancelled. * * The function returns a pointer to an edit script if there are objects to be * deleted, NULL if there are no objects in the array or -ENOMEM. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ struct assoc_array_edit *assoc_array_clear(struct assoc_array *array, const struct assoc_array_ops *ops) { struct assoc_array_edit *edit; pr_devel("-->%s()\n", __func__); if (!array->root) return NULL; edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return ERR_PTR(-ENOMEM); edit->array = array; edit->ops = ops; edit->set[1].ptr = &array->root; edit->set[1].to = NULL; edit->excised_subtree = array->root; edit->ops_for_excised_subtree = ops; pr_devel("all gone\n"); return edit; } /* * Handle the deferred destruction after an applied edit. */ static void assoc_array_rcu_cleanup(struct rcu_head *head) { struct assoc_array_edit *edit = container_of(head, struct assoc_array_edit, rcu); int i; pr_devel("-->%s()\n", __func__); if (edit->dead_leaf) edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf)); for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++) if (edit->excised_meta[i]) kfree(assoc_array_ptr_to_node(edit->excised_meta[i])); if (edit->excised_subtree) { BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree)); if (assoc_array_ptr_is_node(edit->excised_subtree)) { struct assoc_array_node *n = assoc_array_ptr_to_node(edit->excised_subtree); n->back_pointer = NULL; } else { struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(edit->excised_subtree); s->back_pointer = NULL; } assoc_array_destroy_subtree(edit->excised_subtree, edit->ops_for_excised_subtree); } kfree(edit); } /** * assoc_array_apply_edit - Apply an edit script to an associative array * @edit: The script to apply. * * Apply an edit script to an associative array to effect an insertion, * deletion or clearance. As the edit script includes preallocated memory, * this is guaranteed not to fail. * * The edit script, dead objects and dead metadata will be scheduled for * destruction after an RCU grace period to permit those doing read-only * accesses on the array to continue to do so under the RCU read lock whilst * the edit is taking place. */ void assoc_array_apply_edit(struct assoc_array_edit *edit) { struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *ptr; int i; pr_devel("-->%s()\n", __func__); smp_wmb(); if (edit->leaf_p) *edit->leaf_p = edit->leaf; smp_wmb(); for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++) if (edit->set_parent_slot[i].p) *edit->set_parent_slot[i].p = edit->set_parent_slot[i].to; smp_wmb(); for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++) if (edit->set_backpointers[i]) *edit->set_backpointers[i] = edit->set_backpointers_to; smp_wmb(); for (i = 0; i < ARRAY_SIZE(edit->set); i++) if (edit->set[i].ptr) *edit->set[i].ptr = edit->set[i].to; if (edit->array->root == NULL) { edit->array->nr_leaves_on_tree = 0; } else if (edit->adjust_count_on) { node = edit->adjust_count_on; for (;;) { node->nr_leaves_on_branch += edit->adjust_count_by; ptr = node->back_pointer; if (!ptr) break; if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); ptr = shortcut->back_pointer; if (!ptr) break; } BUG_ON(!assoc_array_ptr_is_node(ptr)); node = assoc_array_ptr_to_node(ptr); } edit->array->nr_leaves_on_tree += edit->adjust_count_by; } call_rcu(&edit->rcu, assoc_array_rcu_cleanup); } /** * assoc_array_cancel_edit - Discard an edit script. * @edit: The script to discard. * * Free an edit script and all the preallocated data it holds without making * any changes to the associative array it was intended for. * * NOTE! In the case of an insertion script, this does _not_ release the leaf * that was to be inserted. That is left to the caller. */ void assoc_array_cancel_edit(struct assoc_array_edit *edit) { struct assoc_array_ptr *ptr; int i; pr_devel("-->%s()\n", __func__); /* Clean up after an out of memory error */ for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) { ptr = edit->new_meta[i]; if (ptr) { if (assoc_array_ptr_is_node(ptr)) kfree(assoc_array_ptr_to_node(ptr)); else kfree(assoc_array_ptr_to_shortcut(ptr)); } } kfree(edit); } /** * assoc_array_gc - Garbage collect an associative array. * @array: The array to clean. * @ops: The operations to use. * @iterator: A callback function to pass judgement on each object. * @iterator_data: Private data for the callback function. * * Collect garbage from an associative array and pack down the internal tree to * save memory. * * The iterator function is asked to pass judgement upon each object in the * array. If it returns false, the object is discard and if it returns true, * the object is kept. If it returns true, it must increment the object's * usage count (or whatever it needs to do to retain it) before returning. * * This function returns 0 if successful or -ENOMEM if out of memory. In the * latter case, the array is not changed. * * The caller should lock against other modifications and must continue to hold * the lock until assoc_array_apply_edit() has been called. * * Accesses to the tree may take place concurrently with this function, * provided they hold the RCU read lock. */ int assoc_array_gc(struct assoc_array *array, const struct assoc_array_ops *ops, bool (*iterator)(void *object, void *iterator_data), void *iterator_data) { struct assoc_array_shortcut *shortcut, *new_s; struct assoc_array_node *node, *new_n; struct assoc_array_edit *edit; struct assoc_array_ptr *cursor, *ptr; struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp; unsigned long nr_leaves_on_tree; int keylen, slot, nr_free, next_slot, i; pr_devel("-->%s()\n", __func__); if (!array->root) return 0; edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); if (!edit) return -ENOMEM; edit->array = array; edit->ops = ops; edit->ops_for_excised_subtree = ops; edit->set[0].ptr = &array->root; edit->excised_subtree = array->root; new_root = new_parent = NULL; new_ptr_pp = &new_root; cursor = array->root; descend: /* If this point is a shortcut, then we need to duplicate it and * advance the target cursor. */ if (assoc_array_ptr_is_shortcut(cursor)) { shortcut = assoc_array_ptr_to_shortcut(cursor); keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s = kmalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s) goto enomem; pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); memcpy(new_s, shortcut, (sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long))); new_s->back_pointer = new_parent; new_s->parent_slot = shortcut->parent_slot; *new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s); new_ptr_pp = &new_s->next_node; cursor = shortcut->next_node; } /* Duplicate the node at this position */ node = assoc_array_ptr_to_node(cursor); new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n) goto enomem; pr_devel("dup node %p -> %p\n", node, new_n); new_n->back_pointer = new_parent; new_n->parent_slot = node->parent_slot; *new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n); new_ptr_pp = NULL; slot = 0; continue_node: /* Filter across any leaves and gc any subtrees */ for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = node->slots[slot]; if (!ptr) continue; if (assoc_array_ptr_is_leaf(ptr)) { if (iterator(assoc_array_ptr_to_leaf(ptr), iterator_data)) /* The iterator will have done any reference * counting on the object for us. */ new_n->slots[slot] = ptr; continue; } new_ptr_pp = &new_n->slots[slot]; cursor = ptr; goto descend; } pr_devel("-- compress node %p --\n", new_n); /* Count up the number of empty slots in this node and work out the * subtree leaf count. */ new_n->nr_leaves_on_branch = 0; nr_free = 0; for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = new_n->slots[slot]; if (!ptr) nr_free++; else if (assoc_array_ptr_is_leaf(ptr)) new_n->nr_leaves_on_branch++; } pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch); /* See what we can fold in */ next_slot = 0; for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { struct assoc_array_shortcut *s; struct assoc_array_node *child; ptr = new_n->slots[slot]; if (!ptr || assoc_array_ptr_is_leaf(ptr)) continue; s = NULL; if (assoc_array_ptr_is_shortcut(ptr)) { s = assoc_array_ptr_to_shortcut(ptr); ptr = s->next_node; } child = assoc_array_ptr_to_node(ptr); new_n->nr_leaves_on_branch += child->nr_leaves_on_branch; if (child->nr_leaves_on_branch <= nr_free + 1) { /* Fold the child node into this one */ pr_devel("[%d] fold node %lu/%d [nx %d]\n", slot, child->nr_leaves_on_branch, nr_free + 1, next_slot); /* We would already have reaped an intervening shortcut * on the way back up the tree. */ BUG_ON(s); new_n->slots[slot] = NULL; nr_free++; if (slot < next_slot) next_slot = slot; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { struct assoc_array_ptr *p = child->slots[i]; if (!p) continue; BUG_ON(assoc_array_ptr_is_meta(p)); while (new_n->slots[next_slot]) next_slot++; BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT); new_n->slots[next_slot++] = p; nr_free--; } kfree(child); } else { pr_devel("[%d] retain node %lu/%d [nx %d]\n", slot, child->nr_leaves_on_branch, nr_free + 1, next_slot); } } pr_devel("after: %lu\n", new_n->nr_leaves_on_branch); nr_leaves_on_tree = new_n->nr_leaves_on_branch; /* Excise this node if it is singly occupied by a shortcut */ if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) { for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) if ((ptr = new_n->slots[slot])) break; if (assoc_array_ptr_is_meta(ptr) && assoc_array_ptr_is_shortcut(ptr)) { pr_devel("excise node %p with 1 shortcut\n", new_n); new_s = assoc_array_ptr_to_shortcut(ptr); new_parent = new_n->back_pointer; slot = new_n->parent_slot; kfree(new_n); if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; new_root = ptr; goto gc_complete; } if (assoc_array_ptr_is_shortcut(new_parent)) { /* We can discard any preceding shortcut also */ struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(new_parent); pr_devel("excise preceding shortcut\n"); new_parent = new_s->back_pointer = s->back_pointer; slot = new_s->parent_slot = s->parent_slot; kfree(s); if (!new_parent) { new_s->back_pointer = NULL; new_s->parent_slot = 0; new_root = ptr; goto gc_complete; } } new_s->back_pointer = new_parent; new_s->parent_slot = slot; new_n = assoc_array_ptr_to_node(new_parent); new_n->slots[slot] = ptr; goto ascend_old_tree; } } /* Excise any shortcuts we might encounter that point to nodes that * only contain leaves. */ ptr = new_n->back_pointer; if (!ptr) goto gc_complete; if (assoc_array_ptr_is_shortcut(ptr)) { new_s = assoc_array_ptr_to_shortcut(ptr); new_parent = new_s->back_pointer; slot = new_s->parent_slot; if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { struct assoc_array_node *n; pr_devel("excise shortcut\n"); new_n->back_pointer = new_parent; new_n->parent_slot = slot; kfree(new_s); if (!new_parent) { new_root = assoc_array_node_to_ptr(new_n); goto gc_complete; } n = assoc_array_ptr_to_node(new_parent); n->slots[slot] = assoc_array_node_to_ptr(new_n); } } else { new_parent = ptr; } new_n = assoc_array_ptr_to_node(new_parent); ascend_old_tree: ptr = node->back_pointer; if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); slot = shortcut->parent_slot; cursor = shortcut->back_pointer; if (!cursor) goto gc_complete; } else { slot = node->parent_slot; cursor = ptr; } BUG_ON(!cursor); node = assoc_array_ptr_to_node(cursor); slot++; goto continue_node; gc_complete: edit->set[0].to = new_root; assoc_array_apply_edit(edit); array->nr_leaves_on_tree = nr_leaves_on_tree; return 0; enomem: pr_devel("enomem\n"); assoc_array_destroy_subtree(new_root, edit->ops); kfree(edit); return -ENOMEM; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_5337_0
crossvul-cpp_data_good_624_0
/* * TUN - Universal TUN/TAP device driver. * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.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. * * 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. * * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $ */ /* * Changes: * * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14 * Add TUNSETLINK ioctl to set the link encapsulation * * Mark Smith <markzzzsmith@yahoo.com.au> * Use eth_random_addr() for tap MAC address. * * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20 * Fixes in packet dropping, queue length setting and queue wakeup. * Increased default tx queue length. * Added ethtool API. * Minor cleanups * * Daniel Podlejski <underley@underley.eu.org> * Modifications for 2.3.99-pre5 kernel. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "tun" #define DRV_VERSION "1.6" #define DRV_DESCRIPTION "Universal TUN/TAP device driver" #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>" #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched/signal.h> #include <linux/major.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/miscdevice.h> #include <linux/ethtool.h> #include <linux/rtnetlink.h> #include <linux/compat.h> #include <linux/if.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/if_vlan.h> #include <linux/crc32.h> #include <linux/nsproxy.h> #include <linux/virtio_net.h> #include <linux/rcupdate.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/rtnetlink.h> #include <net/sock.h> #include <linux/seq_file.h> #include <linux/uio.h> #include <linux/skb_array.h> #include <linux/bpf.h> #include <linux/bpf_trace.h> #include <linux/uaccess.h> /* Uncomment to enable debugging */ /* #define TUN_DEBUG 1 */ #ifdef TUN_DEBUG static int debug; #define tun_debug(level, tun, fmt, args...) \ do { \ if (tun->debug) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (debug == 2) \ printk(level fmt, ##args); \ } while (0) #else #define tun_debug(level, tun, fmt, args...) \ do { \ if (0) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (0) \ printk(level fmt, ##args); \ } while (0) #endif #define TUN_HEADROOM 256 #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD) /* TUN device flags */ /* IFF_ATTACH_QUEUE is never stored in device flags, * overload it to mean fasync when stored there. */ #define TUN_FASYNC IFF_ATTACH_QUEUE /* High bits in flags field are unused. */ #define TUN_VNET_LE 0x80000000 #define TUN_VNET_BE 0x40000000 #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \ IFF_MULTI_QUEUE) #define GOODCOPY_LEN 128 #define FLT_EXACT_COUNT 8 struct tap_filter { unsigned int count; /* Number of addrs. Zero means disabled */ u32 mask[2]; /* Mask of the hashed addrs */ unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN]; }; /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal * to max number of VCPUs in guest. */ #define MAX_TAP_QUEUES 256 #define MAX_TAP_FLOWS 4096 #define TUN_FLOW_EXPIRE (3 * HZ) struct tun_pcpu_stats { u64 rx_packets; u64 rx_bytes; u64 tx_packets; u64 tx_bytes; struct u64_stats_sync syncp; u32 rx_dropped; u32 tx_dropped; u32 rx_frame_errors; }; /* A tun_file connects an open character device to a tuntap netdevice. It * also contains all socket related structures (except sock_fprog and tap_filter) * to serve as one transmit queue for tuntap device. The sock_fprog and * tap_filter were kept in tun_struct since they were used for filtering for the * netdevice not for a specific queue (at least I didn't see the requirement for * this). * * RCU usage: * The tun_file and tun_struct are loosely coupled, the pointer from one to the * other can only be read while rcu_read_lock or rtnl_lock is held. */ struct tun_file { struct sock sk; struct socket socket; struct socket_wq wq; struct tun_struct __rcu *tun; struct fasync_struct *fasync; /* only used for fasnyc */ unsigned int flags; union { u16 queue_index; unsigned int ifindex; }; struct list_head next; struct tun_struct *detached; struct skb_array tx_array; }; struct tun_flow_entry { struct hlist_node hash_link; struct rcu_head rcu; struct tun_struct *tun; u32 rxhash; u32 rps_rxhash; int queue_index; unsigned long updated; }; #define TUN_NUM_FLOW_ENTRIES 1024 /* Since the socket were moved to tun_file, to preserve the behavior of persist * device, socket filter, sndbuf and vnet header size were restore when the * file were attached to a persist device. */ struct tun_struct { struct tun_file __rcu *tfiles[MAX_TAP_QUEUES]; unsigned int numqueues; unsigned int flags; kuid_t owner; kgid_t group; struct net_device *dev; netdev_features_t set_features; #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \ NETIF_F_TSO6) int align; int vnet_hdr_sz; int sndbuf; struct tap_filter txflt; struct sock_fprog fprog; /* protected by rtnl lock */ bool filter_attached; #ifdef TUN_DEBUG int debug; #endif spinlock_t lock; struct hlist_head flows[TUN_NUM_FLOW_ENTRIES]; struct timer_list flow_gc_timer; unsigned long ageing_time; unsigned int numdisabled; struct list_head disabled; void *security; u32 flow_count; u32 rx_batched; struct tun_pcpu_stats __percpu *pcpu_stats; struct bpf_prog __rcu *xdp_prog; }; #ifdef CONFIG_TUN_VNET_CROSS_LE static inline bool tun_legacy_is_little_endian(struct tun_struct *tun) { return tun->flags & TUN_VNET_BE ? false : virtio_legacy_is_little_endian(); } static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp) { int be = !!(tun->flags & TUN_VNET_BE); if (put_user(be, argp)) return -EFAULT; return 0; } static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp) { int be; if (get_user(be, argp)) return -EFAULT; if (be) tun->flags |= TUN_VNET_BE; else tun->flags &= ~TUN_VNET_BE; return 0; } #else static inline bool tun_legacy_is_little_endian(struct tun_struct *tun) { return virtio_legacy_is_little_endian(); } static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp) { return -EINVAL; } static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp) { return -EINVAL; } #endif /* CONFIG_TUN_VNET_CROSS_LE */ static inline bool tun_is_little_endian(struct tun_struct *tun) { return tun->flags & TUN_VNET_LE || tun_legacy_is_little_endian(tun); } static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val) { return __virtio16_to_cpu(tun_is_little_endian(tun), val); } static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val) { return __cpu_to_virtio16(tun_is_little_endian(tun), val); } static inline u32 tun_hashfn(u32 rxhash) { return rxhash & 0x3ff; } static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash) { struct tun_flow_entry *e; hlist_for_each_entry_rcu(e, head, hash_link) { if (e->rxhash == rxhash) return e; } return NULL; } static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun, struct hlist_head *head, u32 rxhash, u16 queue_index) { struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC); if (e) { tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n", rxhash, queue_index); e->updated = jiffies; e->rxhash = rxhash; e->rps_rxhash = 0; e->queue_index = queue_index; e->tun = tun; hlist_add_head_rcu(&e->hash_link, head); ++tun->flow_count; } return e; } static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e) { tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n", e->rxhash, e->queue_index); hlist_del_rcu(&e->hash_link); kfree_rcu(e, rcu); --tun->flow_count; } static void tun_flow_flush(struct tun_struct *tun) { int i; spin_lock_bh(&tun->lock); for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) { struct tun_flow_entry *e; struct hlist_node *n; hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) tun_flow_delete(tun, e); } spin_unlock_bh(&tun->lock); } static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index) { int i; spin_lock_bh(&tun->lock); for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) { struct tun_flow_entry *e; struct hlist_node *n; hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) { if (e->queue_index == queue_index) tun_flow_delete(tun, e); } } spin_unlock_bh(&tun->lock); } static void tun_flow_cleanup(unsigned long data) { struct tun_struct *tun = (struct tun_struct *)data; unsigned long delay = tun->ageing_time; unsigned long next_timer = jiffies + delay; unsigned long count = 0; int i; tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n"); spin_lock_bh(&tun->lock); for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) { struct tun_flow_entry *e; struct hlist_node *n; hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) { unsigned long this_timer; count++; this_timer = e->updated + delay; if (time_before_eq(this_timer, jiffies)) tun_flow_delete(tun, e); else if (time_before(this_timer, next_timer)) next_timer = this_timer; } } if (count) mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer)); spin_unlock_bh(&tun->lock); } static void tun_flow_update(struct tun_struct *tun, u32 rxhash, struct tun_file *tfile) { struct hlist_head *head; struct tun_flow_entry *e; unsigned long delay = tun->ageing_time; u16 queue_index = tfile->queue_index; if (!rxhash) return; else head = &tun->flows[tun_hashfn(rxhash)]; rcu_read_lock(); /* We may get a very small possibility of OOO during switching, not * worth to optimize.*/ if (tun->numqueues == 1 || tfile->detached) goto unlock; e = tun_flow_find(head, rxhash); if (likely(e)) { /* TODO: keep queueing to old queue until it's empty? */ e->queue_index = queue_index; e->updated = jiffies; sock_rps_record_flow_hash(e->rps_rxhash); } else { spin_lock_bh(&tun->lock); if (!tun_flow_find(head, rxhash) && tun->flow_count < MAX_TAP_FLOWS) tun_flow_create(tun, head, rxhash, queue_index); if (!timer_pending(&tun->flow_gc_timer)) mod_timer(&tun->flow_gc_timer, round_jiffies_up(jiffies + delay)); spin_unlock_bh(&tun->lock); } unlock: rcu_read_unlock(); } /** * Save the hash received in the stack receive path and update the * flow_hash table accordingly. */ static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash) { if (unlikely(e->rps_rxhash != hash)) e->rps_rxhash = hash; } /* We try to identify a flow through its rxhash first. The reason that * we do not check rxq no. is because some cards(e.g 82599), chooses * the rxq based on the txq where the last packet of the flow comes. As * the userspace application move between processors, we may get a * different rxq no. here. If we could not get rxhash, then we would * hope the rxq no. may help here. */ static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { struct tun_struct *tun = netdev_priv(dev); struct tun_flow_entry *e; u32 txq = 0; u32 numqueues = 0; rcu_read_lock(); numqueues = ACCESS_ONCE(tun->numqueues); txq = __skb_get_hash_symmetric(skb); if (txq) { e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq); if (e) { tun_flow_save_rps_rxhash(e, txq); txq = e->queue_index; } else /* use multiply and shift instead of expensive divide */ txq = ((u64)txq * numqueues) >> 32; } else if (likely(skb_rx_queue_recorded(skb))) { txq = skb_get_rx_queue(skb); while (unlikely(txq >= numqueues)) txq -= numqueues; } rcu_read_unlock(); return txq; } static inline bool tun_not_capable(struct tun_struct *tun) { const struct cred *cred = current_cred(); struct net *net = dev_net(tun->dev); return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) || (gid_valid(tun->group) && !in_egroup_p(tun->group))) && !ns_capable(net->user_ns, CAP_NET_ADMIN); } static void tun_set_real_num_queues(struct tun_struct *tun) { netif_set_real_num_tx_queues(tun->dev, tun->numqueues); netif_set_real_num_rx_queues(tun->dev, tun->numqueues); } static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile) { tfile->detached = tun; list_add_tail(&tfile->next, &tun->disabled); ++tun->numdisabled; } static struct tun_struct *tun_enable_queue(struct tun_file *tfile) { struct tun_struct *tun = tfile->detached; tfile->detached = NULL; list_del_init(&tfile->next); --tun->numdisabled; return tun; } static void tun_queue_purge(struct tun_file *tfile) { struct sk_buff *skb; while ((skb = skb_array_consume(&tfile->tx_array)) != NULL) kfree_skb(skb); skb_queue_purge(&tfile->sk.sk_write_queue); skb_queue_purge(&tfile->sk.sk_error_queue); } static void __tun_detach(struct tun_file *tfile, bool clean) { struct tun_file *ntfile; struct tun_struct *tun; tun = rtnl_dereference(tfile->tun); if (tun && !tfile->detached) { u16 index = tfile->queue_index; BUG_ON(index >= tun->numqueues); rcu_assign_pointer(tun->tfiles[index], tun->tfiles[tun->numqueues - 1]); ntfile = rtnl_dereference(tun->tfiles[index]); ntfile->queue_index = index; --tun->numqueues; if (clean) { RCU_INIT_POINTER(tfile->tun, NULL); sock_put(&tfile->sk); } else tun_disable_queue(tun, tfile); synchronize_net(); tun_flow_delete_by_queue(tun, tun->numqueues + 1); /* Drop read queue */ tun_queue_purge(tfile); tun_set_real_num_queues(tun); } else if (tfile->detached && clean) { tun = tun_enable_queue(tfile); sock_put(&tfile->sk); } if (clean) { if (tun && tun->numqueues == 0 && tun->numdisabled == 0) { netif_carrier_off(tun->dev); if (!(tun->flags & IFF_PERSIST) && tun->dev->reg_state == NETREG_REGISTERED) unregister_netdevice(tun->dev); } if (tun) skb_array_cleanup(&tfile->tx_array); sock_put(&tfile->sk); } } static void tun_detach(struct tun_file *tfile, bool clean) { rtnl_lock(); __tun_detach(tfile, clean); rtnl_unlock(); } static void tun_detach_all(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); struct bpf_prog *xdp_prog = rtnl_dereference(tun->xdp_prog); struct tun_file *tfile, *tmp; int i, n = tun->numqueues; for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); BUG_ON(!tfile); tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN; tfile->socket.sk->sk_data_ready(tfile->socket.sk); RCU_INIT_POINTER(tfile->tun, NULL); --tun->numqueues; } list_for_each_entry(tfile, &tun->disabled, next) { tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN; tfile->socket.sk->sk_data_ready(tfile->socket.sk); RCU_INIT_POINTER(tfile->tun, NULL); } BUG_ON(tun->numqueues != 0); synchronize_net(); for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); /* Drop read queue */ tun_queue_purge(tfile); sock_put(&tfile->sk); } list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) { tun_enable_queue(tfile); tun_queue_purge(tfile); sock_put(&tfile->sk); } BUG_ON(tun->numdisabled != 0); if (xdp_prog) bpf_prog_put(xdp_prog); if (tun->flags & IFF_PERSIST) module_put(THIS_MODULE); } static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter) { struct tun_file *tfile = file->private_data; struct net_device *dev = tun->dev; int err; err = security_tun_dev_attach(tfile->socket.sk, tun->security); if (err < 0) goto out; err = -EINVAL; if (rtnl_dereference(tfile->tun) && !tfile->detached) goto out; err = -EBUSY; if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1) goto out; err = -E2BIG; if (!tfile->detached && tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES) goto out; err = 0; /* Re-attach the filter to persist device */ if (!skip_filter && (tun->filter_attached == true)) { lock_sock(tfile->socket.sk); err = sk_attach_filter(&tun->fprog, tfile->socket.sk); release_sock(tfile->socket.sk); if (!err) goto out; } if (!tfile->detached && skb_array_init(&tfile->tx_array, dev->tx_queue_len, GFP_KERNEL)) { err = -ENOMEM; goto out; } tfile->queue_index = tun->numqueues; tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN; rcu_assign_pointer(tfile->tun, tun); rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile); tun->numqueues++; if (tfile->detached) tun_enable_queue(tfile); else sock_hold(&tfile->sk); tun_set_real_num_queues(tun); /* device is allowed to go away first, so no need to hold extra * refcnt. */ out: return err; } static struct tun_struct *__tun_get(struct tun_file *tfile) { struct tun_struct *tun; rcu_read_lock(); tun = rcu_dereference(tfile->tun); if (tun) dev_hold(tun->dev); rcu_read_unlock(); return tun; } static struct tun_struct *tun_get(struct file *file) { return __tun_get(file->private_data); } static void tun_put(struct tun_struct *tun) { dev_put(tun->dev); } /* TAP filtering */ static void addr_hash_set(u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; mask[n >> 5] |= (1 << (n & 31)); } static unsigned int addr_hash_test(const u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; return mask[n >> 5] & (1 << (n & 31)); } static int update_filter(struct tap_filter *filter, void __user *arg) { struct { u8 u[ETH_ALEN]; } *addr; struct tun_filter uf; int err, alen, n, nexact; if (copy_from_user(&uf, arg, sizeof(uf))) return -EFAULT; if (!uf.count) { /* Disabled */ filter->count = 0; return 0; } alen = ETH_ALEN * uf.count; addr = memdup_user(arg + sizeof(uf), alen); if (IS_ERR(addr)) return PTR_ERR(addr); /* The filter is updated without holding any locks. Which is * perfectly safe. We disable it first and in the worst * case we'll accept a few undesired packets. */ filter->count = 0; wmb(); /* Use first set of addresses as an exact filter */ for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++) memcpy(filter->addr[n], addr[n].u, ETH_ALEN); nexact = n; /* Remaining multicast addresses are hashed, * unicast will leave the filter disabled. */ memset(filter->mask, 0, sizeof(filter->mask)); for (; n < uf.count; n++) { if (!is_multicast_ether_addr(addr[n].u)) { err = 0; /* no filter */ goto free_addr; } addr_hash_set(filter->mask, addr[n].u); } /* For ALLMULTI just set the mask to all ones. * This overrides the mask populated above. */ if ((uf.flags & TUN_FLT_ALLMULTI)) memset(filter->mask, ~0, sizeof(filter->mask)); /* Now enable the filter */ wmb(); filter->count = nexact; /* Return the number of exact filters */ err = nexact; free_addr: kfree(addr); return err; } /* Returns: 0 - drop, !=0 - accept */ static int run_filter(struct tap_filter *filter, const struct sk_buff *skb) { /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect * at this point. */ struct ethhdr *eh = (struct ethhdr *) skb->data; int i; /* Exact match */ for (i = 0; i < filter->count; i++) if (ether_addr_equal(eh->h_dest, filter->addr[i])) return 1; /* Inexact match (multicast only) */ if (is_multicast_ether_addr(eh->h_dest)) return addr_hash_test(filter->mask, eh->h_dest); return 0; } /* * Checks whether the packet is accepted or not. * Returns: 0 - drop, !=0 - accept */ static int check_filter(struct tap_filter *filter, const struct sk_buff *skb) { if (!filter->count) return 1; return run_filter(filter, skb); } /* Network device part of the driver */ static const struct ethtool_ops tun_ethtool_ops; /* Net device detach from fd. */ static void tun_net_uninit(struct net_device *dev) { tun_detach_all(dev); } /* Net device open. */ static int tun_net_open(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); int i; netif_tx_start_all_queues(dev); for (i = 0; i < tun->numqueues; i++) { struct tun_file *tfile; tfile = rtnl_dereference(tun->tfiles[i]); tfile->socket.sk->sk_write_space(tfile->socket.sk); } return 0; } /* Net device close. */ static int tun_net_close(struct net_device *dev) { netif_tx_stop_all_queues(dev); return 0; } /* Net device start xmit */ static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); int txq = skb->queue_mapping; struct tun_file *tfile; u32 numqueues = 0; rcu_read_lock(); tfile = rcu_dereference(tun->tfiles[txq]); numqueues = ACCESS_ONCE(tun->numqueues); /* Drop packet if interface is not attached */ if (txq >= numqueues) goto drop; #ifdef CONFIG_RPS if (numqueues == 1 && static_key_false(&rps_needed)) { /* Select queue was not called for the skbuff, so we extract the * RPS hash and save it into the flow_table here. */ __u32 rxhash; rxhash = __skb_get_hash_symmetric(skb); if (rxhash) { struct tun_flow_entry *e; e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash); if (e) tun_flow_save_rps_rxhash(e, rxhash); } } #endif tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len); BUG_ON(!tfile); /* Drop if the filter does not like it. * This is a noop if the filter is disabled. * Filter can be enabled only for the TAP devices. */ if (!check_filter(&tun->txflt, skb)) goto drop; if (tfile->socket.sk->sk_filter && sk_filter(tfile->socket.sk, skb)) goto drop; if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) goto drop; skb_tx_timestamp(skb); /* Orphan the skb - required as we might hang on to it * for indefinite time. */ skb_orphan(skb); nf_reset(skb); if (skb_array_produce(&tfile->tx_array, skb)) goto drop; /* Notify and wake up reader process */ if (tfile->flags & TUN_FASYNC) kill_fasync(&tfile->fasync, SIGIO, POLL_IN); tfile->socket.sk->sk_data_ready(tfile->socket.sk); rcu_read_unlock(); return NETDEV_TX_OK; drop: this_cpu_inc(tun->pcpu_stats->tx_dropped); skb_tx_error(skb); kfree_skb(skb); rcu_read_unlock(); return NET_XMIT_DROP; } static void tun_net_mclist(struct net_device *dev) { /* * This callback is supposed to deal with mc filter in * _rx_ path and has nothing to do with the _tx_ path. * In rx path we always accept everything userspace gives us. */ } static netdev_features_t tun_net_fix_features(struct net_device *dev, netdev_features_t features) { struct tun_struct *tun = netdev_priv(dev); return (features & tun->set_features) | (features & ~TUN_USER_FEATURES); } #ifdef CONFIG_NET_POLL_CONTROLLER static void tun_poll_controller(struct net_device *dev) { /* * Tun only receives frames when: * 1) the char device endpoint gets data from user space * 2) the tun socket gets a sendmsg call from user space * Since both of those are synchronous operations, we are guaranteed * never to have pending data when we poll for it * so there is nothing to do here but return. * We need this though so netpoll recognizes us as an interface that * supports polling, which enables bridge devices in virt setups to * still use netconsole */ return; } #endif static void tun_set_headroom(struct net_device *dev, int new_hr) { struct tun_struct *tun = netdev_priv(dev); if (new_hr < NET_SKB_PAD) new_hr = NET_SKB_PAD; tun->align = new_hr; } static void tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0; struct tun_struct *tun = netdev_priv(dev); struct tun_pcpu_stats *p; int i; for_each_possible_cpu(i) { u64 rxpackets, rxbytes, txpackets, txbytes; unsigned int start; p = per_cpu_ptr(tun->pcpu_stats, i); do { start = u64_stats_fetch_begin(&p->syncp); rxpackets = p->rx_packets; rxbytes = p->rx_bytes; txpackets = p->tx_packets; txbytes = p->tx_bytes; } while (u64_stats_fetch_retry(&p->syncp, start)); stats->rx_packets += rxpackets; stats->rx_bytes += rxbytes; stats->tx_packets += txpackets; stats->tx_bytes += txbytes; /* u32 counters */ rx_dropped += p->rx_dropped; rx_frame_errors += p->rx_frame_errors; tx_dropped += p->tx_dropped; } stats->rx_dropped = rx_dropped; stats->rx_frame_errors = rx_frame_errors; stats->tx_dropped = tx_dropped; } static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog, struct netlink_ext_ack *extack) { struct tun_struct *tun = netdev_priv(dev); struct bpf_prog *old_prog; old_prog = rtnl_dereference(tun->xdp_prog); rcu_assign_pointer(tun->xdp_prog, prog); if (old_prog) bpf_prog_put(old_prog); return 0; } static u32 tun_xdp_query(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); const struct bpf_prog *xdp_prog; xdp_prog = rtnl_dereference(tun->xdp_prog); if (xdp_prog) return xdp_prog->aux->id; return 0; } static int tun_xdp(struct net_device *dev, struct netdev_xdp *xdp) { switch (xdp->command) { case XDP_SETUP_PROG: return tun_xdp_set(dev, xdp->prog, xdp->extack); case XDP_QUERY_PROG: xdp->prog_id = tun_xdp_query(dev); xdp->prog_attached = !!xdp->prog_id; return 0; default: return -EINVAL; } } static const struct net_device_ops tun_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_fix_features = tun_net_fix_features, .ndo_select_queue = tun_select_queue, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif .ndo_set_rx_headroom = tun_set_headroom, .ndo_get_stats64 = tun_net_get_stats64, }; static const struct net_device_ops tap_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_fix_features = tun_net_fix_features, .ndo_set_rx_mode = tun_net_mclist, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, .ndo_select_queue = tun_select_queue, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif .ndo_features_check = passthru_features_check, .ndo_set_rx_headroom = tun_set_headroom, .ndo_get_stats64 = tun_net_get_stats64, .ndo_xdp = tun_xdp, }; static void tun_flow_init(struct tun_struct *tun) { int i; for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) INIT_HLIST_HEAD(&tun->flows[i]); tun->ageing_time = TUN_FLOW_EXPIRE; setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun); mod_timer(&tun->flow_gc_timer, round_jiffies_up(jiffies + tun->ageing_time)); } static void tun_flow_uninit(struct tun_struct *tun) { del_timer_sync(&tun->flow_gc_timer); tun_flow_flush(tun); } #define MIN_MTU 68 #define MAX_MTU 65535 /* Initialize net device. */ static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; break; case IFF_TAP: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; dev->priv_flags |= IFF_LIVE_ADDR_CHANGE; eth_hw_addr_random(dev); break; } dev->min_mtu = MIN_MTU; dev->max_mtu = MAX_MTU - dev->hard_header_len; } /* Character device part */ /* Poll */ static unsigned int tun_chr_poll(struct file *file, poll_table *wait) { struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); struct sock *sk; unsigned int mask = 0; if (!tun) return POLLERR; sk = tfile->socket.sk; tun_debug(KERN_INFO, tun, "tun_chr_poll\n"); poll_wait(file, sk_sleep(sk), wait); if (!skb_array_empty(&tfile->tx_array)) mask |= POLLIN | POLLRDNORM; if (tun->dev->flags & IFF_UP && (sock_writeable(sk) || (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) && sock_writeable(sk)))) mask |= POLLOUT | POLLWRNORM; if (tun->dev->reg_state != NETREG_REGISTERED) mask = POLLERR; tun_put(tun); return mask; } /* prepad is the amount to reserve at front. len is length after that. * linear is a hint as to how much to copy (usually headers). */ static struct sk_buff *tun_alloc_skb(struct tun_file *tfile, size_t prepad, size_t len, size_t linear, int noblock) { struct sock *sk = tfile->socket.sk; struct sk_buff *skb; int err; /* Under a page? Don't bother with paged skb. */ if (prepad + len < PAGE_SIZE || !linear) linear = len; skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock, &err, 0); if (!skb) return ERR_PTR(err); skb_reserve(skb, prepad); skb_put(skb, linear); skb->data_len = len - linear; skb->len += len - linear; return skb; } static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile, struct sk_buff *skb, int more) { struct sk_buff_head *queue = &tfile->sk.sk_write_queue; struct sk_buff_head process_queue; u32 rx_batched = tun->rx_batched; bool rcv = false; if (!rx_batched || (!more && skb_queue_empty(queue))) { local_bh_disable(); netif_receive_skb(skb); local_bh_enable(); return; } spin_lock(&queue->lock); if (!more || skb_queue_len(queue) == rx_batched) { __skb_queue_head_init(&process_queue); skb_queue_splice_tail_init(queue, &process_queue); rcv = true; } else { __skb_queue_tail(queue, skb); } spin_unlock(&queue->lock); if (rcv) { struct sk_buff *nskb; local_bh_disable(); while ((nskb = __skb_dequeue(&process_queue))) netif_receive_skb(nskb); netif_receive_skb(skb); local_bh_enable(); } } static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile, int len, int noblock, bool zerocopy) { if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) return false; if (tfile->socket.sk->sk_sndbuf != INT_MAX) return false; if (!noblock) return false; if (zerocopy) return false; if (SKB_DATA_ALIGN(len + TUN_RX_PAD) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE) return false; return true; } static struct sk_buff *tun_build_skb(struct tun_struct *tun, struct tun_file *tfile, struct iov_iter *from, struct virtio_net_hdr *hdr, int len, int *skb_xdp) { struct page_frag *alloc_frag = &current->task_frag; struct sk_buff *skb; struct bpf_prog *xdp_prog; int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); unsigned int delta = 0; char *buf; size_t copied; bool xdp_xmit = false; int err, pad = TUN_RX_PAD; rcu_read_lock(); xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog) pad += TUN_HEADROOM; buflen += SKB_DATA_ALIGN(len + pad); rcu_read_unlock(); if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL))) return ERR_PTR(-ENOMEM); buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset; copied = copy_page_from_iter(alloc_frag->page, alloc_frag->offset + pad, len, from); if (copied != len) return ERR_PTR(-EFAULT); /* There's a small window that XDP may be set after the check * of xdp_prog above, this should be rare and for simplicity * we do XDP on skb in case the headroom is not enough. */ if (hdr->gso_type || !xdp_prog) *skb_xdp = 1; else *skb_xdp = 0; rcu_read_lock(); xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog && !*skb_xdp) { struct xdp_buff xdp; void *orig_data; u32 act; xdp.data_hard_start = buf; xdp.data = buf + pad; xdp.data_end = xdp.data + len; orig_data = xdp.data; act = bpf_prog_run_xdp(xdp_prog, &xdp); switch (act) { case XDP_REDIRECT: get_page(alloc_frag->page); alloc_frag->offset += buflen; err = xdp_do_redirect(tun->dev, &xdp, xdp_prog); if (err) goto err_redirect; return NULL; case XDP_TX: xdp_xmit = true; /* fall through */ case XDP_PASS: delta = orig_data - xdp.data; break; default: bpf_warn_invalid_xdp_action(act); /* fall through */ case XDP_ABORTED: trace_xdp_exception(tun->dev, xdp_prog, act); /* fall through */ case XDP_DROP: goto err_xdp; } } skb = build_skb(buf, buflen); if (!skb) { rcu_read_unlock(); return ERR_PTR(-ENOMEM); } skb_reserve(skb, pad - delta); skb_put(skb, len + delta); get_page(alloc_frag->page); alloc_frag->offset += buflen; if (xdp_xmit) { skb->dev = tun->dev; generic_xdp_tx(skb, xdp_prog); rcu_read_lock(); return NULL; } rcu_read_unlock(); return skb; err_redirect: put_page(alloc_frag->page); err_xdp: rcu_read_unlock(); this_cpu_inc(tun->pcpu_stats->rx_dropped); return NULL; } /* Get packet from user space buffer */ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, void *msg_control, struct iov_iter *from, int noblock, bool more) { struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) }; struct sk_buff *skb; size_t total_len = iov_iter_count(from); size_t len = total_len, align = tun->align, linear; struct virtio_net_hdr gso = { 0 }; struct tun_pcpu_stats *stats; int good_linear; int copylen; bool zerocopy = false; int err; u32 rxhash; int skb_xdp = 1; if (!(tun->dev->flags & IFF_UP)) return -EIO; if (!(tun->flags & IFF_NO_PI)) { if (len < sizeof(pi)) return -EINVAL; len -= sizeof(pi); if (!copy_from_iter_full(&pi, sizeof(pi), from)) return -EFAULT; } if (tun->flags & IFF_VNET_HDR) { int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz); if (len < vnet_hdr_sz) return -EINVAL; len -= vnet_hdr_sz; if (!copy_from_iter_full(&gso, sizeof(gso), from)) return -EFAULT; if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len)) gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2); if (tun16_to_cpu(tun, gso.hdr_len) > len) return -EINVAL; iov_iter_advance(from, vnet_hdr_sz - sizeof(gso)); } if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) { align += NET_IP_ALIGN; if (unlikely(len < ETH_HLEN || (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN))) return -EINVAL; } good_linear = SKB_MAX_HEAD(align); if (msg_control) { struct iov_iter i = *from; /* There are 256 bytes to be copied in skb, so there is * enough room for skb expand head in case it is used. * The rest of the buffer is mapped from userspace. */ copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN; if (copylen > good_linear) copylen = good_linear; linear = copylen; iov_iter_advance(&i, copylen); if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS) zerocopy = true; } if (tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) { /* For the packet that is not easy to be processed * (e.g gso or jumbo packet), we will do it at after * skb was created with generic XDP routine. */ skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp); if (IS_ERR(skb)) { this_cpu_inc(tun->pcpu_stats->rx_dropped); return PTR_ERR(skb); } if (!skb) return total_len; } else { if (!zerocopy) { copylen = len; if (tun16_to_cpu(tun, gso.hdr_len) > good_linear) linear = good_linear; else linear = tun16_to_cpu(tun, gso.hdr_len); } skb = tun_alloc_skb(tfile, align, copylen, linear, noblock); if (IS_ERR(skb)) { if (PTR_ERR(skb) != -EAGAIN) this_cpu_inc(tun->pcpu_stats->rx_dropped); return PTR_ERR(skb); } if (zerocopy) err = zerocopy_sg_from_iter(skb, from); else err = skb_copy_datagram_from_iter(skb, 0, from, len); if (err) { this_cpu_inc(tun->pcpu_stats->rx_dropped); kfree_skb(skb); return -EFAULT; } } if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) { this_cpu_inc(tun->pcpu_stats->rx_frame_errors); kfree_skb(skb); return -EINVAL; } switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: if (tun->flags & IFF_NO_PI) { u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0; switch (ip_version) { case 4: pi.proto = htons(ETH_P_IP); break; case 6: pi.proto = htons(ETH_P_IPV6); break; default: this_cpu_inc(tun->pcpu_stats->rx_dropped); kfree_skb(skb); return -EINVAL; } } skb_reset_mac_header(skb); skb->protocol = pi.proto; skb->dev = tun->dev; break; case IFF_TAP: skb->protocol = eth_type_trans(skb, tun->dev); break; } /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; } else if (msg_control) { struct ubuf_info *uarg = msg_control; uarg->callback(uarg, false); } skb_reset_network_header(skb); skb_probe_transport_header(skb, 0); if (skb_xdp) { struct bpf_prog *xdp_prog; int ret; rcu_read_lock(); xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog) { ret = do_xdp_generic(xdp_prog, skb); if (ret != XDP_PASS) { rcu_read_unlock(); return total_len; } } rcu_read_unlock(); } rxhash = __skb_get_hash_symmetric(skb); #ifndef CONFIG_4KSTACKS tun_rx_batched(tun, tfile, skb, more); #else netif_rx_ni(skb); #endif stats = get_cpu_ptr(tun->pcpu_stats); u64_stats_update_begin(&stats->syncp); stats->rx_packets++; stats->rx_bytes += len; u64_stats_update_end(&stats->syncp); put_cpu_ptr(stats); tun_flow_update(tun, rxhash, tfile); return total_len; } static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct tun_struct *tun = tun_get(file); struct tun_file *tfile = file->private_data; ssize_t result; if (!tun) return -EBADFD; result = tun_get_user(tun, tfile, NULL, from, file->f_flags & O_NONBLOCK, false); tun_put(tun); return result; } /* Put packet to the user space buffer */ static ssize_t tun_put_user(struct tun_struct *tun, struct tun_file *tfile, struct sk_buff *skb, struct iov_iter *iter) { struct tun_pi pi = { 0, skb->protocol }; struct tun_pcpu_stats *stats; ssize_t total; int vlan_offset = 0; int vlan_hlen = 0; int vnet_hdr_sz = 0; if (skb_vlan_tag_present(skb)) vlan_hlen = VLAN_HLEN; if (tun->flags & IFF_VNET_HDR) vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz); total = skb->len + vlan_hlen + vnet_hdr_sz; if (!(tun->flags & IFF_NO_PI)) { if (iov_iter_count(iter) < sizeof(pi)) return -EINVAL; total += sizeof(pi); if (iov_iter_count(iter) < total) { /* Packet will be striped */ pi.flags |= TUN_PKT_STRIP; } if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi)) return -EFAULT; } if (vnet_hdr_sz) { struct virtio_net_hdr gso; if (iov_iter_count(iter) < vnet_hdr_sz) return -EINVAL; if (virtio_net_hdr_from_skb(skb, &gso, tun_is_little_endian(tun), true)) { struct skb_shared_info *sinfo = skb_shinfo(skb); pr_err("unexpected GSO type: " "0x%x, gso_size %d, hdr_len %d\n", sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size), tun16_to_cpu(tun, gso.hdr_len)); print_hex_dump(KERN_ERR, "tun: ", DUMP_PREFIX_NONE, 16, 1, skb->head, min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true); WARN_ON_ONCE(1); return -EINVAL; } if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso)) return -EFAULT; iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso)); } if (vlan_hlen) { int ret; struct { __be16 h_vlan_proto; __be16 h_vlan_TCI; } veth; veth.h_vlan_proto = skb->vlan_proto; veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb)); vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto); ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset); if (ret || !iov_iter_count(iter)) goto done; ret = copy_to_iter(&veth, sizeof(veth), iter); if (ret != sizeof(veth) || !iov_iter_count(iter)) goto done; } skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset); done: /* caller is in process context, */ stats = get_cpu_ptr(tun->pcpu_stats); u64_stats_update_begin(&stats->syncp); stats->tx_packets++; stats->tx_bytes += skb->len + vlan_hlen; u64_stats_update_end(&stats->syncp); put_cpu_ptr(tun->pcpu_stats); return total; } static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock, int *err) { DECLARE_WAITQUEUE(wait, current); struct sk_buff *skb = NULL; int error = 0; skb = skb_array_consume(&tfile->tx_array); if (skb) goto out; if (noblock) { error = -EAGAIN; goto out; } add_wait_queue(&tfile->wq.wait, &wait); current->state = TASK_INTERRUPTIBLE; while (1) { skb = skb_array_consume(&tfile->tx_array); if (skb) break; if (signal_pending(current)) { error = -ERESTARTSYS; break; } if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) { error = -EFAULT; break; } schedule(); } current->state = TASK_RUNNING; remove_wait_queue(&tfile->wq.wait, &wait); out: *err = error; return skb; } static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile, struct iov_iter *to, int noblock, struct sk_buff *skb) { ssize_t ret; int err; tun_debug(KERN_INFO, tun, "tun_do_read\n"); if (!iov_iter_count(to)) return 0; if (!skb) { /* Read frames from ring */ skb = tun_ring_recv(tfile, noblock, &err); if (!skb) return err; } ret = tun_put_user(tun, tfile, skb, to); if (unlikely(ret < 0)) kfree_skb(skb); else consume_skb(skb); return ret; } static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); ssize_t len = iov_iter_count(to), ret; if (!tun) return -EBADFD; ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL); ret = min_t(ssize_t, ret, len); if (ret > 0) iocb->ki_pos = ret; tun_put(tun); return ret; } static void tun_free_netdev(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); BUG_ON(!(list_empty(&tun->disabled))); free_percpu(tun->pcpu_stats); tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); } static void tun_setup(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); tun->owner = INVALID_UID; tun->group = INVALID_GID; dev->ethtool_ops = &tun_ethtool_ops; dev->needs_free_netdev = true; dev->priv_destructor = tun_free_netdev; /* We prefer our own queue length */ dev->tx_queue_len = TUN_READQ_SIZE; } /* Trivial set of netlink ops to allow deleting tun or tap * device with netlink. */ static int tun_validate(struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { return -EINVAL; } static struct rtnl_link_ops tun_link_ops __read_mostly = { .kind = DRV_NAME, .priv_size = sizeof(struct tun_struct), .setup = tun_setup, .validate = tun_validate, }; static void tun_sock_write_space(struct sock *sk) { struct tun_file *tfile; wait_queue_head_t *wqueue; if (!sock_writeable(sk)) return; if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags)) return; wqueue = sk_sleep(sk); if (wqueue && waitqueue_active(wqueue)) wake_up_interruptible_sync_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND); tfile = container_of(sk, struct tun_file, sk); kill_fasync(&tfile->fasync, SIGIO, POLL_OUT); } static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len) { int ret; struct tun_file *tfile = container_of(sock, struct tun_file, socket); struct tun_struct *tun = __tun_get(tfile); if (!tun) return -EBADFD; ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter, m->msg_flags & MSG_DONTWAIT, m->msg_flags & MSG_MORE); tun_put(tun); return ret; } static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len, int flags) { struct tun_file *tfile = container_of(sock, struct tun_file, socket); struct tun_struct *tun = __tun_get(tfile); int ret; if (!tun) return -EBADFD; if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) { ret = -EINVAL; goto out; } if (flags & MSG_ERRQUEUE) { ret = sock_recv_errqueue(sock->sk, m, total_len, SOL_PACKET, TUN_TX_TIMESTAMP); goto out; } ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, m->msg_control); if (ret > (ssize_t)total_len) { m->msg_flags |= MSG_TRUNC; ret = flags & MSG_TRUNC ? ret : total_len; } out: tun_put(tun); return ret; } static int tun_peek_len(struct socket *sock) { struct tun_file *tfile = container_of(sock, struct tun_file, socket); struct tun_struct *tun; int ret = 0; tun = __tun_get(tfile); if (!tun) return 0; ret = skb_array_peek_len(&tfile->tx_array); tun_put(tun); return ret; } /* Ops structure to mimic raw sockets with tun */ static const struct proto_ops tun_socket_ops = { .peek_len = tun_peek_len, .sendmsg = tun_sendmsg, .recvmsg = tun_recvmsg, }; static struct proto tun_proto = { .name = "tun", .owner = THIS_MODULE, .obj_size = sizeof(struct tun_file), }; static int tun_flags(struct tun_struct *tun) { return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP); } static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "0x%x\n", tun_flags(tun)); } static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return uid_valid(tun->owner)? sprintf(buf, "%u\n", from_kuid_munged(current_user_ns(), tun->owner)): sprintf(buf, "-1\n"); } static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return gid_valid(tun->group) ? sprintf(buf, "%u\n", from_kgid_munged(current_user_ns(), tun->group)): sprintf(buf, "-1\n"); } static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL); static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL); static DEVICE_ATTR(group, 0444, tun_show_group, NULL); static struct attribute *tun_dev_attrs[] = { &dev_attr_tun_flags.attr, &dev_attr_owner.attr, &dev_attr_group.attr, NULL }; static const struct attribute_group tun_attr_group = { .attrs = tun_dev_attrs }; static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err < 0) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } static void tun_get_iff(struct net *net, struct tun_struct *tun, struct ifreq *ifr) { tun_debug(KERN_INFO, tun, "tun_get_iff\n"); strcpy(ifr->ifr_name, tun->dev->name); ifr->ifr_flags = tun_flags(tun); } /* This is like a cut-down ethtool ops, except done via tun fd so no * privs required. */ static int set_offload(struct tun_struct *tun, unsigned long arg) { netdev_features_t features = 0; if (arg & TUN_F_CSUM) { features |= NETIF_F_HW_CSUM; arg &= ~TUN_F_CSUM; if (arg & (TUN_F_TSO4|TUN_F_TSO6)) { if (arg & TUN_F_TSO_ECN) { features |= NETIF_F_TSO_ECN; arg &= ~TUN_F_TSO_ECN; } if (arg & TUN_F_TSO4) features |= NETIF_F_TSO; if (arg & TUN_F_TSO6) features |= NETIF_F_TSO6; arg &= ~(TUN_F_TSO4|TUN_F_TSO6); } } /* This gives the user a way to test for new features in future by * trying to set them. */ if (arg) return -EINVAL; tun->set_features = features; tun->dev->wanted_features &= ~TUN_USER_FEATURES; tun->dev->wanted_features |= features; netdev_update_features(tun->dev); return 0; } static void tun_detach_filter(struct tun_struct *tun, int n) { int i; struct tun_file *tfile; for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); lock_sock(tfile->socket.sk); sk_detach_filter(tfile->socket.sk); release_sock(tfile->socket.sk); } tun->filter_attached = false; } static int tun_attach_filter(struct tun_struct *tun) { int i, ret = 0; struct tun_file *tfile; for (i = 0; i < tun->numqueues; i++) { tfile = rtnl_dereference(tun->tfiles[i]); lock_sock(tfile->socket.sk); ret = sk_attach_filter(&tun->fprog, tfile->socket.sk); release_sock(tfile->socket.sk); if (ret) { tun_detach_filter(tun, i); return ret; } } tun->filter_attached = true; return ret; } static void tun_set_sndbuf(struct tun_struct *tun) { struct tun_file *tfile; int i; for (i = 0; i < tun->numqueues; i++) { tfile = rtnl_dereference(tun->tfiles[i]); tfile->socket.sk->sk_sndbuf = tun->sndbuf; } } static int tun_set_queue(struct file *file, struct ifreq *ifr) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; int ret = 0; rtnl_lock(); if (ifr->ifr_flags & IFF_ATTACH_QUEUE) { tun = tfile->detached; if (!tun) { ret = -EINVAL; goto unlock; } ret = security_tun_dev_attach_queue(tun->security); if (ret < 0) goto unlock; ret = tun_attach(tun, file, false); } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) { tun = rtnl_dereference(tfile->tun); if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached) ret = -EINVAL; else __tun_detach(tfile, false); } else ret = -EINVAL; unlock: rtnl_unlock(); return ret; } static long __tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg, int ifreq_len) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; void __user* argp = (void __user*)arg; struct ifreq ifr; kuid_t owner; kgid_t group; int sndbuf; int vnet_hdr_sz; unsigned int ifindex; int le; int ret; if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) { if (copy_from_user(&ifr, argp, ifreq_len)) return -EFAULT; } else { memset(&ifr, 0, sizeof(ifr)); } if (cmd == TUNGETFEATURES) { /* Currently this just means: "what IFF flags are valid?". * This is needed because we never checked for invalid flags on * TUNSETIFF. */ return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES, (unsigned int __user*)argp); } else if (cmd == TUNSETQUEUE) return tun_set_queue(file, &ifr); ret = 0; rtnl_lock(); tun = __tun_get(tfile); if (cmd == TUNSETIFF) { ret = -EEXIST; if (tun) goto unlock; ifr.ifr_name[IFNAMSIZ-1] = '\0'; ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr); if (ret) goto unlock; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; goto unlock; } if (cmd == TUNSETIFINDEX) { ret = -EPERM; if (tun) goto unlock; ret = -EFAULT; if (copy_from_user(&ifindex, argp, sizeof(ifindex))) goto unlock; ret = 0; tfile->ifindex = ifindex; goto unlock; } ret = -EBADFD; if (!tun) goto unlock; tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd); ret = 0; switch (cmd) { case TUNGETIFF: tun_get_iff(current->nsproxy->net_ns, tun, &ifr); if (tfile->detached) ifr.ifr_flags |= IFF_DETACH_QUEUE; if (!tfile->socket.sk->sk_filter) ifr.ifr_flags |= IFF_NOFILTER; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case TUNSETNOCSUM: /* Disable/Enable checksum */ /* [unimplemented] */ tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n", arg ? "disabled" : "enabled"); break; case TUNSETPERSIST: /* Disable/Enable persist mode. Keep an extra reference to the * module to prevent the module being unprobed. */ if (arg && !(tun->flags & IFF_PERSIST)) { tun->flags |= IFF_PERSIST; __module_get(THIS_MODULE); } if (!arg && (tun->flags & IFF_PERSIST)) { tun->flags &= ~IFF_PERSIST; module_put(THIS_MODULE); } tun_debug(KERN_INFO, tun, "persist %s\n", arg ? "enabled" : "disabled"); break; case TUNSETOWNER: /* Set owner of the device */ owner = make_kuid(current_user_ns(), arg); if (!uid_valid(owner)) { ret = -EINVAL; break; } tun->owner = owner; tun_debug(KERN_INFO, tun, "owner set to %u\n", from_kuid(&init_user_ns, tun->owner)); break; case TUNSETGROUP: /* Set group of the device */ group = make_kgid(current_user_ns(), arg); if (!gid_valid(group)) { ret = -EINVAL; break; } tun->group = group; tun_debug(KERN_INFO, tun, "group set to %u\n", from_kgid(&init_user_ns, tun->group)); break; case TUNSETLINK: /* Only allow setting the type when the interface is down */ if (tun->dev->flags & IFF_UP) { tun_debug(KERN_INFO, tun, "Linktype set failed because interface is up\n"); ret = -EBUSY; } else { tun->dev->type = (int) arg; tun_debug(KERN_INFO, tun, "linktype set to %d\n", tun->dev->type); ret = 0; } break; #ifdef TUN_DEBUG case TUNSETDEBUG: tun->debug = arg; break; #endif case TUNSETOFFLOAD: ret = set_offload(tun, arg); break; case TUNSETTXFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = update_filter(&tun->txflt, (void __user *)arg); break; case SIOCGIFHWADDR: /* Get hw address */ memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN); ifr.ifr_hwaddr.sa_family = tun->dev->type; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case SIOCSIFHWADDR: /* Set hw address */ tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n", ifr.ifr_hwaddr.sa_data); ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr); break; case TUNGETSNDBUF: sndbuf = tfile->socket.sk->sk_sndbuf; if (copy_to_user(argp, &sndbuf, sizeof(sndbuf))) ret = -EFAULT; break; case TUNSETSNDBUF: if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) { ret = -EFAULT; break; } tun->sndbuf = sndbuf; tun_set_sndbuf(tun); break; case TUNGETVNETHDRSZ: vnet_hdr_sz = tun->vnet_hdr_sz; if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz))) ret = -EFAULT; break; case TUNSETVNETHDRSZ: if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) { ret = -EFAULT; break; } if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) { ret = -EINVAL; break; } tun->vnet_hdr_sz = vnet_hdr_sz; break; case TUNGETVNETLE: le = !!(tun->flags & TUN_VNET_LE); if (put_user(le, (int __user *)argp)) ret = -EFAULT; break; case TUNSETVNETLE: if (get_user(le, (int __user *)argp)) { ret = -EFAULT; break; } if (le) tun->flags |= TUN_VNET_LE; else tun->flags &= ~TUN_VNET_LE; break; case TUNGETVNETBE: ret = tun_get_vnet_be(tun, argp); break; case TUNSETVNETBE: ret = tun_set_vnet_be(tun, argp); break; case TUNATTACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = -EFAULT; if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog))) break; ret = tun_attach_filter(tun); break; case TUNDETACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = 0; tun_detach_filter(tun, tun->numqueues); break; case TUNGETFILTER: ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP) break; ret = -EFAULT; if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog))) break; ret = 0; break; default: ret = -EINVAL; break; } unlock: rtnl_unlock(); if (tun) tun_put(tun); return ret; } static long tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq)); } #ifdef CONFIG_COMPAT static long tun_chr_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case TUNSETIFF: case TUNGETIFF: case TUNSETTXFILTER: case TUNGETSNDBUF: case TUNSETSNDBUF: case SIOCGIFHWADDR: case SIOCSIFHWADDR: arg = (unsigned long)compat_ptr(arg); break; default: arg = (compat_ulong_t)arg; break; } /* * compat_ifreq is shorter than ifreq, so we must not access beyond * the end of that structure. All fields that are used in this * driver are compatible though, we don't need to convert the * contents. */ return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq)); } #endif /* CONFIG_COMPAT */ static int tun_chr_fasync(int fd, struct file *file, int on) { struct tun_file *tfile = file->private_data; int ret; if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0) goto out; if (on) { __f_setown(file, task_pid(current), PIDTYPE_PID, 0); tfile->flags |= TUN_FASYNC; } else tfile->flags &= ~TUN_FASYNC; ret = 0; out: return ret; } static int tun_chr_open(struct inode *inode, struct file * file) { struct net *net = current->nsproxy->net_ns; struct tun_file *tfile; DBG1(KERN_INFO, "tunX: tun_chr_open\n"); tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL, &tun_proto, 0); if (!tfile) return -ENOMEM; RCU_INIT_POINTER(tfile->tun, NULL); tfile->flags = 0; tfile->ifindex = 0; init_waitqueue_head(&tfile->wq.wait); RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq); tfile->socket.file = file; tfile->socket.ops = &tun_socket_ops; sock_init_data(&tfile->socket, &tfile->sk); tfile->sk.sk_write_space = tun_sock_write_space; tfile->sk.sk_sndbuf = INT_MAX; file->private_data = tfile; INIT_LIST_HEAD(&tfile->next); sock_set_flag(&tfile->sk, SOCK_ZEROCOPY); return 0; } static int tun_chr_close(struct inode *inode, struct file *file) { struct tun_file *tfile = file->private_data; tun_detach(tfile, true); return 0; } #ifdef CONFIG_PROC_FS static void tun_chr_show_fdinfo(struct seq_file *m, struct file *f) { struct tun_struct *tun; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); rtnl_lock(); tun = tun_get(f); if (tun) tun_get_iff(current->nsproxy->net_ns, tun, &ifr); rtnl_unlock(); if (tun) tun_put(tun); seq_printf(m, "iff:\t%s\n", ifr.ifr_name); } #endif static const struct file_operations tun_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read_iter = tun_chr_read_iter, .write_iter = tun_chr_write_iter, .poll = tun_chr_poll, .unlocked_ioctl = tun_chr_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = tun_chr_compat_ioctl, #endif .open = tun_chr_open, .release = tun_chr_close, .fasync = tun_chr_fasync, #ifdef CONFIG_PROC_FS .show_fdinfo = tun_chr_show_fdinfo, #endif }; static struct miscdevice tun_miscdev = { .minor = TUN_MINOR, .name = "tun", .nodename = "net/tun", .fops = &tun_fops, }; /* ethtool interface */ static int tun_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { ethtool_link_ksettings_zero_link_mode(cmd, supported); ethtool_link_ksettings_zero_link_mode(cmd, advertising); cmd->base.speed = SPEED_10; cmd->base.duplex = DUPLEX_FULL; cmd->base.port = PORT_TP; cmd->base.phy_address = 0; cmd->base.autoneg = AUTONEG_DISABLE; return 0; } static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct tun_struct *tun = netdev_priv(dev); strlcpy(info->driver, DRV_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_VERSION, sizeof(info->version)); switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: strlcpy(info->bus_info, "tun", sizeof(info->bus_info)); break; case IFF_TAP: strlcpy(info->bus_info, "tap", sizeof(info->bus_info)); break; } } static u32 tun_get_msglevel(struct net_device *dev) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); return tun->debug; #else return -EOPNOTSUPP; #endif } static void tun_set_msglevel(struct net_device *dev, u32 value) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); tun->debug = value; #endif } static int tun_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tun_struct *tun = netdev_priv(dev); ec->rx_max_coalesced_frames = tun->rx_batched; return 0; } static int tun_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tun_struct *tun = netdev_priv(dev); if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT) tun->rx_batched = NAPI_POLL_WEIGHT; else tun->rx_batched = ec->rx_max_coalesced_frames; return 0; } static const struct ethtool_ops tun_ethtool_ops = { .get_drvinfo = tun_get_drvinfo, .get_msglevel = tun_get_msglevel, .set_msglevel = tun_set_msglevel, .get_link = ethtool_op_get_link, .get_ts_info = ethtool_op_get_ts_info, .get_coalesce = tun_get_coalesce, .set_coalesce = tun_set_coalesce, .get_link_ksettings = tun_get_link_ksettings, }; static int tun_queue_resize(struct tun_struct *tun) { struct net_device *dev = tun->dev; struct tun_file *tfile; struct skb_array **arrays; int n = tun->numqueues + tun->numdisabled; int ret, i; arrays = kmalloc_array(n, sizeof(*arrays), GFP_KERNEL); if (!arrays) return -ENOMEM; for (i = 0; i < tun->numqueues; i++) { tfile = rtnl_dereference(tun->tfiles[i]); arrays[i] = &tfile->tx_array; } list_for_each_entry(tfile, &tun->disabled, next) arrays[i++] = &tfile->tx_array; ret = skb_array_resize_multiple(arrays, n, dev->tx_queue_len, GFP_KERNEL); kfree(arrays); return ret; } static int tun_device_event(struct notifier_block *unused, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct tun_struct *tun = netdev_priv(dev); if (dev->rtnl_link_ops != &tun_link_ops) return NOTIFY_DONE; switch (event) { case NETDEV_CHANGE_TX_QUEUE_LEN: if (tun_queue_resize(tun)) return NOTIFY_BAD; break; default: break; } return NOTIFY_DONE; } static struct notifier_block tun_notifier_block __read_mostly = { .notifier_call = tun_device_event, }; static int __init tun_init(void) { int ret = 0; pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION); ret = rtnl_link_register(&tun_link_ops); if (ret) { pr_err("Can't register link_ops\n"); goto err_linkops; } ret = misc_register(&tun_miscdev); if (ret) { pr_err("Can't register misc device %d\n", TUN_MINOR); goto err_misc; } ret = register_netdevice_notifier(&tun_notifier_block); if (ret) { pr_err("Can't register netdevice notifier\n"); goto err_notifier; } return 0; err_notifier: misc_deregister(&tun_miscdev); err_misc: rtnl_link_unregister(&tun_link_ops); err_linkops: return ret; } static void tun_cleanup(void) { misc_deregister(&tun_miscdev); rtnl_link_unregister(&tun_link_ops); unregister_netdevice_notifier(&tun_notifier_block); } /* Get an underlying socket object from tun file. Returns error unless file is * attached to a device. The returned object works like a packet socket, it * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for * holding a reference to the file for as long as the socket is in use. */ struct socket *tun_get_socket(struct file *file) { struct tun_file *tfile; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tfile = file->private_data; if (!tfile) return ERR_PTR(-EBADFD); return &tfile->socket; } EXPORT_SYMBOL_GPL(tun_get_socket); struct skb_array *tun_get_skb_array(struct file *file) { struct tun_file *tfile; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tfile = file->private_data; if (!tfile) return ERR_PTR(-EBADFD); return &tfile->tx_array; } EXPORT_SYMBOL_GPL(tun_get_skb_array); module_init(tun_init); module_exit(tun_cleanup); MODULE_DESCRIPTION(DRV_DESCRIPTION); MODULE_AUTHOR(DRV_COPYRIGHT); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(TUN_MINOR); MODULE_ALIAS("devname:net/tun");
./CrossVul/dataset_final_sorted/CWE-476/c/good_624_0
crossvul-cpp_data_good_75_0
/* * Hisilicon clock driver * * Copyright (c) 2013-2017 Hisilicon Limited. * Copyright (c) 2017 Linaro Limited. * * Author: Kai Zhao <zhaokai1@hisilicon.com> * Tao Wang <kevin.wangtao@hisilicon.com> * Leo Yan <leo.yan@linaro.org> * * 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. * */ #include <linux/clk-provider.h> #include <linux/device.h> #include <linux/err.h> #include <linux/init.h> #include <linux/mailbox_client.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <dt-bindings/clock/hi3660-clock.h> #define HI3660_STUB_CLOCK_DATA (0x70) #define MHZ (1000 * 1000) #define DEFINE_CLK_STUB(_id, _cmd, _name) \ { \ .id = (_id), \ .cmd = (_cmd), \ .hw.init = &(struct clk_init_data) { \ .name = #_name, \ .ops = &hi3660_stub_clk_ops, \ .num_parents = 0, \ .flags = CLK_GET_RATE_NOCACHE, \ }, \ }, #define to_stub_clk(_hw) container_of(_hw, struct hi3660_stub_clk, hw) struct hi3660_stub_clk_chan { struct mbox_client cl; struct mbox_chan *mbox; }; struct hi3660_stub_clk { unsigned int id; struct clk_hw hw; unsigned int cmd; unsigned int msg[8]; unsigned int rate; }; static void __iomem *freq_reg; static struct hi3660_stub_clk_chan stub_clk_chan; static unsigned long hi3660_stub_clk_recalc_rate(struct clk_hw *hw, unsigned long parent_rate) { struct hi3660_stub_clk *stub_clk = to_stub_clk(hw); /* * LPM3 writes back the CPU frequency in shared SRAM so read * back the frequency. */ stub_clk->rate = readl(freq_reg + (stub_clk->id << 2)) * MHZ; return stub_clk->rate; } static long hi3660_stub_clk_round_rate(struct clk_hw *hw, unsigned long rate, unsigned long *prate) { /* * LPM3 handles rate rounding so just return whatever * rate is requested. */ return rate; } static int hi3660_stub_clk_set_rate(struct clk_hw *hw, unsigned long rate, unsigned long parent_rate) { struct hi3660_stub_clk *stub_clk = to_stub_clk(hw); stub_clk->msg[0] = stub_clk->cmd; stub_clk->msg[1] = rate / MHZ; dev_dbg(stub_clk_chan.cl.dev, "set rate msg[0]=0x%x msg[1]=0x%x\n", stub_clk->msg[0], stub_clk->msg[1]); mbox_send_message(stub_clk_chan.mbox, stub_clk->msg); mbox_client_txdone(stub_clk_chan.mbox, 0); stub_clk->rate = rate; return 0; } static const struct clk_ops hi3660_stub_clk_ops = { .recalc_rate = hi3660_stub_clk_recalc_rate, .round_rate = hi3660_stub_clk_round_rate, .set_rate = hi3660_stub_clk_set_rate, }; static struct hi3660_stub_clk hi3660_stub_clks[HI3660_CLK_STUB_NUM] = { DEFINE_CLK_STUB(HI3660_CLK_STUB_CLUSTER0, 0x0001030A, "cpu-cluster.0") DEFINE_CLK_STUB(HI3660_CLK_STUB_CLUSTER1, 0x0002030A, "cpu-cluster.1") DEFINE_CLK_STUB(HI3660_CLK_STUB_GPU, 0x0003030A, "clk-g3d") DEFINE_CLK_STUB(HI3660_CLK_STUB_DDR, 0x00040309, "clk-ddrc") }; static struct clk_hw *hi3660_stub_clk_hw_get(struct of_phandle_args *clkspec, void *data) { unsigned int idx = clkspec->args[0]; if (idx >= HI3660_CLK_STUB_NUM) { pr_err("%s: invalid index %u\n", __func__, idx); return ERR_PTR(-EINVAL); } return &hi3660_stub_clks[idx].hw; } static int hi3660_stub_clk_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct resource *res; unsigned int i; int ret; /* Use mailbox client without blocking */ stub_clk_chan.cl.dev = dev; stub_clk_chan.cl.tx_done = NULL; stub_clk_chan.cl.tx_block = false; stub_clk_chan.cl.knows_txdone = false; /* Allocate mailbox channel */ stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0); if (IS_ERR(stub_clk_chan.mbox)) return PTR_ERR(stub_clk_chan.mbox); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -EINVAL; freq_reg = devm_ioremap(dev, res->start, resource_size(res)); if (!freq_reg) return -ENOMEM; freq_reg += HI3660_STUB_CLOCK_DATA; for (i = 0; i < HI3660_CLK_STUB_NUM; i++) { ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw); if (ret) return ret; } return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get, hi3660_stub_clks); } static const struct of_device_id hi3660_stub_clk_of_match[] = { { .compatible = "hisilicon,hi3660-stub-clk", }, {} }; static struct platform_driver hi3660_stub_clk_driver = { .probe = hi3660_stub_clk_probe, .driver = { .name = "hi3660-stub-clk", .of_match_table = hi3660_stub_clk_of_match, }, }; static int __init hi3660_stub_clk_init(void) { return platform_driver_register(&hi3660_stub_clk_driver); } subsys_initcall(hi3660_stub_clk_init);
./CrossVul/dataset_final_sorted/CWE-476/c/good_75_0
crossvul-cpp_data_good_5217_0
/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2014 Nexenta Systems, Inc. All rights reserved. * Copyright 2016 Syneto S.R.L. All rights reserved. */ /* * Dispatch function for SMB2_FLUSH */ #include <smbsrv/smb2_kproto.h> #include <smbsrv/smb_fsops.h> smb_sdrc_t smb2_flush(smb_request_t *sr) { uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, "wwlqq", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } smb_ofile_flush(sr, sr->fid_ofile); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, "wwl", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_5217_0
crossvul-cpp_data_bad_3223_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * I/O Stream Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ /* The configuration header file should be included first. */ #include "jasper/jas_config.h" #include <assert.h> #if defined(JAS_HAVE_FCNTL_H) #include <fcntl.h> #endif #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #if defined(JAS_HAVE_UNISTD_H) #include <unistd.h> #endif #if defined(WIN32) || defined(JAS_HAVE_IO_H) #include <io.h> #endif #include "jasper/jas_debug.h" #include "jasper/jas_types.h" #include "jasper/jas_stream.h" #include "jasper/jas_malloc.h" #include "jasper/jas_math.h" /******************************************************************************\ * Local function prototypes. \******************************************************************************/ static int jas_strtoopenmode(const char *s); static void jas_stream_destroy(jas_stream_t *stream); static jas_stream_t *jas_stream_create(void); static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize); static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt); static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt); static long mem_seek(jas_stream_obj_t *obj, long offset, int origin); static int mem_close(jas_stream_obj_t *obj); static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt); static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt); static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin); static int sfile_close(jas_stream_obj_t *obj); static int file_read(jas_stream_obj_t *obj, char *buf, int cnt); static int file_write(jas_stream_obj_t *obj, char *buf, int cnt); static long file_seek(jas_stream_obj_t *obj, long offset, int origin); static int file_close(jas_stream_obj_t *obj); /******************************************************************************\ * Local data. \******************************************************************************/ static jas_stream_ops_t jas_stream_fileops = { file_read, file_write, file_seek, file_close }; static jas_stream_ops_t jas_stream_sfileops = { sfile_read, sfile_write, sfile_seek, sfile_close }; static jas_stream_ops_t jas_stream_memops = { mem_read, mem_write, mem_seek, mem_close }; /******************************************************************************\ * Code for opening and closing streams. \******************************************************************************/ static jas_stream_t *jas_stream_create() { jas_stream_t *stream; if (!(stream = jas_malloc(sizeof(jas_stream_t)))) { return 0; } stream->openmode_ = 0; stream->bufmode_ = 0; stream->flags_ = 0; stream->bufbase_ = 0; stream->bufstart_ = 0; stream->bufsize_ = 0; stream->ptr_ = 0; stream->cnt_ = 0; stream->ops_ = 0; stream->obj_ = 0; stream->rwcnt_ = 0; stream->rwlimit_ = -1; return stream; } #if 0 /* Obsolete code. */ jas_stream_t *jas_stream_memopen(char *buf, int bufsize) { jas_stream_t *stream; jas_stream_memobj_t *obj; JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize)); if (!(stream = jas_stream_create())) { return 0; } /* A stream associated with a memory buffer is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Since the stream data is already resident in memory, buffering is not necessary. */ /* But... It still may be faster to use buffering anyways. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a memory stream. */ stream->ops_ = &jas_stream_memops; /* Allocate memory for the underlying memory stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { jas_stream_destroy(stream); return 0; } stream->obj_ = (void *) obj; /* Initialize a few important members of the memory stream object. */ obj->myalloc_ = 0; obj->buf_ = 0; /* If the buffer size specified is nonpositive, then the buffer is allocated internally and automatically grown as needed. */ if (bufsize <= 0) { obj->bufsize_ = 1024; obj->growable_ = 1; } else { obj->bufsize_ = bufsize; obj->growable_ = 0; } if (buf) { obj->buf_ = (unsigned char *) buf; } else { obj->buf_ = jas_malloc(obj->bufsize_); obj->myalloc_ = 1; } if (!obj->buf_) { jas_stream_close(stream); return 0; } JAS_DBGLOG(100, ("jas_stream_memopen buffer buf=%p myalloc=%d\n", obj->buf_, obj->myalloc_)); if (bufsize > 0 && buf) { /* If a buffer was supplied by the caller and its length is positive, make the associated buffer data appear in the stream initially. */ obj->len_ = bufsize; } else { /* The stream is initially empty. */ obj->len_ = 0; } obj->pos_ = 0; return stream; } #else /* This function will eventually replace jas_stream_memopen. If buf is 0 and bufsize > 0: a buffer is dynamically allocated with size bufsize and this buffer is not growable. If buf is 0 and bufsize is 0: a buffer is dynamically allocated whose size will automatically grow to accommodate the amount of data written. If buf is not 0: bufsize (which, in this case, is not currently allowed to be zero) is the size of the (nongrowable) buffer pointed to by buf. */ jas_stream_t *jas_stream_memopen2(char *buf, size_t bufsize) { jas_stream_t *stream; jas_stream_memobj_t *obj; JAS_DBGLOG(100, ("jas_stream_memopen2(%p, %zu)\n", buf, bufsize)); assert((buf && bufsize > 0) || (!buf)); if (!(stream = jas_stream_create())) { return 0; } /* A stream associated with a memory buffer is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Since the stream data is already resident in memory, buffering is not necessary. */ /* But... It still may be faster to use buffering anyways. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a memory stream. */ stream->ops_ = &jas_stream_memops; /* Allocate memory for the underlying memory stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { jas_stream_destroy(stream); return 0; } stream->obj_ = (void *) obj; /* Initialize a few important members of the memory stream object. */ obj->myalloc_ = 0; obj->buf_ = 0; /* If the buffer size specified is nonpositive, then the buffer is allocated internally and automatically grown as needed. */ if (!bufsize) { obj->bufsize_ = 1024; obj->growable_ = 1; } else { obj->bufsize_ = bufsize; obj->growable_ = 0; } if (buf) { obj->buf_ = JAS_CAST(unsigned char *, buf); } else { obj->buf_ = jas_malloc(obj->bufsize_); obj->myalloc_ = 1; } if (!obj->buf_) { jas_stream_close(stream); return 0; } JAS_DBGLOG(100, ("jas_stream_memopen2 buffer buf=%p myalloc=%d\n", obj->buf_, obj->myalloc_)); if (bufsize > 0 && buf) { /* If a buffer was supplied by the caller and its length is positive, make the associated buffer data appear in the stream initially. */ obj->len_ = bufsize; } else { /* The stream is initially empty. */ obj->len_ = 0; } obj->pos_ = 0; return stream; } /* NOTE: The version of the function jas_stream_memopen only exists for backwards compatibility. Eventually, it should be replaced by jas_stream_memopen2. In retrospect, it was a very poor choice to have specified the buffer size parameter (bufsize) to have type int. On some machines, int may only be a 16-bit integer. This precludes larger-sized buffer allocations, which are needed in practice. If bufsize <= 0, the buffer is growable; otherwise, the buffer has a fixed size of bufsize. If buf is 0, the buffer is dynamically allocated with jas_malloc. If buf is not 0 and bufsize <= 0 (which is not permitted in any circumstances), bad things will happen (especially if the buf was not allocated with jas_malloc). */ jas_stream_t *jas_stream_memopen(char *buf, int bufsize) { char *new_buf; size_t new_bufsize; JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize)); if (bufsize < 0) { jas_deprecated("negative buffer size for jas_stream_memopen"); } if (buf && bufsize <= 0) { // This was never a valid thing to do with the old API. jas_eprintf("Invalid use of jas_stream_memopen detected.\n"); jas_deprecated("A user-provided buffer for " "jas_stream_memopen cannot be growable.\n"); } if (bufsize <= 0) { new_bufsize = 0; new_buf = 0; } else { new_bufsize = bufsize; new_buf = buf; } return jas_stream_memopen2(new_buf, new_bufsize); } #endif jas_stream_t *jas_stream_fopen(const char *filename, const char *mode) { jas_stream_t *stream; jas_stream_fileobj_t *obj; int openflags; JAS_DBGLOG(100, ("jas_stream_fopen(\"%s\", \"%s\")\n", filename, mode)); /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); /* Determine the correct flags to use for opening the file. */ if ((stream->openmode_ & JAS_STREAM_READ) && (stream->openmode_ & JAS_STREAM_WRITE)) { openflags = O_RDWR; } else if (stream->openmode_ & JAS_STREAM_READ) { openflags = O_RDONLY; } else if (stream->openmode_ & JAS_STREAM_WRITE) { openflags = O_WRONLY; } else { openflags = 0; } if (stream->openmode_ & JAS_STREAM_APPEND) { openflags |= O_APPEND; } if (stream->openmode_ & JAS_STREAM_BINARY) { openflags |= O_BINARY; } if (stream->openmode_ & JAS_STREAM_CREATE) { openflags |= O_CREAT | O_TRUNC; } /* Allocate space for the underlying file stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = -1; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = (void *) obj; /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_fileops; /* Open the underlying file. */ if ((obj->fd = open(filename, openflags, JAS_STREAM_PERMS)) < 0) { // Free the underlying file object, since it will not otherwise // be freed. jas_free(obj); jas_stream_destroy(stream); return 0; } /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); return stream; } jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp) { jas_stream_t *stream; int openflags; JAS_DBGLOG(100, ("jas_stream_freopen(\"%s\", \"%s\", %p)\n", path, mode, fp)); /* Eliminate compiler warning about unused variable. */ path = 0; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); /* Determine the correct flags to use for opening the file. */ if ((stream->openmode_ & JAS_STREAM_READ) && (stream->openmode_ & JAS_STREAM_WRITE)) { openflags = O_RDWR; } else if (stream->openmode_ & JAS_STREAM_READ) { openflags = O_RDONLY; } else if (stream->openmode_ & JAS_STREAM_WRITE) { openflags = O_WRONLY; } else { openflags = 0; } if (stream->openmode_ & JAS_STREAM_APPEND) { openflags |= O_APPEND; } if (stream->openmode_ & JAS_STREAM_BINARY) { openflags |= O_BINARY; } if (stream->openmode_ & JAS_STREAM_CREATE) { openflags |= O_CREAT | O_TRUNC; } stream->obj_ = JAS_CAST(void *, fp); /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_sfileops; /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); return stream; } jas_stream_t *jas_stream_tmpfile() { jas_stream_t *stream; jas_stream_fileobj_t *obj; JAS_DBGLOG(100, ("jas_stream_tmpfile()\n")); if (!(stream = jas_stream_create())) { return 0; } /* A temporary file stream is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Allocate memory for the underlying temporary file object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = -1; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = obj; /* Choose a file name. */ tmpnam(obj->pathname); /* Open the underlying file. */ if ((obj->fd = open(obj->pathname, O_CREAT | O_EXCL | O_RDWR | O_TRUNC | O_BINARY, JAS_STREAM_PERMS)) < 0) { jas_stream_destroy(stream); return 0; } /* Unlink the file so that it will disappear if the program terminates abnormally. */ /* Under UNIX, one can unlink an open file and continue to do I/O on it. Not all operating systems support this functionality, however. For example, under Microsoft Windows the unlink operation will fail, since the file is open. */ if (unlink(obj->pathname)) { /* We will try unlinking the file again after it is closed. */ obj->flags |= JAS_STREAM_FILEOBJ_DELONCLOSE; } /* Use full buffering. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); stream->ops_ = &jas_stream_fileops; return stream; } jas_stream_t *jas_stream_fdopen(int fd, const char *mode) { jas_stream_t *stream; jas_stream_fileobj_t *obj; JAS_DBGLOG(100, ("jas_stream_fdopen(%d, \"%s\")\n", fd, mode)); /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); #if defined(WIN32) /* Argh!!! Someone ought to banish text mode (i.e., O_TEXT) to the greatest depths of purgatory! */ /* Ensure that the file descriptor is in binary mode, if the caller has specified the binary mode flag. Arguably, the caller ought to take care of this, but text mode is a ugly wart anyways, so we save the caller some grief by handling this within the stream library. */ /* This ugliness is mainly for the benefit of those who run the JasPer software under Windows from shells that insist on opening files in text mode. For example, in the Cygwin environment, shells often open files in text mode when I/O redirection is used. Grr... */ if (stream->openmode_ & JAS_STREAM_BINARY) { setmode(fd, O_BINARY); } #endif /* Allocate space for the underlying file stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = fd; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = (void *) obj; /* Do not close the underlying file descriptor when the stream is closed. */ obj->flags |= JAS_STREAM_FILEOBJ_NOCLOSE; /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_fileops; return stream; } static void jas_stream_destroy(jas_stream_t *stream) { JAS_DBGLOG(100, ("jas_stream_destroy(%p)\n", stream)); /* If the memory for the buffer was allocated with malloc, free this memory. */ if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) { JAS_DBGLOG(100, ("jas_stream_destroy freeing buffer %p\n", stream->bufbase_)); jas_free(stream->bufbase_); stream->bufbase_ = 0; } jas_free(stream); } int jas_stream_close(jas_stream_t *stream) { JAS_DBGLOG(100, ("jas_stream_close(%p)\n", stream)); /* Flush buffer if necessary. */ jas_stream_flush(stream); /* Close the underlying stream object. */ (*stream->ops_->close_)(stream->obj_); jas_stream_destroy(stream); return 0; } /******************************************************************************\ * Code for reading and writing streams. \******************************************************************************/ int jas_stream_getc_func(jas_stream_t *stream) { assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ + JAS_STREAM_MAXPUTBACK); return jas_stream_getc_macro(stream); } int jas_stream_putc_func(jas_stream_t *stream, int c) { assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); return jas_stream_putc_macro(stream, c); } int jas_stream_ungetc(jas_stream_t *stream, int c) { if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) { return -1; } /* Reset the EOF indicator (since we now have at least one character to read). */ stream->flags_ &= ~JAS_STREAM_EOF; --stream->rwcnt_; --stream->ptr_; ++stream->cnt_; *stream->ptr_ = c; return 0; } int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; JAS_DBGLOG(100, ("jas_stream_read(%p, %p, %d)\n", stream, buf, cnt)); if (cnt < 0) { jas_deprecated("negative count for jas_stream_read"); } bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; } int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; JAS_DBGLOG(100, ("jas_stream_write(%p, %p, %d)\n", stream, buf, cnt)); if (cnt < 0) { jas_deprecated("negative count for jas_stream_write"); } bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } /* Note: This function uses a fixed size buffer. Therefore, it cannot handle invocations that will produce more output than can be held by the buffer. */ int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...) { va_list ap; char buf[4096]; int ret; va_start(ap, fmt); ret = vsnprintf(buf, sizeof buf, fmt, ap); jas_stream_puts(stream, buf); va_end(ap); return ret; } int jas_stream_puts(jas_stream_t *stream, const char *s) { while (*s != '\0') { if (jas_stream_putc_macro(stream, *s) == EOF) { return -1; } ++s; } return 0; } char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize) { int c; char *bufptr; assert(bufsize > 0); JAS_DBGLOG(100, ("jas_stream_gets(%p, %p, %d)\n", stream, buf, bufsize)); bufptr = buf; while (bufsize > 1) { if ((c = jas_stream_getc(stream)) == EOF) { break; } *bufptr++ = c; --bufsize; if (c == '\n') { break; } } *bufptr = '\0'; return buf; } int jas_stream_gobble(jas_stream_t *stream, int n) { int m; JAS_DBGLOG(100, ("jas_stream_gobble(%p, %d)\n", stream, n)); if (n < 0) { jas_deprecated("negative count for jas_stream_gobble"); } m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } int jas_stream_pad(jas_stream_t *stream, int n, int c) { int m; JAS_DBGLOG(100, ("jas_stream_pad(%p, %d, %d)\n", stream, n, c)); if (n < 0) { jas_deprecated("negative count for jas_stream_pad"); } m = n; for (m = n; m > 0; --m) { if (jas_stream_putc(stream, c) == EOF) return n - m; } return n; } /******************************************************************************\ * Code for getting and setting the stream position. \******************************************************************************/ int jas_stream_isseekable(jas_stream_t *stream) { if (stream->ops_ == &jas_stream_memops) { return 1; } else if (stream->ops_ == &jas_stream_fileops) { if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) { return 0; } return 1; } else { return 0; } } int jas_stream_rewind(jas_stream_t *stream) { JAS_DBGLOG(100, ("jas_stream_rewind(%p)\n", stream)); return jas_stream_seek(stream, 0, SEEK_SET); } long jas_stream_seek(jas_stream_t *stream, long offset, int origin) { long newpos; JAS_DBGLOG(100, ("jas_stream_seek(%p, %ld, %d)\n", stream, offset, origin)); /* The buffer cannot be in use for both reading and writing. */ assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ & JAS_STREAM_WRBUF))); /* Reset the EOF indicator (since we may not be at the EOF anymore). */ stream->flags_ &= ~JAS_STREAM_EOF; if (stream->bufmode_ & JAS_STREAM_RDBUF) { if (origin == SEEK_CUR) { offset -= stream->cnt_; } } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { if (jas_stream_flush(stream)) { return -1; } } stream->cnt_ = 0; stream->ptr_ = stream->bufstart_; stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF); if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin)) < 0) { return -1; } return newpos; } long jas_stream_tell(jas_stream_t *stream) { int adjust; int offset; JAS_DBGLOG(100, ("jas_stream_tell(%p)\n", stream)); if (stream->bufmode_ & JAS_STREAM_RDBUF) { adjust = -stream->cnt_; } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { adjust = stream->ptr_ - stream->bufstart_; } else { adjust = 0; } if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) { return -1; } return offset + adjust; } /******************************************************************************\ * Buffer initialization code. \******************************************************************************/ static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize) { /* If this function is being called, the buffer should not have been initialized yet. */ assert(!stream->bufbase_); if (bufmode != JAS_STREAM_UNBUF) { /* The full- or line-buffered mode is being employed. */ if (!buf) { /* The caller has not specified a buffer to employ, so allocate one. */ if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + JAS_STREAM_MAXPUTBACK))) { stream->bufmode_ |= JAS_STREAM_FREEBUF; stream->bufsize_ = JAS_STREAM_BUFSIZE; } else { /* The buffer allocation has failed. Resort to unbuffered operation. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } } else { /* The caller has specified a buffer to employ. */ /* The buffer must be large enough to accommodate maximum putback. */ assert(bufsize > JAS_STREAM_MAXPUTBACK); stream->bufbase_ = JAS_CAST(jas_uchar *, buf); stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; } } else { /* The unbuffered mode is being employed. */ /* A buffer should not have been supplied by the caller. */ assert(!buf); /* Use a trivial one-character buffer. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; stream->ptr_ = stream->bufstart_; stream->cnt_ = 0; stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; } /******************************************************************************\ * Buffer filling and flushing code. \******************************************************************************/ int jas_stream_flush(jas_stream_t *stream) { if (stream->bufmode_ & JAS_STREAM_RDBUF) { return 0; } return jas_stream_flushbuf(stream, EOF); } int jas_stream_fillbuf(jas_stream_t *stream, int getflag) { int c; /* The stream must not be in an error or EOF state. */ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { return EOF; } /* The stream must be open for reading. */ if ((stream->openmode_ & JAS_STREAM_READ) == 0) { return EOF; } /* Make a half-hearted attempt to confirm that the buffer is not currently being used for writing. This check is not intended to be foolproof! */ assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0); assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); /* Mark the buffer as being used for reading. */ stream->bufmode_ |= JAS_STREAM_RDBUF; /* Read new data into the buffer. */ stream->ptr_ = stream->bufstart_; if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_, (char *) stream->bufstart_, stream->bufsize_)) <= 0) { if (stream->cnt_ < 0) { stream->flags_ |= JAS_STREAM_ERR; } else { stream->flags_ |= JAS_STREAM_EOF; } stream->cnt_ = 0; return EOF; } assert(stream->cnt_ > 0); /* Get or peek at the first character in the buffer. */ c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_); return c; } int jas_stream_flushbuf(jas_stream_t *stream, int c) { int len; int n; /* The stream should not be in an error or EOF state. */ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { return EOF; } /* The stream must be open for writing. */ if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) { return EOF; } /* The buffer should not currently be in use for reading. */ assert(!(stream->bufmode_ & JAS_STREAM_RDBUF)); /* Note: Do not use the quantity stream->cnt to determine the number of characters in the buffer! Depending on how this function was called, the stream->cnt value may be "off-by-one". */ len = stream->ptr_ - stream->bufstart_; if (len > 0) { n = (*stream->ops_->write_)(stream->obj_, (char *) stream->bufstart_, len); if (n != len) { stream->flags_ |= JAS_STREAM_ERR; return EOF; } } stream->cnt_ = stream->bufsize_; stream->ptr_ = stream->bufstart_; stream->bufmode_ |= JAS_STREAM_WRBUF; if (c != EOF) { assert(stream->cnt_ > 0); return jas_stream_putc2(stream, c); } return 0; } /******************************************************************************\ * Miscellaneous code. \******************************************************************************/ static int jas_strtoopenmode(const char *s) { int openmode = 0; while (*s != '\0') { switch (*s) { case 'r': openmode |= JAS_STREAM_READ; break; case 'w': openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE; break; case 'b': openmode |= JAS_STREAM_BINARY; break; case 'a': openmode |= JAS_STREAM_APPEND; break; case '+': openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE; break; default: break; } ++s; } return openmode; } int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n) { int all; int c; int m; all = (n < 0) ? 1 : 0; m = n; while (all || m > 0) { if ((c = jas_stream_getc_macro(in)) == EOF) { /* The next character of input could not be read. */ /* Return with an error if an I/O error occured (not including EOF) or if an explicit copy count was specified. */ return (!all || jas_stream_error(in)) ? (-1) : 0; } if (jas_stream_putc_macro(out, c) == EOF) { return -1; } --m; } return 0; } long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt) { int old; old = stream->rwcnt_; stream->rwcnt_ = rwcnt; return old; } int jas_stream_display(jas_stream_t *stream, FILE *fp, int n) { unsigned char buf[16]; int i; int j; int m; int c; int display; int cnt; cnt = n - (n % 16); display = 1; for (i = 0; i < n; i += 16) { if (n > 16 && i > 0) { display = (i >= cnt) ? 1 : 0; } if (display) { fprintf(fp, "%08x:", i); } m = JAS_MIN(n - i, 16); for (j = 0; j < m; ++j) { if ((c = jas_stream_getc(stream)) == EOF) { abort(); return -1; } buf[j] = c; } if (display) { for (j = 0; j < m; ++j) { fprintf(fp, " %02x", buf[j]); } fputc(' ', fp); for (; j < 16; ++j) { fprintf(fp, " "); } for (j = 0; j < m; ++j) { if (isprint(buf[j])) { fputc(buf[j], fp); } else { fputc(' ', fp); } } fprintf(fp, "\n"); } } return 0; } long jas_stream_length(jas_stream_t *stream) { long oldpos; long pos; if ((oldpos = jas_stream_tell(stream)) < 0) { return -1; } if (jas_stream_seek(stream, 0, SEEK_END) < 0) { return -1; } if ((pos = jas_stream_tell(stream)) < 0) { return -1; } if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) { return -1; } return pos; } /******************************************************************************\ * Memory stream object. \******************************************************************************/ static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt) { ssize_t n; assert(cnt >= 0); assert(buf); JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt)); jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; n = m->len_ - m->pos_; cnt = JAS_MIN(n, cnt); memcpy(buf, &m->buf_[m->pos_], cnt); m->pos_ += cnt; return cnt; } static int mem_resize(jas_stream_memobj_t *m, size_t bufsize) { unsigned char *buf; //assert(m->buf_); //assert(bufsize >= 0); JAS_DBGLOG(100, ("mem_resize(%p, %zu)\n", m, bufsize)); if (!bufsize) { jas_eprintf( "mem_resize was not really designed to handle a buffer of size 0\n" "This may not work.\n" ); } if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, ("mem_resize realloc failed\n")); return -1; } JAS_DBGLOG(100, ("mem_resize realloc succeeded\n")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; } static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt) { size_t n; int ret; jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; size_t newbufsize; size_t newpos; assert(buf); assert(cnt >= 0); JAS_DBGLOG(100, ("mem_write(%p, %p, %d)\n", obj, buf, cnt)); newpos = m->pos_ + cnt; if (newpos > m->bufsize_ && m->growable_) { newbufsize = m->bufsize_; while (newbufsize < newpos) { //newbufsize <<= 1; if (!jas_safe_size_mul(newbufsize, 2, &newbufsize)) { JAS_DBGLOG(100, ("new buffer size would cause overflow\n")); return -1; } } JAS_DBGLOG(100, ("mem_write resizing from %d to %zu\n", m->bufsize_, newbufsize)); assert(newbufsize > 0); if (mem_resize(m, newbufsize)) { return -1; } } if (m->pos_ > m->len_) { /* The current position is beyond the end of the file, so pad the file to the current position with zeros. */ n = JAS_MIN(m->pos_, m->bufsize_) - m->len_; if (n > 0) { memset(&m->buf_[m->len_], 0, n); m->len_ += n; } if (m->pos_ != m->len_) { /* The buffer is not big enough. */ return 0; } } n = m->bufsize_ - m->pos_; ret = JAS_MIN(n, cnt); if (ret > 0) { memcpy(&m->buf_[m->pos_], buf, ret); m->pos_ += ret; } if (m->pos_ > m->len_) { m->len_ = m->pos_; } assert(ret == cnt); return ret; } static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; size_t newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; } static int mem_close(jas_stream_obj_t *obj) { JAS_DBGLOG(100, ("mem_close(%p)\n", obj)); jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; JAS_DBGLOG(100, ("mem_close myalloc=%d\n", m->myalloc_)); if (m->myalloc_ && m->buf_) { JAS_DBGLOG(100, ("mem_close freeing buffer %p\n", m->buf_)); jas_free(m->buf_); m->buf_ = 0; } jas_free(obj); return 0; } /******************************************************************************\ * File stream object. \******************************************************************************/ static int file_read(jas_stream_obj_t *obj, char *buf, int cnt) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_read(%p, %p, %d)\n", obj, buf, cnt)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return read(fileobj->fd, buf, cnt); } static int file_write(jas_stream_obj_t *obj, char *buf, int cnt) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_write(%p, %p, %d)\n", obj, buf, cnt)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return write(fileobj->fd, buf, cnt); } static long file_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_seek(%p, %ld, %d)\n", obj, offset, origin)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return lseek(fileobj->fd, offset, origin); } static int file_close(jas_stream_obj_t *obj) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_close(%p)\n", obj)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); int ret; ret = close(fileobj->fd); if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) { unlink(fileobj->pathname); } jas_free(fileobj); return ret; } /******************************************************************************\ * Stdio file stream object. \******************************************************************************/ static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt) { FILE *fp; size_t n; int result; JAS_DBGLOG(100, ("sfile_read(%p, %p, %d)\n", obj, buf, cnt)); fp = JAS_CAST(FILE *, obj); n = fread(buf, 1, cnt, fp); if (n != cnt) { result = (!ferror(fp) && feof(fp)) ? 0 : -1; } result = JAS_CAST(int, n); return result; } static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt) { FILE *fp; size_t n; JAS_DBGLOG(100, ("sfile_write(%p, %p, %d)\n", obj, buf, cnt)); fp = JAS_CAST(FILE *, obj); n = fwrite(buf, 1, cnt, fp); return (n != JAS_CAST(size_t, cnt)) ? (-1) : cnt; } static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin) { FILE *fp; JAS_DBGLOG(100, ("sfile_seek(%p, %ld, %d)\n", obj, offset, origin)); fp = JAS_CAST(FILE *, obj); return fseek(fp, offset, origin); } static int sfile_close(jas_stream_obj_t *obj) { FILE *fp; JAS_DBGLOG(100, ("sfile_close(%p)\n", obj)); fp = JAS_CAST(FILE *, obj); return fclose(fp); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3223_0
crossvul-cpp_data_bad_3060_10
/* Large capacity key type * * Copyright (C) 2013 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 <linux/module.h> #include <linux/init.h> #include <linux/seq_file.h> #include <linux/file.h> #include <linux/shmem_fs.h> #include <linux/err.h> #include <keys/user-type.h> #include <keys/big_key-type.h> MODULE_LICENSE("GPL"); /* * If the data is under this limit, there's no point creating a shm file to * hold it as the permanently resident metadata for the shmem fs will be at * least as large as the data. */ #define BIG_KEY_FILE_THRESHOLD (sizeof(struct inode) + sizeof(struct dentry)) /* * big_key defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_big_key = { .name = "big_key", .preparse = big_key_preparse, .free_preparse = big_key_free_preparse, .instantiate = generic_key_instantiate, .match = user_match, .revoke = big_key_revoke, .destroy = big_key_destroy, .describe = big_key_describe, .read = big_key_read, }; /* * Preparse a big key */ int big_key_preparse(struct key_preparsed_payload *prep) { struct path *path = (struct path *)&prep->payload; struct file *file; ssize_t written; size_t datalen = prep->datalen; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 1024 * 1024 || !prep->data) goto error; /* Set an arbitrary quota */ prep->quotalen = 16; prep->type_data[1] = (void *)(unsigned long)datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { /* Create a shmem file to store the data in. This will permit the data * to be swapped out if needed. * * TODO: Encrypt the stored data with a temporary key. */ file = shmem_kernel_file_setup("", datalen, 0); if (IS_ERR(file)) { ret = PTR_ERR(file); goto error; } written = kernel_write(file, prep->data, prep->datalen, 0); if (written != datalen) { ret = written; if (written >= 0) ret = -ENOMEM; goto err_fput; } /* Pin the mount and dentry to the key so that we can open it again * later */ *path = file->f_path; path_get(path); fput(file); } else { /* Just store the data in a buffer */ void *data = kmalloc(datalen, GFP_KERNEL); if (!data) return -ENOMEM; prep->payload[0] = memcpy(data, prep->data, prep->datalen); } return 0; err_fput: fput(file); error: return ret; } /* * Clear preparsement. */ void big_key_free_preparse(struct key_preparsed_payload *prep) { if (prep->datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&prep->payload; path_put(path); } else { kfree(prep->payload[0]); } } /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data2; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_instantiated(key) && key->type_data.x[1] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } /* * dispose of the data dangling from the corpse of a big_key key */ void big_key_destroy(struct key *key) { if (key->type_data.x[1] > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data2; path_put(path); path->mnt = NULL; path->dentry = NULL; } else { kfree(key->payload.data); key->payload.data = NULL; } } /* * describe the big_key key */ void big_key_describe(const struct key *key, struct seq_file *m) { unsigned long datalen = key->type_data.x[1]; seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %lu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } /* * read the key data * - the key's semaphore is read-locked */ long big_key_read(const struct key *key, char __user *buffer, size_t buflen) { unsigned long datalen = key->type_data.x[1]; long ret; if (!buffer || buflen < datalen) return datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data2; struct file *file; loff_t pos; file = dentry_open(path, O_RDONLY, current_cred()); if (IS_ERR(file)) return PTR_ERR(file); pos = 0; ret = vfs_read(file, buffer, datalen, &pos); fput(file); if (ret >= 0 && ret != datalen) ret = -EIO; } else { ret = datalen; if (copy_to_user(buffer, key->payload.data, datalen) != 0) ret = -EFAULT; } return ret; } /* * Module stuff */ static int __init big_key_init(void) { return register_key_type(&key_type_big_key); } static void __exit big_key_cleanup(void) { unregister_key_type(&key_type_big_key); } module_init(big_key_init); module_exit(big_key_cleanup);
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3060_10
crossvul-cpp_data_good_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 >= 4 && 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 >= 4 && 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/good_828_0
crossvul-cpp_data_bad_914_0
/********************************************************************** regcomp.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2019 K.Kosako <sndgk393 AT ybb DOT ne 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" #define OPS_INIT_SIZE 8 OnigCaseFoldType OnigDefaultCaseFoldFlag = ONIGENC_CASE_FOLD_MIN; #if 0 typedef struct { int n; int alloc; int* v; } int_stack; static int make_int_stack(int_stack** rs, int init_size) { int_stack* s; int* v; *rs = 0; s = xmalloc(sizeof(*s)); if (IS_NULL(s)) return ONIGERR_MEMORY; v = (int* )xmalloc(sizeof(int) * init_size); if (IS_NULL(v)) { xfree(s); return ONIGERR_MEMORY; } s->n = 0; s->alloc = init_size; s->v = v; *rs = s; return ONIG_NORMAL; } static void free_int_stack(int_stack* s) { if (IS_NOT_NULL(s)) { if (IS_NOT_NULL(s->v)) xfree(s->v); xfree(s); } } static int int_stack_push(int_stack* s, int v) { if (s->n >= s->alloc) { int new_size = s->alloc * 2; int* nv = (int* )xrealloc(s->v, sizeof(int) * new_size); if (IS_NULL(nv)) return ONIGERR_MEMORY; s->alloc = new_size; s->v = nv; } s->v[s->n] = v; s->n++; return ONIG_NORMAL; } static int int_stack_pop(int_stack* s) { int v; #ifdef ONIG_DEBUG if (s->n <= 0) { fprintf(stderr, "int_stack_pop: fail empty. %p\n", s); return 0; } #endif v = s->v[s->n]; s->n--; return v; } #endif static int ops_init(regex_t* reg, int init_alloc_size) { Operation* p; size_t size; if (init_alloc_size > 0) { size = sizeof(Operation) * init_alloc_size; p = (Operation* )xrealloc(reg->ops, size); CHECK_NULL_RETURN_MEMERR(p); #ifdef USE_DIRECT_THREADED_CODE { enum OpCode* cp; size = sizeof(enum OpCode) * init_alloc_size; cp = (enum OpCode* )xrealloc(reg->ocs, size); CHECK_NULL_RETURN_MEMERR(cp); reg->ocs = cp; } #endif } else { p = (Operation* )0; #ifdef USE_DIRECT_THREADED_CODE reg->ocs = (enum OpCode* )0; #endif } reg->ops = p; reg->ops_curr = 0; /* !!! not yet done ops_new() */ reg->ops_alloc = init_alloc_size; reg->ops_used = 0; return ONIG_NORMAL; } static int ops_expand(regex_t* reg, int n) { #define MIN_OPS_EXPAND_SIZE 4 #ifdef USE_DIRECT_THREADED_CODE enum OpCode* cp; #endif Operation* p; size_t size; if (n <= 0) n = MIN_OPS_EXPAND_SIZE; n += reg->ops_alloc; size = sizeof(Operation) * n; p = (Operation* )xrealloc(reg->ops, size); CHECK_NULL_RETURN_MEMERR(p); #ifdef USE_DIRECT_THREADED_CODE size = sizeof(enum OpCode) * n; cp = (enum OpCode* )xrealloc(reg->ocs, size); CHECK_NULL_RETURN_MEMERR(cp); reg->ocs = cp; #endif reg->ops = p; reg->ops_alloc = n; if (reg->ops_used == 0) reg->ops_curr = 0; else reg->ops_curr = reg->ops + (reg->ops_used - 1); return ONIG_NORMAL; } static int ops_new(regex_t* reg) { int r; if (reg->ops_used >= reg->ops_alloc) { r = ops_expand(reg, reg->ops_alloc); if (r != ONIG_NORMAL) return r; } reg->ops_curr = reg->ops + reg->ops_used; reg->ops_used++; xmemset(reg->ops_curr, 0, sizeof(Operation)); return ONIG_NORMAL; } static int is_in_string_pool(regex_t* reg, UChar* s) { return (s >= reg->string_pool && s < reg->string_pool_end); } static void ops_free(regex_t* reg) { int i; if (IS_NULL(reg->ops)) return ; for (i = 0; i < (int )reg->ops_used; i++) { enum OpCode opcode; Operation* op; op = reg->ops + i; #ifdef USE_DIRECT_THREADED_CODE opcode = *(reg->ocs + i); #else opcode = op->opcode; #endif switch (opcode) { case OP_EXACTMBN: if (! is_in_string_pool(reg, op->exact_len_n.s)) xfree(op->exact_len_n.s); break; case OP_EXACTN: case OP_EXACTMB2N: case OP_EXACTMB3N: case OP_EXACTN_IC: if (! is_in_string_pool(reg, op->exact_n.s)) xfree(op->exact_n.s); break; case OP_EXACT1: case OP_EXACT2: case OP_EXACT3: case OP_EXACT4: case OP_EXACT5: case OP_EXACTMB2N1: case OP_EXACTMB2N2: case OP_EXACTMB2N3: case OP_EXACT1_IC: break; case OP_CCLASS_NOT: case OP_CCLASS: xfree(op->cclass.bsp); break; case OP_CCLASS_MB_NOT: case OP_CCLASS_MB: xfree(op->cclass_mb.mb); break; case OP_CCLASS_MIX_NOT: case OP_CCLASS_MIX: xfree(op->cclass_mix.mb); xfree(op->cclass_mix.bsp); break; case OP_BACKREF1: case OP_BACKREF2: case OP_BACKREF_N: case OP_BACKREF_N_IC: break; case OP_BACKREF_MULTI: case OP_BACKREF_MULTI_IC: case OP_BACKREF_WITH_LEVEL: case OP_BACKREF_WITH_LEVEL_IC: case OP_BACKREF_CHECK: case OP_BACKREF_CHECK_WITH_LEVEL: if (op->backref_general.num != 1) xfree(op->backref_general.ns); break; default: break; } } xfree(reg->ops); #ifdef USE_DIRECT_THREADED_CODE xfree(reg->ocs); reg->ocs = 0; #endif reg->ops = 0; reg->ops_curr = 0; reg->ops_alloc = 0; reg->ops_used = 0; } static int ops_calc_size_of_string_pool(regex_t* reg) { int i; int total; if (IS_NULL(reg->ops)) return 0; total = 0; for (i = 0; i < (int )reg->ops_used; i++) { enum OpCode opcode; Operation* op; op = reg->ops + i; #ifdef USE_DIRECT_THREADED_CODE opcode = *(reg->ocs + i); #else opcode = op->opcode; #endif switch (opcode) { case OP_EXACTMBN: total += op->exact_len_n.len * op->exact_len_n.n; break; case OP_EXACTN: case OP_EXACTN_IC: total += op->exact_n.n; break; case OP_EXACTMB2N: total += op->exact_n.n * 2; break; case OP_EXACTMB3N: total += op->exact_n.n * 3; break; default: break; } } return total; } static int ops_make_string_pool(regex_t* reg) { int i; int len; int size; UChar* pool; UChar* curr; size = ops_calc_size_of_string_pool(reg); if (size <= 0) { return 0; } curr = pool = (UChar* )xmalloc((size_t )size); CHECK_NULL_RETURN_MEMERR(pool); for (i = 0; i < (int )reg->ops_used; i++) { enum OpCode opcode; Operation* op; op = reg->ops + i; #ifdef USE_DIRECT_THREADED_CODE opcode = *(reg->ocs + i); #else opcode = op->opcode; #endif switch (opcode) { case OP_EXACTMBN: len = op->exact_len_n.len * op->exact_len_n.n; xmemcpy(curr, op->exact_len_n.s, len); xfree(op->exact_len_n.s); op->exact_len_n.s = curr; curr += len; break; case OP_EXACTN: case OP_EXACTN_IC: len = op->exact_n.n; copy: xmemcpy(curr, op->exact_n.s, len); xfree(op->exact_n.s); op->exact_n.s = curr; curr += len; break; case OP_EXACTMB2N: len = op->exact_n.n * 2; goto copy; break; case OP_EXACTMB3N: len = op->exact_n.n * 3; goto copy; break; default: break; } } reg->string_pool = pool; reg->string_pool_end = pool + size; return 0; } extern OnigCaseFoldType onig_get_default_case_fold_flag(void) { return OnigDefaultCaseFoldFlag; } extern int onig_set_default_case_fold_flag(OnigCaseFoldType case_fold_flag) { OnigDefaultCaseFoldFlag = case_fold_flag; return 0; } static int int_multiply_cmp(int x, int y, int v) { if (x == 0 || y == 0) return -1; if (x < INT_MAX / y) { int xy = x * y; if (xy > v) return 1; else { if (xy == v) return 0; else return -1; } } else return 1; } extern int onig_positive_int_multiply(int x, int y) { if (x == 0 || y == 0) return 0; if (x < INT_MAX / y) return x * y; else return -1; } static void swap_node(Node* a, Node* b) { Node c; c = *a; *a = *b; *b = c; if (NODE_TYPE(a) == NODE_STRING) { StrNode* sn = STR_(a); if (sn->capacity == 0) { int len = (int )(sn->end - sn->s); sn->s = sn->buf; sn->end = sn->s + len; } } if (NODE_TYPE(b) == NODE_STRING) { StrNode* sn = STR_(b); if (sn->capacity == 0) { int len = (int )(sn->end - sn->s); sn->s = sn->buf; sn->end = sn->s + len; } } } static OnigLen distance_add(OnigLen d1, OnigLen d2) { if (d1 == INFINITE_LEN || d2 == INFINITE_LEN) return INFINITE_LEN; else { if (d1 <= INFINITE_LEN - d2) return d1 + d2; else return INFINITE_LEN; } } static OnigLen distance_multiply(OnigLen d, int m) { if (m == 0) return 0; if (d < INFINITE_LEN / m) return d * m; else return INFINITE_LEN; } static int bitset_is_empty(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { if (bs[i] != 0) return 0; } return 1; } #ifdef USE_CALL static int unset_addr_list_init(UnsetAddrList* list, int size) { UnsetAddr* p = (UnsetAddr* )xmalloc(sizeof(UnsetAddr)* size); CHECK_NULL_RETURN_MEMERR(p); list->num = 0; list->alloc = size; list->us = p; return 0; } static void unset_addr_list_end(UnsetAddrList* list) { if (IS_NOT_NULL(list->us)) xfree(list->us); } static int unset_addr_list_add(UnsetAddrList* list, int offset, struct _Node* node) { UnsetAddr* p; int size; if (list->num >= list->alloc) { size = list->alloc * 2; p = (UnsetAddr* )xrealloc(list->us, sizeof(UnsetAddr) * size); CHECK_NULL_RETURN_MEMERR(p); list->alloc = size; list->us = p; } list->us[list->num].offset = offset; list->us[list->num].target = node; list->num++; return 0; } #endif /* USE_CALL */ static int add_op(regex_t* reg, int opcode) { int r; r = ops_new(reg); if (r != ONIG_NORMAL) return r; #ifdef USE_DIRECT_THREADED_CODE *(reg->ocs + (reg->ops_curr - reg->ops)) = opcode; #else reg->ops_curr->opcode = opcode; #endif return 0; } static int compile_length_tree(Node* node, regex_t* reg); static int compile_tree(Node* node, regex_t* reg, ScanEnv* env); #define IS_NEED_STR_LEN_OP_EXACT(op) \ ((op) == OP_EXACTN || (op) == OP_EXACTMB2N ||\ (op) == OP_EXACTMB3N || (op) == OP_EXACTMBN || (op) == OP_EXACTN_IC) static int select_str_opcode(int mb_len, int str_len, int ignore_case) { int op; if (ignore_case) { switch (str_len) { case 1: op = OP_EXACT1_IC; break; default: op = OP_EXACTN_IC; break; } } else { switch (mb_len) { case 1: switch (str_len) { case 1: op = OP_EXACT1; break; case 2: op = OP_EXACT2; break; case 3: op = OP_EXACT3; break; case 4: op = OP_EXACT4; break; case 5: op = OP_EXACT5; break; default: op = OP_EXACTN; break; } break; case 2: switch (str_len) { case 1: op = OP_EXACTMB2N1; break; case 2: op = OP_EXACTMB2N2; break; case 3: op = OP_EXACTMB2N3; break; default: op = OP_EXACTMB2N; break; } break; case 3: op = OP_EXACTMB3N; break; default: op = OP_EXACTMBN; break; } } return op; } static int compile_tree_empty_check(Node* node, regex_t* reg, int empty_info, ScanEnv* env) { int r; int saved_num_null_check = reg->num_null_check; if (empty_info != BODY_IS_NOT_EMPTY) { r = add_op(reg, OP_EMPTY_CHECK_START); if (r != 0) return r; COP(reg)->empty_check_start.mem = reg->num_null_check; /* NULL CHECK ID */ reg->num_null_check++; } r = compile_tree(node, reg, env); if (r != 0) return r; if (empty_info != BODY_IS_NOT_EMPTY) { if (empty_info == BODY_IS_EMPTY) r = add_op(reg, OP_EMPTY_CHECK_END); else if (empty_info == BODY_IS_EMPTY_MEM) r = add_op(reg, OP_EMPTY_CHECK_END_MEMST); else if (empty_info == BODY_IS_EMPTY_REC) r = add_op(reg, OP_EMPTY_CHECK_END_MEMST_PUSH); if (r != 0) return r; COP(reg)->empty_check_end.mem = saved_num_null_check; /* NULL CHECK ID */ } return r; } #ifdef USE_CALL static int compile_call(CallNode* node, regex_t* reg, ScanEnv* env) { int r; int offset; r = add_op(reg, OP_CALL); if (r != 0) return r; COP(reg)->call.addr = 0; /* dummy addr. */ offset = COP_CURR_OFFSET_BYTES(reg, call.addr); r = unset_addr_list_add(env->unset_addr_list, offset, NODE_CALL_BODY(node)); return r; } #endif static int compile_tree_n_times(Node* node, int n, regex_t* reg, ScanEnv* env) { int i, r; for (i = 0; i < n; i++) { r = compile_tree(node, reg, env); if (r != 0) return r; } return 0; } static int add_compile_string_length(UChar* s ARG_UNUSED, int mb_len, int str_len, regex_t* reg ARG_UNUSED, int ignore_case) { return 1; } static int add_compile_string(UChar* s, int mb_len, int str_len, regex_t* reg, int ignore_case) { int op; int r; int byte_len; UChar* p; UChar* end; op = select_str_opcode(mb_len, str_len, ignore_case); r = add_op(reg, op); if (r != 0) return r; byte_len = mb_len * str_len; end = s + byte_len; if (op == OP_EXACTMBN) { p = onigenc_strdup(reg->enc, s, end); CHECK_NULL_RETURN_MEMERR(p); COP(reg)->exact_len_n.len = mb_len; COP(reg)->exact_len_n.n = str_len; COP(reg)->exact_len_n.s = p; } else if (IS_NEED_STR_LEN_OP_EXACT(op)) { p = onigenc_strdup(reg->enc, s, end); CHECK_NULL_RETURN_MEMERR(p); if (op == OP_EXACTN_IC) COP(reg)->exact_n.n = byte_len; else COP(reg)->exact_n.n = str_len; COP(reg)->exact_n.s = p; } else { xmemcpy(COP(reg)->exact.s, s, (size_t )byte_len); COP(reg)->exact.s[byte_len] = '\0'; } return 0; } static int compile_length_string_node(Node* node, regex_t* reg) { int rlen, r, len, prev_len, slen, ambig; UChar *p, *prev; StrNode* sn; OnigEncoding enc = reg->enc; sn = STR_(node); if (sn->end <= sn->s) return 0; ambig = NODE_STRING_IS_AMBIG(node); p = prev = sn->s; prev_len = enclen(enc, p); p += prev_len; slen = 1; rlen = 0; for (; p < sn->end; ) { len = enclen(enc, p); if (len == prev_len) { slen++; } else { r = add_compile_string_length(prev, prev_len, slen, reg, ambig); rlen += r; prev = p; slen = 1; prev_len = len; } p += len; } r = add_compile_string_length(prev, prev_len, slen, reg, ambig); rlen += r; return rlen; } static int compile_length_string_raw_node(StrNode* sn, regex_t* reg) { if (sn->end <= sn->s) return 0; return add_compile_string_length(sn->s, 1 /* sb */, (int )(sn->end - sn->s), reg, 0); } static int compile_string_node(Node* node, regex_t* reg) { int r, len, prev_len, slen, ambig; UChar *p, *prev, *end; StrNode* sn; OnigEncoding enc = reg->enc; sn = STR_(node); if (sn->end <= sn->s) return 0; end = sn->end; ambig = NODE_STRING_IS_AMBIG(node); p = prev = sn->s; prev_len = enclen(enc, p); p += prev_len; slen = 1; for (; p < end; ) { len = enclen(enc, p); if (len == prev_len) { slen++; } else { r = add_compile_string(prev, prev_len, slen, reg, ambig); if (r != 0) return r; prev = p; slen = 1; prev_len = len; } p += len; } return add_compile_string(prev, prev_len, slen, reg, ambig); } static int compile_string_raw_node(StrNode* sn, regex_t* reg) { if (sn->end <= sn->s) return 0; return add_compile_string(sn->s, 1 /* sb */, (int )(sn->end - sn->s), reg, 0); } static void* set_multi_byte_cclass(BBuf* mbuf, regex_t* reg) { size_t len; void* p; len = (size_t )mbuf->used; p = xmalloc(len); if (IS_NULL(p)) return NULL; xmemcpy(p, mbuf->p, len); return p; } static int compile_length_cclass_node(CClassNode* cc, regex_t* reg) { return 1; } static int compile_cclass_node(CClassNode* cc, regex_t* reg) { int r; if (IS_NULL(cc->mbuf)) { r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_NOT : OP_CCLASS); if (r != 0) return r; COP(reg)->cclass.bsp = xmalloc(SIZE_BITSET); CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass.bsp); xmemcpy(COP(reg)->cclass.bsp, cc->bs, SIZE_BITSET); } else { void* p; if (ONIGENC_MBC_MINLEN(reg->enc) > 1 || bitset_is_empty(cc->bs)) { r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MB_NOT : OP_CCLASS_MB); if (r != 0) return r; p = set_multi_byte_cclass(cc->mbuf, reg); CHECK_NULL_RETURN_MEMERR(p); COP(reg)->cclass_mb.mb = p; } else { r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MIX_NOT : OP_CCLASS_MIX); if (r != 0) return r; COP(reg)->cclass_mix.bsp = xmalloc(SIZE_BITSET); CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass_mix.bsp); xmemcpy(COP(reg)->cclass_mix.bsp, cc->bs, SIZE_BITSET); p = set_multi_byte_cclass(cc->mbuf, reg); CHECK_NULL_RETURN_MEMERR(p); COP(reg)->cclass_mix.mb = p; } } return 0; } static int entry_repeat_range(regex_t* reg, int id, int lower, int upper) { #define REPEAT_RANGE_ALLOC 4 OnigRepeatRange* p; if (reg->repeat_range_alloc == 0) { p = (OnigRepeatRange* )xmalloc(sizeof(OnigRepeatRange) * REPEAT_RANGE_ALLOC); CHECK_NULL_RETURN_MEMERR(p); reg->repeat_range = p; reg->repeat_range_alloc = REPEAT_RANGE_ALLOC; } else if (reg->repeat_range_alloc <= id) { int n; n = reg->repeat_range_alloc + REPEAT_RANGE_ALLOC; p = (OnigRepeatRange* )xrealloc(reg->repeat_range, sizeof(OnigRepeatRange) * n); CHECK_NULL_RETURN_MEMERR(p); reg->repeat_range = p; reg->repeat_range_alloc = n; } else { p = reg->repeat_range; } p[id].lower = lower; p[id].upper = (IS_REPEAT_INFINITE(upper) ? 0x7fffffff : upper); return 0; } static int compile_range_repeat_node(QuantNode* qn, int target_len, int empty_info, regex_t* reg, ScanEnv* env) { int r; int num_repeat = reg->num_repeat++; r = add_op(reg, qn->greedy ? OP_REPEAT : OP_REPEAT_NG); if (r != 0) return r; COP(reg)->repeat.id = num_repeat; COP(reg)->repeat.addr = SIZE_INC_OP + target_len + SIZE_OP_REPEAT_INC; r = entry_repeat_range(reg, num_repeat, qn->lower, qn->upper); if (r != 0) return r; r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); if (r != 0) return r; if ( #ifdef USE_CALL NODE_IS_IN_MULTI_ENTRY(qn) || #endif NODE_IS_IN_REAL_REPEAT(qn)) { r = add_op(reg, qn->greedy ? OP_REPEAT_INC_SG : OP_REPEAT_INC_NG_SG); } else { r = add_op(reg, qn->greedy ? OP_REPEAT_INC : OP_REPEAT_INC_NG); } if (r != 0) return r; COP(reg)->repeat_inc.id = num_repeat; return r; } static int is_anychar_infinite_greedy(QuantNode* qn) { if (qn->greedy && IS_REPEAT_INFINITE(qn->upper) && NODE_IS_ANYCHAR(NODE_QUANT_BODY(qn))) return 1; else return 0; } #define QUANTIFIER_EXPAND_LIMIT_SIZE 10 #define CKN_ON (ckn > 0) static int compile_length_quantifier_node(QuantNode* qn, regex_t* reg) { int len, mod_tlen; int infinite = IS_REPEAT_INFINITE(qn->upper); enum BodyEmpty empty_info = qn->empty_info; int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (tlen < 0) return tlen; if (tlen == 0) return 0; /* anychar repeat */ if (is_anychar_infinite_greedy(qn)) { if (qn->lower <= 1 || int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0) { if (IS_NOT_NULL(qn->next_head_exact)) return SIZE_OP_ANYCHAR_STAR_PEEK_NEXT + tlen * qn->lower; else return SIZE_OP_ANYCHAR_STAR + tlen * qn->lower; } } if (empty_info == BODY_IS_NOT_EMPTY) mod_tlen = tlen; else mod_tlen = tlen + (SIZE_OP_EMPTY_CHECK_START + SIZE_OP_EMPTY_CHECK_END); if (infinite && (qn->lower <= 1 || int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) { len = SIZE_OP_JUMP; } else { len = tlen * qn->lower; } if (qn->greedy) { #ifdef USE_OP_PUSH_OR_JUMP_EXACT if (IS_NOT_NULL(qn->head_exact)) len += SIZE_OP_PUSH_OR_JUMP_EXACT1 + mod_tlen + SIZE_OP_JUMP; else #endif if (IS_NOT_NULL(qn->next_head_exact)) len += SIZE_OP_PUSH_IF_PEEK_NEXT + mod_tlen + SIZE_OP_JUMP; else len += SIZE_OP_PUSH + mod_tlen + SIZE_OP_JUMP; } else len += SIZE_OP_JUMP + mod_tlen + SIZE_OP_PUSH; } else if (qn->upper == 0) { if (qn->is_refered != 0) { /* /(?<n>..){0}/ */ len = SIZE_OP_JUMP + tlen; } else len = 0; } else if (!infinite && qn->greedy && (qn->upper == 1 || int_multiply_cmp(tlen + SIZE_OP_PUSH, qn->upper, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { len = tlen * qn->lower; len += (SIZE_OP_PUSH + tlen) * (qn->upper - qn->lower); } else if (!qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */ len = SIZE_OP_PUSH + SIZE_OP_JUMP + tlen; } else { len = SIZE_OP_REPEAT_INC + mod_tlen + SIZE_OP_REPEAT; } return len; } static int compile_quantifier_node(QuantNode* qn, regex_t* reg, ScanEnv* env) { int i, r, mod_tlen; int infinite = IS_REPEAT_INFINITE(qn->upper); enum BodyEmpty empty_info = qn->empty_info; int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (tlen < 0) return tlen; if (tlen == 0) return 0; if (is_anychar_infinite_greedy(qn) && (qn->lower <= 1 || int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; if (IS_NOT_NULL(qn->next_head_exact)) { r = add_op(reg, IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ? OP_ANYCHAR_ML_STAR_PEEK_NEXT : OP_ANYCHAR_STAR_PEEK_NEXT); if (r != 0) return r; COP(reg)->anychar_star_peek_next.c = STR_(qn->next_head_exact)->s[0]; return 0; } else { r = add_op(reg, IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ? OP_ANYCHAR_ML_STAR : OP_ANYCHAR_STAR); return r; } } if (empty_info == BODY_IS_NOT_EMPTY) mod_tlen = tlen; else mod_tlen = tlen + (SIZE_OP_EMPTY_CHECK_START + SIZE_OP_EMPTY_CHECK_END); if (infinite && (qn->lower <= 1 || int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { int addr; if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) { r = add_op(reg, OP_JUMP); if (r != 0) return r; if (qn->greedy) { #ifdef USE_OP_PUSH_OR_JUMP_EXACT if (IS_NOT_NULL(qn->head_exact)) COP(reg)->jump.addr = SIZE_OP_PUSH_OR_JUMP_EXACT1 + SIZE_INC_OP; else #endif if (IS_NOT_NULL(qn->next_head_exact)) COP(reg)->jump.addr = SIZE_OP_PUSH_IF_PEEK_NEXT + SIZE_INC_OP; else COP(reg)->jump.addr = SIZE_OP_PUSH + SIZE_INC_OP; } else { COP(reg)->jump.addr = SIZE_OP_JUMP + SIZE_INC_OP; } } else { r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; } if (qn->greedy) { #ifdef USE_OP_PUSH_OR_JUMP_EXACT if (IS_NOT_NULL(qn->head_exact)) { r = add_op(reg, OP_PUSH_OR_JUMP_EXACT1); if (r != 0) return r; COP(reg)->push_or_jump_exact1.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; COP(reg)->push_or_jump_exact1.c = STR_(qn->head_exact)->s[0]; r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); if (r != 0) return r; addr = -(mod_tlen + (int )SIZE_OP_PUSH_OR_JUMP_EXACT1); } else #endif if (IS_NOT_NULL(qn->next_head_exact)) { r = add_op(reg, OP_PUSH_IF_PEEK_NEXT); if (r != 0) return r; COP(reg)->push_if_peek_next.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; COP(reg)->push_if_peek_next.c = STR_(qn->next_head_exact)->s[0]; r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); if (r != 0) return r; addr = -(mod_tlen + (int )SIZE_OP_PUSH_IF_PEEK_NEXT); } else { r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); if (r != 0) return r; addr = -(mod_tlen + (int )SIZE_OP_PUSH); } r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = addr; } else { r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = mod_tlen + SIZE_INC_OP; r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); if (r != 0) return r; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = -mod_tlen; } } else if (qn->upper == 0) { if (qn->is_refered != 0) { /* /(?<n>..){0}/ */ r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = tlen + SIZE_INC_OP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); } else { /* Nothing output */ r = 0; } } else if (! infinite && qn->greedy && (qn->upper == 1 || int_multiply_cmp(tlen + SIZE_OP_PUSH, qn->upper, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { int n = qn->upper - qn->lower; r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; for (i = 0; i < n; i++) { int v = onig_positive_int_multiply(n - i, tlen + SIZE_OP_PUSH); if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = v; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; } } else if (! qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */ r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + SIZE_OP_JUMP; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = tlen + SIZE_INC_OP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); } else { r = compile_range_repeat_node(qn, mod_tlen, empty_info, reg, env); } return r; } static int compile_length_option_node(BagNode* node, regex_t* reg) { int tlen; OnigOptionType prev = reg->options; reg->options = node->o.options; tlen = compile_length_tree(NODE_BAG_BODY(node), reg); reg->options = prev; return tlen; } static int compile_option_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r; OnigOptionType prev = reg->options; reg->options = node->o.options; r = compile_tree(NODE_BAG_BODY(node), reg, env); reg->options = prev; return r; } static int compile_length_bag_node(BagNode* node, regex_t* reg) { int len; int tlen; if (node->type == BAG_OPTION) return compile_length_option_node(node, reg); if (NODE_BAG_BODY(node)) { tlen = compile_length_tree(NODE_BAG_BODY(node), reg); if (tlen < 0) return tlen; } else tlen = 0; switch (node->type) { case BAG_MEMORY: #ifdef USE_CALL if (node->m.regnum == 0 && NODE_IS_CALLED(node)) { len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; return len; } if (NODE_IS_CALLED(node)) { len = SIZE_OP_MEMORY_START_PUSH + tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); else len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); } else if (NODE_IS_RECURSION(node)) { len = SIZE_OP_MEMORY_START_PUSH; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC); } else #endif { if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) len = SIZE_OP_MEMORY_START_PUSH; else len = SIZE_OP_MEMORY_START; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END); } break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { int v; QuantNode* qn; qn = QUANT_(NODE_BAG_BODY(node)); tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (tlen < 0) return tlen; v = onig_positive_int_multiply(qn->lower, tlen); if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP; } else { len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END; } break; case BAG_IF_ELSE: { Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; len = compile_length_tree(cond, reg); if (len < 0) return len; len += SIZE_OP_PUSH; len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Then)) { tlen = compile_length_tree(Then, reg); if (tlen < 0) return tlen; len += tlen; } if (IS_NOT_NULL(Else)) { len += SIZE_OP_JUMP; tlen = compile_length_tree(Else, reg); if (tlen < 0) return tlen; len += tlen; } } break; case BAG_OPTION: /* never come here, but set for escape warning */ len = 0; break; } return len; } static int get_char_len_node(Node* node, regex_t* reg, int* len); static int compile_bag_memory_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r; int len; #ifdef USE_CALL if (NODE_IS_CALLED(node)) { r = add_op(reg, OP_CALL); if (r != 0) return r; node->m.called_addr = COP_CURR_OFFSET(reg) + 1 + SIZE_OP_JUMP; NODE_STATUS_ADD(node, ADDR_FIXED); COP(reg)->call.addr = (int )node->m.called_addr; if (node->m.regnum == 0) { len = compile_length_tree(NODE_BAG_BODY(node), reg); len += SIZE_OP_RETURN; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = len + SIZE_INC_OP; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_RETURN); return r; } else { len = compile_length_tree(NODE_BAG_BODY(node), reg); len += (SIZE_OP_MEMORY_START_PUSH + SIZE_OP_RETURN); if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); else len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = len + SIZE_INC_OP; } } #endif if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) r = add_op(reg, OP_MEMORY_START_PUSH); else r = add_op(reg, OP_MEMORY_START); if (r != 0) return r; COP(reg)->memory_start.num = node->m.regnum; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; #ifdef USE_CALL if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) r = add_op(reg, (NODE_IS_RECURSION(node) ? OP_MEMORY_END_PUSH_REC : OP_MEMORY_END_PUSH)); else r = add_op(reg, (NODE_IS_RECURSION(node) ? OP_MEMORY_END_REC : OP_MEMORY_END)); if (r != 0) return r; COP(reg)->memory_end.num = node->m.regnum; if (NODE_IS_CALLED(node)) { if (r != 0) return r; r = add_op(reg, OP_RETURN); } #else if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) r = add_op(reg, OP_MEMORY_END_PUSH); else r = add_op(reg, OP_MEMORY_END); if (r != 0) return r; COP(reg)->memory_end.num = node->m.regnum; #endif return r; } static int compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r, len; switch (node->type) { case BAG_MEMORY: r = compile_bag_memory_node(node, reg, env); break; case BAG_OPTION: r = compile_option_node(node, reg, env); break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; len = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (len < 0) return len; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; r = add_op(reg, OP_POP_OUT); if (r != 0) return r; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); } else { r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); } break; case BAG_IF_ELSE: { int cond_len, then_len, jump_len; Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; cond_len = compile_length_tree(cond, reg); if (cond_len < 0) return cond_len; if (IS_NOT_NULL(Then)) { then_len = compile_length_tree(Then, reg); if (then_len < 0) return then_len; } else then_len = 0; jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + jump_len; r = compile_tree(cond, reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Then)) { r = compile_tree(Then, reg, env); if (r != 0) return r; } if (IS_NOT_NULL(Else)) { int else_len = compile_length_tree(Else, reg); r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = else_len + SIZE_INC_OP; r = compile_tree(Else, reg, env); } } break; } return r; } static int compile_length_anchor_node(AnchorNode* node, regex_t* reg) { int len; int tlen = 0; if (IS_NOT_NULL(NODE_ANCHOR_BODY(node))) { tlen = compile_length_tree(NODE_ANCHOR_BODY(node), reg); if (tlen < 0) return tlen; } switch (node->type) { case ANCR_PREC_READ: len = SIZE_OP_PREC_READ_START + tlen + SIZE_OP_PREC_READ_END; break; case ANCR_PREC_READ_NOT: len = SIZE_OP_PREC_READ_NOT_START + tlen + SIZE_OP_PREC_READ_NOT_END; break; case ANCR_LOOK_BEHIND: len = SIZE_OP_LOOK_BEHIND + tlen; break; case ANCR_LOOK_BEHIND_NOT: len = SIZE_OP_LOOK_BEHIND_NOT_START + tlen + SIZE_OP_LOOK_BEHIND_NOT_END; break; case ANCR_WORD_BOUNDARY: case ANCR_NO_WORD_BOUNDARY: #ifdef USE_WORD_BEGIN_END case ANCR_WORD_BEGIN: case ANCR_WORD_END: #endif len = SIZE_OP_WORD_BOUNDARY; break; case ANCR_TEXT_SEGMENT_BOUNDARY: case ANCR_NO_TEXT_SEGMENT_BOUNDARY: len = SIZE_OPCODE; break; default: len = SIZE_OPCODE; break; } return len; } static int compile_anchor_node(AnchorNode* node, regex_t* reg, ScanEnv* env) { int r, len; enum OpCode op; switch (node->type) { case ANCR_BEGIN_BUF: r = add_op(reg, OP_BEGIN_BUF); break; case ANCR_END_BUF: r = add_op(reg, OP_END_BUF); break; case ANCR_BEGIN_LINE: r = add_op(reg, OP_BEGIN_LINE); break; case ANCR_END_LINE: r = add_op(reg, OP_END_LINE); break; case ANCR_SEMI_END_BUF: r = add_op(reg, OP_SEMI_END_BUF); break; case ANCR_BEGIN_POSITION: r = add_op(reg, OP_BEGIN_POSITION); break; case ANCR_WORD_BOUNDARY: op = OP_WORD_BOUNDARY; word: r = add_op(reg, op); if (r != 0) return r; COP(reg)->word_boundary.mode = (ModeType )node->ascii_mode; break; case ANCR_NO_WORD_BOUNDARY: op = OP_NO_WORD_BOUNDARY; goto word; break; #ifdef USE_WORD_BEGIN_END case ANCR_WORD_BEGIN: op = OP_WORD_BEGIN; goto word; break; case ANCR_WORD_END: op = OP_WORD_END; goto word; break; #endif case ANCR_TEXT_SEGMENT_BOUNDARY: case ANCR_NO_TEXT_SEGMENT_BOUNDARY: { enum TextSegmentBoundaryType type; r = add_op(reg, OP_TEXT_SEGMENT_BOUNDARY); if (r != 0) return r; type = EXTENDED_GRAPHEME_CLUSTER_BOUNDARY; #ifdef USE_UNICODE_WORD_BREAK if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_TEXT_SEGMENT_WORD)) type = WORD_BOUNDARY; #endif COP(reg)->text_segment_boundary.type = type; COP(reg)->text_segment_boundary.not = (node->type == ANCR_NO_TEXT_SEGMENT_BOUNDARY ? 1 : 0); } break; case ANCR_PREC_READ: r = add_op(reg, OP_PREC_READ_START); if (r != 0) return r; r = compile_tree(NODE_ANCHOR_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_PREC_READ_END); break; case ANCR_PREC_READ_NOT: len = compile_length_tree(NODE_ANCHOR_BODY(node), reg); if (len < 0) return len; r = add_op(reg, OP_PREC_READ_NOT_START); if (r != 0) return r; COP(reg)->prec_read_not_start.addr = SIZE_INC_OP + len + SIZE_OP_PREC_READ_NOT_END; r = compile_tree(NODE_ANCHOR_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_PREC_READ_NOT_END); break; case ANCR_LOOK_BEHIND: { int n; r = add_op(reg, OP_LOOK_BEHIND); if (r != 0) return r; if (node->char_len < 0) { r = get_char_len_node(NODE_ANCHOR_BODY(node), reg, &n); if (r != 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN; } else n = node->char_len; COP(reg)->look_behind.len = n; r = compile_tree(NODE_ANCHOR_BODY(node), reg, env); } break; case ANCR_LOOK_BEHIND_NOT: { int n; len = compile_length_tree(NODE_ANCHOR_BODY(node), reg); r = add_op(reg, OP_LOOK_BEHIND_NOT_START); if (r != 0) return r; COP(reg)->look_behind_not_start.addr = SIZE_INC_OP + len + SIZE_OP_LOOK_BEHIND_NOT_END; if (node->char_len < 0) { r = get_char_len_node(NODE_ANCHOR_BODY(node), reg, &n); if (r != 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN; } else n = node->char_len; COP(reg)->look_behind_not_start.len = n; r = compile_tree(NODE_ANCHOR_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_LOOK_BEHIND_NOT_END); } break; default: return ONIGERR_TYPE_BUG; break; } return r; } static int compile_gimmick_node(GimmickNode* node, regex_t* reg) { int r; switch (node->type) { case GIMMICK_FAIL: r = add_op(reg, OP_FAIL); break; case GIMMICK_SAVE: r = add_op(reg, OP_PUSH_SAVE_VAL); if (r != 0) return r; COP(reg)->push_save_val.type = node->detail_type; COP(reg)->push_save_val.id = node->id; break; case GIMMICK_UPDATE_VAR: r = add_op(reg, OP_UPDATE_VAR); if (r != 0) return r; COP(reg)->update_var.type = node->detail_type; COP(reg)->update_var.id = node->id; break; #ifdef USE_CALLOUT case GIMMICK_CALLOUT: switch (node->detail_type) { case ONIG_CALLOUT_OF_CONTENTS: case ONIG_CALLOUT_OF_NAME: { if (node->detail_type == ONIG_CALLOUT_OF_NAME) { r = add_op(reg, OP_CALLOUT_NAME); if (r != 0) return r; COP(reg)->callout_name.id = node->id; COP(reg)->callout_name.num = node->num; } else { r = add_op(reg, OP_CALLOUT_CONTENTS); if (r != 0) return r; COP(reg)->callout_contents.num = node->num; } } break; default: r = ONIGERR_TYPE_BUG; break; } #endif } return r; } static int compile_length_gimmick_node(GimmickNode* node, regex_t* reg) { int len; switch (node->type) { case GIMMICK_FAIL: len = SIZE_OP_FAIL; break; case GIMMICK_SAVE: len = SIZE_OP_PUSH_SAVE_VAL; break; case GIMMICK_UPDATE_VAR: len = SIZE_OP_UPDATE_VAR; break; #ifdef USE_CALLOUT case GIMMICK_CALLOUT: switch (node->detail_type) { case ONIG_CALLOUT_OF_CONTENTS: len = SIZE_OP_CALLOUT_CONTENTS; break; case ONIG_CALLOUT_OF_NAME: len = SIZE_OP_CALLOUT_NAME; break; default: len = ONIGERR_TYPE_BUG; break; } break; #endif } return len; } static int compile_length_tree(Node* node, regex_t* reg) { int len, r; switch (NODE_TYPE(node)) { case NODE_LIST: len = 0; do { r = compile_length_tree(NODE_CAR(node), reg); if (r < 0) return r; len += r; } while (IS_NOT_NULL(node = NODE_CDR(node))); r = len; break; case NODE_ALT: { int n; n = r = 0; do { r += compile_length_tree(NODE_CAR(node), reg); n++; } while (IS_NOT_NULL(node = NODE_CDR(node))); r += (SIZE_OP_PUSH + SIZE_OP_JUMP) * (n - 1); } break; case NODE_STRING: if (NODE_STRING_IS_RAW(node)) r = compile_length_string_raw_node(STR_(node), reg); else r = compile_length_string_node(node, reg); break; case NODE_CCLASS: r = compile_length_cclass_node(CCLASS_(node), reg); break; case NODE_CTYPE: r = SIZE_OPCODE; break; case NODE_BACKREF: r = SIZE_OP_BACKREF; break; #ifdef USE_CALL case NODE_CALL: r = SIZE_OP_CALL; break; #endif case NODE_QUANT: r = compile_length_quantifier_node(QUANT_(node), reg); break; case NODE_BAG: r = compile_length_bag_node(BAG_(node), reg); break; case NODE_ANCHOR: r = compile_length_anchor_node(ANCHOR_(node), reg); break; case NODE_GIMMICK: r = compile_length_gimmick_node(GIMMICK_(node), reg); break; default: return ONIGERR_TYPE_BUG; break; } return r; } static int compile_tree(Node* node, regex_t* reg, ScanEnv* env) { int n, len, pos, r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: do { r = compile_tree(NODE_CAR(node), reg, env); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ALT: { Node* x = node; len = 0; do { len += compile_length_tree(NODE_CAR(x), reg); if (IS_NOT_NULL(NODE_CDR(x))) { len += SIZE_OP_PUSH + SIZE_OP_JUMP; } } while (IS_NOT_NULL(x = NODE_CDR(x))); pos = COP_CURR_OFFSET(reg) + 1 + len; /* goal position */ do { len = compile_length_tree(NODE_CAR(node), reg); if (IS_NOT_NULL(NODE_CDR(node))) { enum OpCode push = NODE_IS_SUPER(node) ? OP_PUSH_SUPER : OP_PUSH; r = add_op(reg, push); if (r != 0) break; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_JUMP; } r = compile_tree(NODE_CAR(node), reg, env); if (r != 0) break; if (IS_NOT_NULL(NODE_CDR(node))) { len = pos - (COP_CURR_OFFSET(reg) + 1); r = add_op(reg, OP_JUMP); if (r != 0) break; COP(reg)->jump.addr = len; } } while (IS_NOT_NULL(node = NODE_CDR(node))); } break; case NODE_STRING: if (NODE_STRING_IS_RAW(node)) r = compile_string_raw_node(STR_(node), reg); else r = compile_string_node(node, reg); break; case NODE_CCLASS: r = compile_cclass_node(CCLASS_(node), reg); break; case NODE_CTYPE: { int op; switch (CTYPE_(node)->ctype) { case CTYPE_ANYCHAR: r = add_op(reg, IS_MULTILINE(CTYPE_OPTION(node, reg)) ? OP_ANYCHAR_ML : OP_ANYCHAR); break; case ONIGENC_CTYPE_WORD: if (CTYPE_(node)->ascii_mode == 0) { op = CTYPE_(node)->not != 0 ? OP_NO_WORD : OP_WORD; } else { op = CTYPE_(node)->not != 0 ? OP_NO_WORD_ASCII : OP_WORD_ASCII; } r = add_op(reg, op); break; default: return ONIGERR_TYPE_BUG; break; } } break; case NODE_BACKREF: { BackRefNode* br = BACKREF_(node); if (NODE_IS_CHECKER(node)) { #ifdef USE_BACKREF_WITH_LEVEL if (NODE_IS_NEST_LEVEL(node)) { r = add_op(reg, OP_BACKREF_CHECK_WITH_LEVEL); if (r != 0) return r; COP(reg)->backref_general.nest_level = br->nest_level; } else #endif { r = add_op(reg, OP_BACKREF_CHECK); if (r != 0) return r; } goto add_bacref_mems; } else { #ifdef USE_BACKREF_WITH_LEVEL if (NODE_IS_NEST_LEVEL(node)) { if ((reg->options & ONIG_OPTION_IGNORECASE) != 0) r = add_op(reg, OP_BACKREF_WITH_LEVEL_IC); else r = add_op(reg, OP_BACKREF_WITH_LEVEL); if (r != 0) return r; COP(reg)->backref_general.nest_level = br->nest_level; goto add_bacref_mems; } else #endif if (br->back_num == 1) { n = br->back_static[0]; if (IS_IGNORECASE(reg->options)) { r = add_op(reg, OP_BACKREF_N_IC); if (r != 0) return r; COP(reg)->backref_n.n1 = n; } else { switch (n) { case 1: r = add_op(reg, OP_BACKREF1); break; case 2: r = add_op(reg, OP_BACKREF2); break; default: r = add_op(reg, OP_BACKREF_N); if (r != 0) return r; COP(reg)->backref_n.n1 = n; break; } } } else { int num; int* p; r = add_op(reg, IS_IGNORECASE(reg->options) ? OP_BACKREF_MULTI_IC : OP_BACKREF_MULTI); if (r != 0) return r; add_bacref_mems: num = br->back_num; COP(reg)->backref_general.num = num; if (num == 1) { COP(reg)->backref_general.n1 = br->back_static[0]; } else { int i, j; MemNumType* ns; ns = xmalloc(sizeof(MemNumType) * num); CHECK_NULL_RETURN_MEMERR(ns); COP(reg)->backref_general.ns = ns; p = BACKREFS_P(br); for (i = num - 1, j = 0; i >= 0; i--, j++) { ns[j] = p[i]; } } } } } break; #ifdef USE_CALL case NODE_CALL: r = compile_call(CALL_(node), reg, env); break; #endif case NODE_QUANT: r = compile_quantifier_node(QUANT_(node), reg, env); break; case NODE_BAG: r = compile_bag_node(BAG_(node), reg, env); break; case NODE_ANCHOR: r = compile_anchor_node(ANCHOR_(node), reg, env); break; case NODE_GIMMICK: r = compile_gimmick_node(GIMMICK_(node), reg); break; default: #ifdef ONIG_DEBUG fprintf(stderr, "compile_tree: undefined node type %d\n", NODE_TYPE(node)); #endif break; } return r; } static int noname_disable_map(Node** plink, GroupNumRemap* map, int* counter) { int r = 0; Node* node = *plink; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = noname_disable_map(&(NODE_CAR(node)), map, counter); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: { Node** ptarget = &(NODE_BODY(node)); Node* old = *ptarget; r = noname_disable_map(ptarget, map, counter); if (*ptarget != old && NODE_TYPE(*ptarget) == NODE_QUANT) { onig_reduce_nested_quantifier(node, *ptarget); } } break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_NAMED_GROUP(node)) { (*counter)++; map[en->m.regnum].new_val = *counter; en->m.regnum = *counter; r = noname_disable_map(&(NODE_BODY(node)), map, counter); } else { *plink = NODE_BODY(node); NODE_BODY(node) = NULL_NODE; onig_node_free(node); r = noname_disable_map(plink, map, counter); } } else if (en->type == BAG_IF_ELSE) { r = noname_disable_map(&(NODE_BAG_BODY(en)), map, counter); if (r != 0) return r; if (IS_NOT_NULL(en->te.Then)) { r = noname_disable_map(&(en->te.Then), map, counter); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) { r = noname_disable_map(&(en->te.Else), map, counter); if (r != 0) return r; } } else r = noname_disable_map(&(NODE_BODY(node)), map, counter); } break; case NODE_ANCHOR: if (IS_NOT_NULL(NODE_BODY(node))) r = noname_disable_map(&(NODE_BODY(node)), map, counter); break; default: break; } return r; } static int renumber_node_backref(Node* node, GroupNumRemap* map) { int i, pos, n, old_num; int *backs; BackRefNode* bn = BACKREF_(node); if (! NODE_IS_BY_NAME(node)) return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED; old_num = bn->back_num; if (IS_NULL(bn->back_dynamic)) backs = bn->back_static; else backs = bn->back_dynamic; for (i = 0, pos = 0; i < old_num; i++) { n = map[backs[i]].new_val; if (n > 0) { backs[pos] = n; pos++; } } bn->back_num = pos; return 0; } static int renumber_by_map(Node* node, GroupNumRemap* map) { int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = renumber_by_map(NODE_CAR(node), map); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: r = renumber_by_map(NODE_BODY(node), map); break; case NODE_BAG: { BagNode* en = BAG_(node); r = renumber_by_map(NODE_BODY(node), map); if (r != 0) return r; if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { r = renumber_by_map(en->te.Then, map); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) { r = renumber_by_map(en->te.Else, map); if (r != 0) return r; } } } break; case NODE_BACKREF: r = renumber_node_backref(node, map); break; case NODE_ANCHOR: if (IS_NOT_NULL(NODE_BODY(node))) r = renumber_by_map(NODE_BODY(node), map); break; default: break; } return r; } static int numbered_ref_check(Node* node) { int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = numbered_ref_check(NODE_CAR(node)); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ANCHOR: if (IS_NULL(NODE_BODY(node))) break; /* fall */ case NODE_QUANT: r = numbered_ref_check(NODE_BODY(node)); break; case NODE_BAG: { BagNode* en = BAG_(node); r = numbered_ref_check(NODE_BODY(node)); if (r != 0) return r; if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { r = numbered_ref_check(en->te.Then); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) { r = numbered_ref_check(en->te.Else); if (r != 0) return r; } } } break; case NODE_BACKREF: if (! NODE_IS_BY_NAME(node)) return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED; break; default: break; } return r; } static int disable_noname_group_capture(Node** root, regex_t* reg, ScanEnv* env) { int r, i, pos, counter; MemStatusType loc; GroupNumRemap* map; map = (GroupNumRemap* )xalloca(sizeof(GroupNumRemap) * (env->num_mem + 1)); CHECK_NULL_RETURN_MEMERR(map); for (i = 1; i <= env->num_mem; i++) { map[i].new_val = 0; } counter = 0; r = noname_disable_map(root, map, &counter); if (r != 0) return r; r = renumber_by_map(*root, map); if (r != 0) return r; for (i = 1, pos = 1; i <= env->num_mem; i++) { if (map[i].new_val > 0) { SCANENV_MEMENV(env)[pos] = SCANENV_MEMENV(env)[i]; pos++; } } loc = env->capture_history; MEM_STATUS_CLEAR(env->capture_history); for (i = 1; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) { if (MEM_STATUS_AT(loc, i)) { MEM_STATUS_ON_SIMPLE(env->capture_history, map[i].new_val); } } env->num_mem = env->num_named; reg->num_mem = env->num_named; return onig_renumber_name_table(reg, map); } #ifdef USE_CALL static int fix_unset_addr_list(UnsetAddrList* uslist, regex_t* reg) { int i, offset; BagNode* en; AbsAddrType addr; AbsAddrType* paddr; for (i = 0; i < uslist->num; i++) { if (! NODE_IS_ADDR_FIXED(uslist->us[i].target)) return ONIGERR_PARSER_BUG; en = BAG_(uslist->us[i].target); addr = en->m.called_addr; offset = uslist->us[i].offset; paddr = (AbsAddrType* )((char* )reg->ops + offset); *paddr = addr; } return 0; } #endif #define GET_CHAR_LEN_VARLEN -1 #define GET_CHAR_LEN_TOP_ALT_VARLEN -2 /* fixed size pattern node only */ static int get_char_len_node1(Node* node, regex_t* reg, int* len, int level) { int tlen; int r = 0; level++; *len = 0; switch (NODE_TYPE(node)) { case NODE_LIST: do { r = get_char_len_node1(NODE_CAR(node), reg, &tlen, level); if (r == 0) *len = distance_add(*len, tlen); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ALT: { int tlen2; int varlen = 0; r = get_char_len_node1(NODE_CAR(node), reg, &tlen, level); while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))) { r = get_char_len_node1(NODE_CAR(node), reg, &tlen2, level); if (r == 0) { if (tlen != tlen2) varlen = 1; } } if (r == 0) { if (varlen != 0) { if (level == 1) r = GET_CHAR_LEN_TOP_ALT_VARLEN; else r = GET_CHAR_LEN_VARLEN; } else *len = tlen; } } break; case NODE_STRING: { StrNode* sn = STR_(node); UChar *s = sn->s; while (s < sn->end) { s += enclen(reg->enc, s); (*len)++; } } break; case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->lower == qn->upper) { if (qn->upper == 0) { *len = 0; } else { r = get_char_len_node1(NODE_BODY(node), reg, &tlen, level); if (r == 0) *len = distance_multiply(tlen, qn->lower); } } else r = GET_CHAR_LEN_VARLEN; } break; #ifdef USE_CALL case NODE_CALL: if (! NODE_IS_RECURSION(node)) r = get_char_len_node1(NODE_BODY(node), reg, len, level); else r = GET_CHAR_LEN_VARLEN; break; #endif case NODE_CTYPE: case NODE_CCLASS: *len = 1; break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: #ifdef USE_CALL if (NODE_IS_CLEN_FIXED(node)) *len = en->char_len; else { r = get_char_len_node1(NODE_BODY(node), reg, len, level); if (r == 0) { en->char_len = *len; NODE_STATUS_ADD(node, CLEN_FIXED); } } break; #endif case BAG_OPTION: case BAG_STOP_BACKTRACK: r = get_char_len_node1(NODE_BODY(node), reg, len, level); break; case BAG_IF_ELSE: { int clen, elen; r = get_char_len_node1(NODE_BODY(node), reg, &clen, level); if (r == 0) { if (IS_NOT_NULL(en->te.Then)) { r = get_char_len_node1(en->te.Then, reg, &tlen, level); if (r != 0) break; } else tlen = 0; if (IS_NOT_NULL(en->te.Else)) { r = get_char_len_node1(en->te.Else, reg, &elen, level); if (r != 0) break; } else elen = 0; if (clen + tlen != elen) { r = GET_CHAR_LEN_VARLEN; } else { *len = elen; } } } break; } } break; case NODE_ANCHOR: case NODE_GIMMICK: break; case NODE_BACKREF: if (NODE_IS_CHECKER(node)) break; /* fall */ default: r = GET_CHAR_LEN_VARLEN; break; } return r; } static int get_char_len_node(Node* node, regex_t* reg, int* len) { return get_char_len_node1(node, reg, len, 0); } /* x is not included y ==> 1 : 0 */ static int is_exclusive(Node* x, Node* y, regex_t* reg) { int i, len; OnigCodePoint code; UChar *p; NodeType ytype; retry: ytype = NODE_TYPE(y); switch (NODE_TYPE(x)) { case NODE_CTYPE: { if (CTYPE_(x)->ctype == CTYPE_ANYCHAR || CTYPE_(y)->ctype == CTYPE_ANYCHAR) break; switch (ytype) { case NODE_CTYPE: if (CTYPE_(y)->ctype == CTYPE_(x)->ctype && CTYPE_(y)->not != CTYPE_(x)->not && CTYPE_(y)->ascii_mode == CTYPE_(x)->ascii_mode) return 1; else return 0; break; case NODE_CCLASS: swap: { Node* tmp; tmp = x; x = y; y = tmp; goto retry; } break; case NODE_STRING: goto swap; break; default: break; } } break; case NODE_CCLASS: { int range; CClassNode* xc = CCLASS_(x); switch (ytype) { case NODE_CTYPE: switch (CTYPE_(y)->ctype) { case CTYPE_ANYCHAR: return 0; break; case ONIGENC_CTYPE_WORD: if (CTYPE_(y)->not == 0) { if (IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) { range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE; for (i = 0; i < range; i++) { if (BITSET_AT(xc->bs, i)) { if (ONIGENC_IS_CODE_WORD(reg->enc, i)) return 0; } } return 1; } return 0; } else { if (IS_NOT_NULL(xc->mbuf)) return 0; if (IS_NCCLASS_NOT(xc)) return 0; range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE; for (i = 0; i < range; i++) { if (! ONIGENC_IS_CODE_WORD(reg->enc, i)) { if (BITSET_AT(xc->bs, i)) return 0; } } for (i = range; i < SINGLE_BYTE_SIZE; i++) { if (BITSET_AT(xc->bs, i)) return 0; } return 1; } break; default: break; } break; case NODE_CCLASS: { int v; CClassNode* yc = CCLASS_(y); for (i = 0; i < SINGLE_BYTE_SIZE; i++) { v = BITSET_AT(xc->bs, i); if ((v != 0 && !IS_NCCLASS_NOT(xc)) || (v == 0 && IS_NCCLASS_NOT(xc))) { v = BITSET_AT(yc->bs, i); if ((v != 0 && !IS_NCCLASS_NOT(yc)) || (v == 0 && IS_NCCLASS_NOT(yc))) return 0; } } if ((IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) || (IS_NULL(yc->mbuf) && !IS_NCCLASS_NOT(yc))) return 1; return 0; } break; case NODE_STRING: goto swap; break; default: break; } } break; case NODE_STRING: { StrNode* xs = STR_(x); if (NODE_STRING_LEN(x) == 0) break; switch (ytype) { case NODE_CTYPE: switch (CTYPE_(y)->ctype) { case CTYPE_ANYCHAR: break; case ONIGENC_CTYPE_WORD: if (CTYPE_(y)->ascii_mode == 0) { if (ONIGENC_IS_MBC_WORD(reg->enc, xs->s, xs->end)) return CTYPE_(y)->not; else return !(CTYPE_(y)->not); } else { if (ONIGENC_IS_MBC_WORD_ASCII(reg->enc, xs->s, xs->end)) return CTYPE_(y)->not; else return !(CTYPE_(y)->not); } break; default: break; } break; case NODE_CCLASS: { CClassNode* cc = CCLASS_(y); code = ONIGENC_MBC_TO_CODE(reg->enc, xs->s, xs->s + ONIGENC_MBC_MAXLEN(reg->enc)); return onig_is_code_in_cc(reg->enc, code, cc) == 0; } break; case NODE_STRING: { UChar *q; StrNode* ys = STR_(y); len = NODE_STRING_LEN(x); if (len > NODE_STRING_LEN(y)) len = NODE_STRING_LEN(y); if (NODE_STRING_IS_AMBIG(x) || NODE_STRING_IS_AMBIG(y)) { /* tiny version */ return 0; } else { for (i = 0, p = ys->s, q = xs->s; i < len; i++, p++, q++) { if (*p != *q) return 1; } } } break; default: break; } } break; default: break; } return 0; } static Node* get_head_value_node(Node* node, int exact, regex_t* reg) { Node* n = NULL_NODE; switch (NODE_TYPE(node)) { case NODE_BACKREF: case NODE_ALT: #ifdef USE_CALL case NODE_CALL: #endif break; case NODE_CTYPE: if (CTYPE_(node)->ctype == CTYPE_ANYCHAR) break; /* fall */ case NODE_CCLASS: if (exact == 0) { n = node; } break; case NODE_LIST: n = get_head_value_node(NODE_CAR(node), exact, reg); break; case NODE_STRING: { StrNode* sn = STR_(node); if (sn->end <= sn->s) break; if (exact == 0 || ! IS_IGNORECASE(reg->options) || NODE_STRING_IS_RAW(node)) { n = node; } } break; case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->lower > 0) { if (IS_NOT_NULL(qn->head_exact)) n = qn->head_exact; else n = get_head_value_node(NODE_BODY(node), exact, reg); } } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_OPTION: { OnigOptionType options = reg->options; reg->options = BAG_(node)->o.options; n = get_head_value_node(NODE_BODY(node), exact, reg); reg->options = options; } break; case BAG_MEMORY: case BAG_STOP_BACKTRACK: case BAG_IF_ELSE: n = get_head_value_node(NODE_BODY(node), exact, reg); break; } } break; case NODE_ANCHOR: if (ANCHOR_(node)->type == ANCR_PREC_READ) n = get_head_value_node(NODE_BODY(node), exact, reg); break; case NODE_GIMMICK: default: break; } return n; } static int check_type_tree(Node* node, int type_mask, int bag_mask, int anchor_mask) { NodeType type; int r = 0; type = NODE_TYPE(node); if ((NODE_TYPE2BIT(type) & type_mask) == 0) return 1; switch (type) { case NODE_LIST: case NODE_ALT: do { r = check_type_tree(NODE_CAR(node), type_mask, bag_mask, anchor_mask); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: r = check_type_tree(NODE_BODY(node), type_mask, bag_mask, anchor_mask); break; case NODE_BAG: { BagNode* en = BAG_(node); if (((1<<en->type) & bag_mask) == 0) return 1; r = check_type_tree(NODE_BODY(node), type_mask, bag_mask, anchor_mask); if (r == 0 && en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { r = check_type_tree(en->te.Then, type_mask, bag_mask, anchor_mask); if (r != 0) break; } if (IS_NOT_NULL(en->te.Else)) { r = check_type_tree(en->te.Else, type_mask, bag_mask, anchor_mask); } } } break; case NODE_ANCHOR: type = ANCHOR_(node)->type; if ((type & anchor_mask) == 0) return 1; if (IS_NOT_NULL(NODE_BODY(node))) r = check_type_tree(NODE_BODY(node), type_mask, bag_mask, anchor_mask); break; case NODE_GIMMICK: default: break; } return r; } static OnigLen tree_min_len(Node* node, ScanEnv* env) { OnigLen len; OnigLen tmin; len = 0; switch (NODE_TYPE(node)) { case NODE_BACKREF: if (! NODE_IS_CHECKER(node)) { int i; int* backs; MemEnv* mem_env = SCANENV_MEMENV(env); BackRefNode* br = BACKREF_(node); if (NODE_IS_RECURSION(node)) break; backs = BACKREFS_P(br); len = tree_min_len(mem_env[backs[0]].node, env); for (i = 1; i < br->back_num; i++) { tmin = tree_min_len(mem_env[backs[i]].node, env); if (len > tmin) len = tmin; } } break; #ifdef USE_CALL case NODE_CALL: { Node* t = NODE_BODY(node); if (NODE_IS_RECURSION(node)) { if (NODE_IS_MIN_FIXED(t)) len = BAG_(t)->min_len; } else len = tree_min_len(t, env); } break; #endif case NODE_LIST: do { tmin = tree_min_len(NODE_CAR(node), env); len = distance_add(len, tmin); } while (IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ALT: { Node *x, *y; y = node; do { x = NODE_CAR(y); tmin = tree_min_len(x, env); if (y == node) len = tmin; else if (len > tmin) len = tmin; } while (IS_NOT_NULL(y = NODE_CDR(y))); } break; case NODE_STRING: { StrNode* sn = STR_(node); len = (int )(sn->end - sn->s); } break; case NODE_CTYPE: case NODE_CCLASS: len = ONIGENC_MBC_MINLEN(env->enc); break; case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->lower > 0) { len = tree_min_len(NODE_BODY(node), env); len = distance_multiply(len, qn->lower); } } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: if (NODE_IS_MIN_FIXED(node)) len = en->min_len; else { if (NODE_IS_MARK1(node)) len = 0; /* recursive */ else { NODE_STATUS_ADD(node, MARK1); len = tree_min_len(NODE_BODY(node), env); NODE_STATUS_REMOVE(node, MARK1); en->min_len = len; NODE_STATUS_ADD(node, MIN_FIXED); } } break; case BAG_OPTION: case BAG_STOP_BACKTRACK: len = tree_min_len(NODE_BODY(node), env); break; case BAG_IF_ELSE: { OnigLen elen; len = tree_min_len(NODE_BODY(node), env); if (IS_NOT_NULL(en->te.Then)) len += tree_min_len(en->te.Then, env); if (IS_NOT_NULL(en->te.Else)) elen = tree_min_len(en->te.Else, env); else elen = 0; if (elen < len) len = elen; } break; } } break; case NODE_GIMMICK: { GimmickNode* g = GIMMICK_(node); if (g->type == GIMMICK_FAIL) { len = INFINITE_LEN; break; } } /* fall */ case NODE_ANCHOR: default: break; } return len; } static OnigLen tree_max_len(Node* node, ScanEnv* env) { OnigLen len; OnigLen tmax; len = 0; switch (NODE_TYPE(node)) { case NODE_LIST: do { tmax = tree_max_len(NODE_CAR(node), env); len = distance_add(len, tmax); } while (IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ALT: do { tmax = tree_max_len(NODE_CAR(node), env); if (len < tmax) len = tmax; } while (IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_STRING: { StrNode* sn = STR_(node); len = (OnigLen )(sn->end - sn->s); } break; case NODE_CTYPE: case NODE_CCLASS: len = ONIGENC_MBC_MAXLEN_DIST(env->enc); break; case NODE_BACKREF: if (! NODE_IS_CHECKER(node)) { int i; int* backs; MemEnv* mem_env = SCANENV_MEMENV(env); BackRefNode* br = BACKREF_(node); if (NODE_IS_RECURSION(node)) { len = INFINITE_LEN; break; } backs = BACKREFS_P(br); for (i = 0; i < br->back_num; i++) { tmax = tree_max_len(mem_env[backs[i]].node, env); if (len < tmax) len = tmax; } } break; #ifdef USE_CALL case NODE_CALL: if (! NODE_IS_RECURSION(node)) len = tree_max_len(NODE_BODY(node), env); else len = INFINITE_LEN; break; #endif case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->upper != 0) { len = tree_max_len(NODE_BODY(node), env); if (len != 0) { if (! IS_REPEAT_INFINITE(qn->upper)) len = distance_multiply(len, qn->upper); else len = INFINITE_LEN; } } } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: if (NODE_IS_MAX_FIXED(node)) len = en->max_len; else { if (NODE_IS_MARK1(node)) len = INFINITE_LEN; else { NODE_STATUS_ADD(node, MARK1); len = tree_max_len(NODE_BODY(node), env); NODE_STATUS_REMOVE(node, MARK1); en->max_len = len; NODE_STATUS_ADD(node, MAX_FIXED); } } break; case BAG_OPTION: case BAG_STOP_BACKTRACK: len = tree_max_len(NODE_BODY(node), env); break; case BAG_IF_ELSE: { OnigLen tlen, elen; len = tree_max_len(NODE_BODY(node), env); if (IS_NOT_NULL(en->te.Then)) { tlen = tree_max_len(en->te.Then, env); len = distance_add(len, tlen); } if (IS_NOT_NULL(en->te.Else)) elen = tree_max_len(en->te.Else, env); else elen = 0; if (elen > len) len = elen; } break; } } break; case NODE_ANCHOR: case NODE_GIMMICK: default: break; } return len; } static int check_backrefs(Node* node, ScanEnv* env) { int r; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = check_backrefs(NODE_CAR(node), env); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ANCHOR: if (! ANCHOR_HAS_BODY(ANCHOR_(node))) { r = 0; break; } /* fall */ case NODE_QUANT: r = check_backrefs(NODE_BODY(node), env); break; case NODE_BAG: r = check_backrefs(NODE_BODY(node), env); { BagNode* en = BAG_(node); if (en->type == BAG_IF_ELSE) { if (r != 0) return r; if (IS_NOT_NULL(en->te.Then)) { r = check_backrefs(en->te.Then, env); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) { r = check_backrefs(en->te.Else, env); } } } break; case NODE_BACKREF: { int i; BackRefNode* br = BACKREF_(node); int* backs = BACKREFS_P(br); MemEnv* mem_env = SCANENV_MEMENV(env); for (i = 0; i < br->back_num; i++) { if (backs[i] > env->num_mem) return ONIGERR_INVALID_BACKREF; NODE_STATUS_ADD(mem_env[backs[i]].node, BACKREF); } r = 0; } break; default: r = 0; break; } return r; } #ifdef USE_CALL #define RECURSION_EXIST (1<<0) #define RECURSION_MUST (1<<1) #define RECURSION_INFINITE (1<<2) static int infinite_recursive_call_check(Node* node, ScanEnv* env, int head) { int ret; int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: { Node *x; OnigLen min; x = node; do { ret = infinite_recursive_call_check(NODE_CAR(x), env, head); if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret; r |= ret; if (head != 0) { min = tree_min_len(NODE_CAR(x), env); if (min != 0) head = 0; } } while (IS_NOT_NULL(x = NODE_CDR(x))); } break; case NODE_ALT: { int must; must = RECURSION_MUST; do { ret = infinite_recursive_call_check(NODE_CAR(node), env, head); if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret; r |= (ret & RECURSION_EXIST); must &= ret; } while (IS_NOT_NULL(node = NODE_CDR(node))); r |= must; } break; case NODE_QUANT: r = infinite_recursive_call_check(NODE_BODY(node), env, head); if (r < 0) return r; if ((r & RECURSION_MUST) != 0) { if (QUANT_(node)->lower == 0) r &= ~RECURSION_MUST; } break; case NODE_ANCHOR: if (! ANCHOR_HAS_BODY(ANCHOR_(node))) break; /* fall */ case NODE_CALL: r = infinite_recursive_call_check(NODE_BODY(node), env, head); break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_MARK2(node)) return 0; else if (NODE_IS_MARK1(node)) return (head == 0 ? RECURSION_EXIST | RECURSION_MUST : RECURSION_EXIST | RECURSION_MUST | RECURSION_INFINITE); else { NODE_STATUS_ADD(node, MARK2); r = infinite_recursive_call_check(NODE_BODY(node), env, head); NODE_STATUS_REMOVE(node, MARK2); } } else if (en->type == BAG_IF_ELSE) { int eret; ret = infinite_recursive_call_check(NODE_BODY(node), env, head); if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret; r |= ret; if (IS_NOT_NULL(en->te.Then)) { OnigLen min; if (head != 0) { min = tree_min_len(NODE_BODY(node), env); } else min = 0; ret = infinite_recursive_call_check(en->te.Then, env, min != 0 ? 0:head); if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret; r |= ret; } if (IS_NOT_NULL(en->te.Else)) { eret = infinite_recursive_call_check(en->te.Else, env, head); if (eret < 0 || (eret & RECURSION_INFINITE) != 0) return eret; r |= (eret & RECURSION_EXIST); if ((eret & RECURSION_MUST) == 0) r &= ~RECURSION_MUST; } } else { r = infinite_recursive_call_check(NODE_BODY(node), env, head); } } break; default: break; } return r; } static int infinite_recursive_call_check_trav(Node* node, ScanEnv* env) { int r; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = infinite_recursive_call_check_trav(NODE_CAR(node), env); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ANCHOR: if (! ANCHOR_HAS_BODY(ANCHOR_(node))) { r = 0; break; } /* fall */ case NODE_QUANT: r = infinite_recursive_call_check_trav(NODE_BODY(node), env); break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_RECURSION(node) && NODE_IS_CALLED(node)) { int ret; NODE_STATUS_ADD(node, MARK1); ret = infinite_recursive_call_check(NODE_BODY(node), env, 1); if (ret < 0) return ret; else if ((ret & (RECURSION_MUST | RECURSION_INFINITE)) != 0) return ONIGERR_NEVER_ENDING_RECURSION; NODE_STATUS_REMOVE(node, MARK1); } } else if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { r = infinite_recursive_call_check_trav(en->te.Then, env); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) { r = infinite_recursive_call_check_trav(en->te.Else, env); if (r != 0) return r; } } } r = infinite_recursive_call_check_trav(NODE_BODY(node), env); break; default: r = 0; break; } return r; } static int recursive_call_check(Node* node) { int r; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: r = 0; do { r |= recursive_call_check(NODE_CAR(node)); } while (IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ANCHOR: if (! ANCHOR_HAS_BODY(ANCHOR_(node))) { r = 0; break; } /* fall */ case NODE_QUANT: r = recursive_call_check(NODE_BODY(node)); break; case NODE_CALL: r = recursive_call_check(NODE_BODY(node)); if (r != 0) { if (NODE_IS_MARK1(NODE_BODY(node))) NODE_STATUS_ADD(node, RECURSION); } break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_MARK2(node)) return 0; else if (NODE_IS_MARK1(node)) return 1; /* recursion */ else { NODE_STATUS_ADD(node, MARK2); r = recursive_call_check(NODE_BODY(node)); NODE_STATUS_REMOVE(node, MARK2); } } else if (en->type == BAG_IF_ELSE) { r = 0; if (IS_NOT_NULL(en->te.Then)) { r |= recursive_call_check(en->te.Then); } if (IS_NOT_NULL(en->te.Else)) { r |= recursive_call_check(en->te.Else); } r |= recursive_call_check(NODE_BODY(node)); } else { r = recursive_call_check(NODE_BODY(node)); } } break; default: r = 0; break; } return r; } #define IN_RECURSION (1<<0) #define FOUND_CALLED_NODE 1 static int recursive_call_check_trav(Node* node, ScanEnv* env, int state) { int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: { int ret; do { ret = recursive_call_check_trav(NODE_CAR(node), env, state); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; else if (ret < 0) return ret; } while (IS_NOT_NULL(node = NODE_CDR(node))); } break; case NODE_QUANT: r = recursive_call_check_trav(NODE_BODY(node), env, state); if (QUANT_(node)->upper == 0) { if (r == FOUND_CALLED_NODE) QUANT_(node)->is_refered = 1; } break; case NODE_ANCHOR: { AnchorNode* an = ANCHOR_(node); if (ANCHOR_HAS_BODY(an)) r = recursive_call_check_trav(NODE_ANCHOR_BODY(an), env, state); } break; case NODE_BAG: { int ret; int state1; BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_CALLED(node) || (state & IN_RECURSION) != 0) { if (! NODE_IS_RECURSION(node)) { NODE_STATUS_ADD(node, MARK1); r = recursive_call_check(NODE_BODY(node)); if (r != 0) NODE_STATUS_ADD(node, RECURSION); NODE_STATUS_REMOVE(node, MARK1); } if (NODE_IS_CALLED(node)) r = FOUND_CALLED_NODE; } } state1 = state; if (NODE_IS_RECURSION(node)) state1 |= IN_RECURSION; ret = recursive_call_check_trav(NODE_BODY(node), env, state1); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { ret = recursive_call_check_trav(en->te.Then, env, state1); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; } if (IS_NOT_NULL(en->te.Else)) { ret = recursive_call_check_trav(en->te.Else, env, state1); if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE; } } } break; default: break; } return r; } #endif #define IN_ALT (1<<0) #define IN_NOT (1<<1) #define IN_REAL_REPEAT (1<<2) #define IN_VAR_REPEAT (1<<3) #define IN_ZERO_REPEAT (1<<4) #define IN_MULTI_ENTRY (1<<5) #define IN_LOOK_BEHIND (1<<6) /* divide different length alternatives in look-behind. (?<=A|B) ==> (?<=A)|(?<=B) (?<!A|B) ==> (?<!A)(?<!B) */ static int divide_look_behind_alternatives(Node* node) { Node *head, *np, *insert_node; AnchorNode* an = ANCHOR_(node); int anc_type = an->type; head = NODE_ANCHOR_BODY(an); np = NODE_CAR(head); swap_node(node, head); NODE_CAR(node) = head; NODE_BODY(head) = np; np = node; while (IS_NOT_NULL(np = NODE_CDR(np))) { insert_node = onig_node_new_anchor(anc_type, an->ascii_mode); CHECK_NULL_RETURN_MEMERR(insert_node); NODE_BODY(insert_node) = NODE_CAR(np); NODE_CAR(np) = insert_node; } if (anc_type == ANCR_LOOK_BEHIND_NOT) { np = node; do { NODE_SET_TYPE(np, NODE_LIST); /* alt -> list */ } while (IS_NOT_NULL(np = NODE_CDR(np))); } return 0; } static int setup_look_behind(Node* node, regex_t* reg, ScanEnv* env) { int r, len; AnchorNode* an = ANCHOR_(node); r = get_char_len_node(NODE_ANCHOR_BODY(an), reg, &len); if (r == 0) an->char_len = len; else if (r == GET_CHAR_LEN_VARLEN) r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN; else if (r == GET_CHAR_LEN_TOP_ALT_VARLEN) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND)) r = divide_look_behind_alternatives(node); else r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN; } return r; } static int next_setup(Node* node, Node* next_node, regex_t* reg) { NodeType type; retry: type = NODE_TYPE(node); if (type == NODE_QUANT) { QuantNode* qn = QUANT_(node); if (qn->greedy && IS_REPEAT_INFINITE(qn->upper)) { #ifdef USE_QUANT_PEEK_NEXT Node* n = get_head_value_node(next_node, 1, reg); /* '\0': for UTF-16BE etc... */ if (IS_NOT_NULL(n) && STR_(n)->s[0] != '\0') { qn->next_head_exact = n; } #endif /* automatic posseivation a*b ==> (?>a*)b */ if (qn->lower <= 1) { if (NODE_IS_SIMPLE_TYPE(NODE_BODY(node))) { Node *x, *y; x = get_head_value_node(NODE_BODY(node), 0, reg); if (IS_NOT_NULL(x)) { y = get_head_value_node(next_node, 0, reg); if (IS_NOT_NULL(y) && is_exclusive(x, y, reg)) { Node* en = onig_node_new_bag(BAG_STOP_BACKTRACK); CHECK_NULL_RETURN_MEMERR(en); NODE_STATUS_ADD(en, STOP_BT_SIMPLE_REPEAT); swap_node(node, en); NODE_BODY(node) = en; } } } } } } else if (type == NODE_BAG) { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { node = NODE_BODY(node); goto retry; } } return 0; } static int update_string_node_case_fold(regex_t* reg, Node *node) { UChar *p, *end, buf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; UChar *sbuf, *ebuf, *sp; int r, i, len, sbuf_size; StrNode* sn = STR_(node); end = sn->end; sbuf_size = (int )(end - sn->s) * 2; sbuf = (UChar* )xmalloc(sbuf_size); CHECK_NULL_RETURN_MEMERR(sbuf); ebuf = sbuf + sbuf_size; sp = sbuf; p = sn->s; while (p < end) { len = ONIGENC_MBC_CASE_FOLD(reg->enc, reg->case_fold_flag, &p, end, buf); for (i = 0; i < len; i++) { if (sp >= ebuf) { sbuf = (UChar* )xrealloc(sbuf, sbuf_size * 2); CHECK_NULL_RETURN_MEMERR(sbuf); sp = sbuf + sbuf_size; sbuf_size *= 2; ebuf = sbuf + sbuf_size; } *sp++ = buf[i]; } } r = onig_node_str_set(node, sbuf, sp); if (r != 0) { xfree(sbuf); return r; } xfree(sbuf); return 0; } static int expand_case_fold_make_rem_string(Node** rnode, UChar *s, UChar *end, regex_t* reg) { int r; Node *node; node = onig_node_new_str(s, end); if (IS_NULL(node)) return ONIGERR_MEMORY; r = update_string_node_case_fold(reg, node); if (r != 0) { onig_node_free(node); return r; } NODE_STRING_SET_AMBIG(node); NODE_STRING_SET_DONT_GET_OPT_INFO(node); *rnode = node; return 0; } static int expand_case_fold_string_alt(int item_num, OnigCaseFoldCodeItem items[], UChar *p, int slen, UChar *end, regex_t* reg, Node **rnode) { int r, i, j; int len; int varlen; Node *anode, *var_anode, *snode, *xnode, *an; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; *rnode = var_anode = NULL_NODE; varlen = 0; for (i = 0; i < item_num; i++) { if (items[i].byte_len != slen) { varlen = 1; break; } } if (varlen != 0) { *rnode = var_anode = onig_node_new_alt(NULL_NODE, NULL_NODE); if (IS_NULL(var_anode)) return ONIGERR_MEMORY; xnode = onig_node_new_list(NULL, NULL); if (IS_NULL(xnode)) goto mem_err; NODE_CAR(var_anode) = xnode; anode = onig_node_new_alt(NULL_NODE, NULL_NODE); if (IS_NULL(anode)) goto mem_err; NODE_CAR(xnode) = anode; } else { *rnode = anode = onig_node_new_alt(NULL_NODE, NULL_NODE); if (IS_NULL(anode)) return ONIGERR_MEMORY; } snode = onig_node_new_str(p, p + slen); if (IS_NULL(snode)) goto mem_err; NODE_CAR(anode) = snode; for (i = 0; i < item_num; i++) { snode = onig_node_new_str(NULL, NULL); if (IS_NULL(snode)) goto mem_err; for (j = 0; j < items[i].code_len; j++) { len = ONIGENC_CODE_TO_MBC(reg->enc, items[i].code[j], buf); if (len < 0) { r = len; goto mem_err2; } r = onig_node_str_cat(snode, buf, buf + len); if (r != 0) goto mem_err2; } an = onig_node_new_alt(NULL_NODE, NULL_NODE); if (IS_NULL(an)) { goto mem_err2; } if (items[i].byte_len != slen && IS_NOT_NULL(var_anode)) { Node *rem; UChar *q = p + items[i].byte_len; if (q < end) { r = expand_case_fold_make_rem_string(&rem, q, end, reg); if (r != 0) { onig_node_free(an); goto mem_err2; } xnode = onig_node_list_add(NULL_NODE, snode); if (IS_NULL(xnode)) { onig_node_free(an); onig_node_free(rem); goto mem_err2; } if (IS_NULL(onig_node_list_add(xnode, rem))) { onig_node_free(an); onig_node_free(xnode); onig_node_free(rem); goto mem_err; } NODE_CAR(an) = xnode; } else { NODE_CAR(an) = snode; } NODE_CDR(var_anode) = an; var_anode = an; } else { NODE_CAR(an) = snode; NODE_CDR(anode) = an; anode = an; } } return varlen; mem_err2: onig_node_free(snode); mem_err: onig_node_free(*rnode); return ONIGERR_MEMORY; } static int is_good_case_fold_items_for_search(OnigEncoding enc, int slen, int n, OnigCaseFoldCodeItem items[]) { int i, len; UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; for (i = 0; i < n; i++) { OnigCaseFoldCodeItem* item = items + i; if (item->code_len != 1) return 0; if (item->byte_len != slen) return 0; len = ONIGENC_CODE_TO_MBC(enc, item->code[0], buf); if (len != slen) return 0; } return 1; } #define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION 8 static int expand_case_fold_string(Node* node, regex_t* reg, int state) { int r, n, len, alt_num; int fold_len; int prev_is_ambig, prev_is_good, is_good, is_in_look_behind; UChar *start, *end, *p; UChar* foldp; Node *top_root, *root, *snode, *prev_node; OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; StrNode* sn; if (NODE_STRING_IS_AMBIG(node)) return 0; sn = STR_(node); start = sn->s; end = sn->end; if (start >= end) return 0; is_in_look_behind = (state & IN_LOOK_BEHIND) != 0; r = 0; top_root = root = prev_node = snode = NULL_NODE; alt_num = 1; p = start; while (p < end) { n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag, p, end, items); if (n < 0) { r = n; goto err; } len = enclen(reg->enc, p); is_good = is_good_case_fold_items_for_search(reg->enc, len, n, items); if (is_in_look_behind || (IS_NOT_NULL(snode) || (is_good /* expand single char case: ex. /(?i:a)/ */ && !(p == start && p + len >= end)))) { if (IS_NULL(snode)) { if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } prev_node = snode = onig_node_new_str(NULL, NULL); if (IS_NULL(snode)) goto mem_err; if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, snode))) { onig_node_free(snode); goto mem_err; } } prev_is_ambig = -1; /* -1: new */ prev_is_good = 0; /* escape compiler warning */ } else { prev_is_ambig = NODE_STRING_IS_AMBIG(snode); prev_is_good = NODE_STRING_IS_GOOD_AMBIG(snode); } if (n != 0) { foldp = p; fold_len = ONIGENC_MBC_CASE_FOLD(reg->enc, reg->case_fold_flag, &foldp, end, buf); foldp = buf; } else { foldp = p; fold_len = len; } if ((prev_is_ambig == 0 && n != 0) || (prev_is_ambig > 0 && (n == 0 || prev_is_good != is_good))) { if (IS_NULL(root) /* && IS_NOT_NULL(prev_node) */) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } prev_node = snode = onig_node_new_str(foldp, foldp + fold_len); if (IS_NULL(snode)) goto mem_err; if (IS_NULL(onig_node_list_add(root, snode))) { onig_node_free(snode); goto mem_err; } } else { r = onig_node_str_cat(snode, foldp, foldp + fold_len); if (r != 0) goto err; } if (n != 0) NODE_STRING_SET_AMBIG(snode); if (is_good != 0) NODE_STRING_SET_GOOD_AMBIG(snode); } else { alt_num *= (n + 1); if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break; if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node); if (r < 0) goto mem_err; if (r == 1) { if (IS_NULL(root)) { top_root = prev_node; } else { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } root = NODE_CAR(prev_node); } else { /* r == 0 */ if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } } snode = NULL_NODE; } p += len; } if (p < end) { Node *srem; r = expand_case_fold_make_rem_string(&srem, p, end, reg); if (r != 0) goto mem_err; if (IS_NOT_NULL(prev_node) && IS_NULL(root)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(srem); onig_node_free(prev_node); goto mem_err; } } if (IS_NULL(root)) { prev_node = srem; } else { if (IS_NULL(onig_node_list_add(root, srem))) { onig_node_free(srem); goto mem_err; } } } /* ending */ top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node); swap_node(node, top_root); onig_node_free(top_root); return 0; mem_err: r = ONIGERR_MEMORY; err: onig_node_free(top_root); return r; } #ifdef USE_INSISTENT_CHECK_CAPTURES_IN_EMPTY_REPEAT static enum BodyEmpty quantifiers_memory_node_info(Node* node) { int r = BODY_IS_EMPTY; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: { int v; do { v = quantifiers_memory_node_info(NODE_CAR(node)); if (v > r) r = v; } while (IS_NOT_NULL(node = NODE_CDR(node))); } break; #ifdef USE_CALL case NODE_CALL: if (NODE_IS_RECURSION(node)) { return BODY_IS_EMPTY_REC; /* tiny version */ } else r = quantifiers_memory_node_info(NODE_BODY(node)); break; #endif case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->upper != 0) { r = quantifiers_memory_node_info(NODE_BODY(node)); } } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: if (NODE_IS_RECURSION(node)) { return BODY_IS_EMPTY_REC; } return BODY_IS_EMPTY_MEM; break; case BAG_OPTION: case BAG_STOP_BACKTRACK: r = quantifiers_memory_node_info(NODE_BODY(node)); break; case BAG_IF_ELSE: { int v; r = quantifiers_memory_node_info(NODE_BODY(node)); if (IS_NOT_NULL(en->te.Then)) { v = quantifiers_memory_node_info(en->te.Then); if (v > r) r = v; } if (IS_NOT_NULL(en->te.Else)) { v = quantifiers_memory_node_info(en->te.Else); if (v > r) r = v; } } break; } } break; case NODE_BACKREF: case NODE_STRING: case NODE_CTYPE: case NODE_CCLASS: case NODE_ANCHOR: case NODE_GIMMICK: default: break; } return r; } #endif /* USE_INSISTENT_CHECK_CAPTURES_IN_EMPTY_REPEAT */ #ifdef USE_CALL #ifdef __GNUC__ __inline #endif static int setup_call_node_call(CallNode* cn, ScanEnv* env, int state) { MemEnv* mem_env = SCANENV_MEMENV(env); if (cn->by_number != 0) { int gnum = cn->group_num; if (env->num_named > 0 && IS_SYNTAX_BV(env->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && ! ONIG_IS_OPTION_ON(env->options, ONIG_OPTION_CAPTURE_GROUP)) { return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED; } if (gnum > env->num_mem) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_GROUP_REFERENCE, cn->name, cn->name_end); return ONIGERR_UNDEFINED_GROUP_REFERENCE; } set_call_attr: NODE_CALL_BODY(cn) = mem_env[cn->group_num].node; if (IS_NULL(NODE_CALL_BODY(cn))) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, cn->name, cn->name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } } else { int *refs; int n = onig_name_to_group_numbers(env->reg, cn->name, cn->name_end, &refs); if (n <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, cn->name, cn->name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } else if (n > 1) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL, cn->name, cn->name_end); return ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL; } else { cn->group_num = refs[0]; goto set_call_attr; } } return 0; } static void setup_call2_call(Node* node) { switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { setup_call2_call(NODE_CAR(node)); } while (IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: setup_call2_call(NODE_BODY(node)); break; case NODE_ANCHOR: if (ANCHOR_HAS_BODY(ANCHOR_(node))) setup_call2_call(NODE_BODY(node)); break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (! NODE_IS_MARK1(node)) { NODE_STATUS_ADD(node, MARK1); setup_call2_call(NODE_BODY(node)); NODE_STATUS_REMOVE(node, MARK1); } } else if (en->type == BAG_IF_ELSE) { setup_call2_call(NODE_BODY(node)); if (IS_NOT_NULL(en->te.Then)) setup_call2_call(en->te.Then); if (IS_NOT_NULL(en->te.Else)) setup_call2_call(en->te.Else); } else { setup_call2_call(NODE_BODY(node)); } } break; case NODE_CALL: if (! NODE_IS_MARK1(node)) { NODE_STATUS_ADD(node, MARK1); { CallNode* cn = CALL_(node); Node* called = NODE_CALL_BODY(cn); cn->entry_count++; NODE_STATUS_ADD(called, CALLED); BAG_(called)->m.entry_count++; setup_call2_call(called); } NODE_STATUS_REMOVE(node, MARK1); } break; default: break; } } static int setup_call(Node* node, ScanEnv* env, int state) { int r; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = setup_call(NODE_CAR(node), env, state); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: if (QUANT_(node)->upper == 0) state |= IN_ZERO_REPEAT; r = setup_call(NODE_BODY(node), env, state); break; case NODE_ANCHOR: if (ANCHOR_HAS_BODY(ANCHOR_(node))) r = setup_call(NODE_BODY(node), env, state); else r = 0; break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if ((state & IN_ZERO_REPEAT) != 0) { NODE_STATUS_ADD(node, IN_ZERO_REPEAT); BAG_(node)->m.entry_count--; } r = setup_call(NODE_BODY(node), env, state); } else if (en->type == BAG_IF_ELSE) { r = setup_call(NODE_BODY(node), env, state); if (r != 0) return r; if (IS_NOT_NULL(en->te.Then)) { r = setup_call(en->te.Then, env, state); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) r = setup_call(en->te.Else, env, state); } else r = setup_call(NODE_BODY(node), env, state); } break; case NODE_CALL: if ((state & IN_ZERO_REPEAT) != 0) { NODE_STATUS_ADD(node, IN_ZERO_REPEAT); CALL_(node)->entry_count--; } r = setup_call_node_call(CALL_(node), env, state); break; default: r = 0; break; } return r; } static int setup_call2(Node* node) { int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = setup_call2(NODE_CAR(node)); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: if (QUANT_(node)->upper != 0) r = setup_call2(NODE_BODY(node)); break; case NODE_ANCHOR: if (ANCHOR_HAS_BODY(ANCHOR_(node))) r = setup_call2(NODE_BODY(node)); break; case NODE_BAG: if (! NODE_IS_IN_ZERO_REPEAT(node)) r = setup_call2(NODE_BODY(node)); { BagNode* en = BAG_(node); if (r != 0) return r; if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { r = setup_call2(en->te.Then); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) r = setup_call2(en->te.Else); } } break; case NODE_CALL: if (! NODE_IS_IN_ZERO_REPEAT(node)) { setup_call2_call(node); } break; default: break; } return r; } static void setup_called_state_call(Node* node, int state) { switch (NODE_TYPE(node)) { case NODE_ALT: state |= IN_ALT; /* fall */ case NODE_LIST: do { setup_called_state_call(NODE_CAR(node), state); } while (IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 2) state |= IN_REAL_REPEAT; if (qn->lower != qn->upper) state |= IN_VAR_REPEAT; setup_called_state_call(NODE_QUANT_BODY(qn), state); } break; case NODE_ANCHOR: { AnchorNode* an = ANCHOR_(node); switch (an->type) { case ANCR_PREC_READ_NOT: case ANCR_LOOK_BEHIND_NOT: state |= IN_NOT; /* fall */ case ANCR_PREC_READ: case ANCR_LOOK_BEHIND: setup_called_state_call(NODE_ANCHOR_BODY(an), state); break; default: break; } } break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_MARK1(node)) { if ((~en->m.called_state & state) != 0) { en->m.called_state |= state; setup_called_state_call(NODE_BODY(node), state); } } else { NODE_STATUS_ADD(node, MARK1); en->m.called_state |= state; setup_called_state_call(NODE_BODY(node), state); NODE_STATUS_REMOVE(node, MARK1); } } else if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { setup_called_state_call(en->te.Then, state); } if (IS_NOT_NULL(en->te.Else)) setup_called_state_call(en->te.Else, state); } else { setup_called_state_call(NODE_BODY(node), state); } } break; case NODE_CALL: setup_called_state_call(NODE_BODY(node), state); break; default: break; } } static void setup_called_state(Node* node, int state) { switch (NODE_TYPE(node)) { case NODE_ALT: state |= IN_ALT; /* fall */ case NODE_LIST: do { setup_called_state(NODE_CAR(node), state); } while (IS_NOT_NULL(node = NODE_CDR(node))); break; #ifdef USE_CALL case NODE_CALL: setup_called_state_call(node, state); break; #endif case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: if (en->m.entry_count > 1) state |= IN_MULTI_ENTRY; en->m.called_state |= state; /* fall */ case BAG_OPTION: case BAG_STOP_BACKTRACK: setup_called_state(NODE_BODY(node), state); break; case BAG_IF_ELSE: setup_called_state(NODE_BODY(node), state); if (IS_NOT_NULL(en->te.Then)) setup_called_state(en->te.Then, state); if (IS_NOT_NULL(en->te.Else)) setup_called_state(en->te.Else, state); break; } } break; case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 2) state |= IN_REAL_REPEAT; if (qn->lower != qn->upper) state |= IN_VAR_REPEAT; setup_called_state(NODE_QUANT_BODY(qn), state); } break; case NODE_ANCHOR: { AnchorNode* an = ANCHOR_(node); switch (an->type) { case ANCR_PREC_READ_NOT: case ANCR_LOOK_BEHIND_NOT: state |= IN_NOT; /* fall */ case ANCR_PREC_READ: case ANCR_LOOK_BEHIND: setup_called_state(NODE_ANCHOR_BODY(an), state); break; default: break; } } break; case NODE_BACKREF: case NODE_STRING: case NODE_CTYPE: case NODE_CCLASS: case NODE_GIMMICK: default: break; } } #endif /* USE_CALL */ static int setup_tree(Node* node, regex_t* reg, int state, ScanEnv* env); #ifdef __GNUC__ __inline #endif static int setup_anchor(Node* node, regex_t* reg, int state, ScanEnv* env) { /* allowed node types in look-behind */ #define ALLOWED_TYPE_IN_LB \ ( NODE_BIT_LIST | NODE_BIT_ALT | NODE_BIT_STRING | NODE_BIT_CCLASS \ | NODE_BIT_CTYPE | NODE_BIT_ANCHOR | NODE_BIT_BAG | NODE_BIT_QUANT \ | NODE_BIT_CALL | NODE_BIT_GIMMICK) #define ALLOWED_BAG_IN_LB ( 1<<BAG_MEMORY | 1<<BAG_OPTION | 1<<BAG_IF_ELSE ) #define ALLOWED_BAG_IN_LB_NOT ( 1<<BAG_OPTION | 1<<BAG_IF_ELSE ) #define ALLOWED_ANCHOR_IN_LB \ ( ANCR_LOOK_BEHIND | ANCR_BEGIN_LINE | ANCR_END_LINE | ANCR_BEGIN_BUF \ | ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY | ANCR_NO_WORD_BOUNDARY \ | ANCR_WORD_BEGIN | ANCR_WORD_END \ | ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY ) #define ALLOWED_ANCHOR_IN_LB_NOT \ ( ANCR_LOOK_BEHIND | ANCR_LOOK_BEHIND_NOT | ANCR_BEGIN_LINE \ | ANCR_END_LINE | ANCR_BEGIN_BUF | ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY \ | ANCR_NO_WORD_BOUNDARY | ANCR_WORD_BEGIN | ANCR_WORD_END \ | ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY ) int r; AnchorNode* an = ANCHOR_(node); switch (an->type) { case ANCR_PREC_READ: r = setup_tree(NODE_ANCHOR_BODY(an), reg, state, env); break; case ANCR_PREC_READ_NOT: r = setup_tree(NODE_ANCHOR_BODY(an), reg, (state | IN_NOT), env); break; case ANCR_LOOK_BEHIND: { r = check_type_tree(NODE_ANCHOR_BODY(an), ALLOWED_TYPE_IN_LB, ALLOWED_BAG_IN_LB, ALLOWED_ANCHOR_IN_LB); if (r < 0) return r; if (r > 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN; r = setup_tree(NODE_ANCHOR_BODY(an), reg, (state|IN_LOOK_BEHIND), env); if (r != 0) return r; r = setup_look_behind(node, reg, env); } break; case ANCR_LOOK_BEHIND_NOT: { r = check_type_tree(NODE_ANCHOR_BODY(an), ALLOWED_TYPE_IN_LB, ALLOWED_BAG_IN_LB_NOT, ALLOWED_ANCHOR_IN_LB_NOT); if (r < 0) return r; if (r > 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN; r = setup_tree(NODE_ANCHOR_BODY(an), reg, (state|IN_NOT|IN_LOOK_BEHIND), env); if (r != 0) return r; r = setup_look_behind(node, reg, env); } break; default: r = 0; break; } return r; } #ifdef __GNUC__ __inline #endif static int setup_quant(Node* node, regex_t* reg, int state, ScanEnv* env) { int r; OnigLen d; QuantNode* qn = QUANT_(node); Node* body = NODE_BODY(node); if ((state & IN_REAL_REPEAT) != 0) { NODE_STATUS_ADD(node, IN_REAL_REPEAT); } if ((state & IN_MULTI_ENTRY) != 0) { NODE_STATUS_ADD(node, IN_MULTI_ENTRY); } if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 1) { d = tree_min_len(body, env); if (d == 0) { #ifdef USE_INSISTENT_CHECK_CAPTURES_IN_EMPTY_REPEAT qn->empty_info = quantifiers_memory_node_info(body); if (qn->empty_info == BODY_IS_EMPTY_REC) { if (NODE_TYPE(body) == NODE_BAG && BAG_(body)->type == BAG_MEMORY) { MEM_STATUS_ON(env->bt_mem_end, BAG_(body)->m.regnum); } } #else qn->empty_info = BODY_IS_EMPTY; #endif } } if (IS_REPEAT_INFINITE(qn->upper) || qn->upper >= 2) state |= IN_REAL_REPEAT; if (qn->lower != qn->upper) state |= IN_VAR_REPEAT; r = setup_tree(body, reg, state, env); if (r != 0) return r; /* expand string */ #define EXPAND_STRING_MAX_LENGTH 100 if (NODE_TYPE(body) == NODE_STRING) { if (!IS_REPEAT_INFINITE(qn->lower) && qn->lower == qn->upper && qn->lower > 1 && qn->lower <= EXPAND_STRING_MAX_LENGTH) { int len = NODE_STRING_LEN(body); StrNode* sn = STR_(body); if (len * qn->lower <= EXPAND_STRING_MAX_LENGTH) { int i, n = qn->lower; onig_node_conv_to_str_node(node, STR_(body)->flag); for (i = 0; i < n; i++) { r = onig_node_str_cat(node, sn->s, sn->end); if (r != 0) return r; } onig_node_free(body); return r; } } } if (qn->greedy && (qn->empty_info == BODY_IS_NOT_EMPTY)) { if (NODE_TYPE(body) == NODE_QUANT) { QuantNode* tqn = QUANT_(body); if (IS_NOT_NULL(tqn->head_exact)) { qn->head_exact = tqn->head_exact; tqn->head_exact = NULL; } } else { qn->head_exact = get_head_value_node(NODE_BODY(node), 1, reg); } } return r; } /* setup_tree does the following work. 1. check empty loop. (set qn->empty_info) 2. expand ignore-case in char class. 3. set memory status bit flags. (reg->mem_stats) 4. set qn->head_exact for [push, exact] -> [push_or_jump_exact1, exact]. 5. find invalid patterns in look-behind. 6. expand repeated string. */ static int setup_tree(Node* node, regex_t* reg, int state, ScanEnv* env) { int r = 0; switch (NODE_TYPE(node)) { case NODE_LIST: { Node* prev = NULL_NODE; do { r = setup_tree(NODE_CAR(node), reg, state, env); if (IS_NOT_NULL(prev) && r == 0) { r = next_setup(prev, NODE_CAR(node), reg); } prev = NODE_CAR(node); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); } break; case NODE_ALT: do { r = setup_tree(NODE_CAR(node), reg, (state | IN_ALT), env); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_STRING: if (IS_IGNORECASE(reg->options) && !NODE_STRING_IS_RAW(node)) { r = expand_case_fold_string(node, reg, state); } break; case NODE_BACKREF: { int i; int* p; BackRefNode* br = BACKREF_(node); p = BACKREFS_P(br); for (i = 0; i < br->back_num; i++) { if (p[i] > env->num_mem) return ONIGERR_INVALID_BACKREF; MEM_STATUS_ON(env->backrefed_mem, p[i]); MEM_STATUS_ON(env->bt_mem_start, p[i]); #ifdef USE_BACKREF_WITH_LEVEL if (NODE_IS_NEST_LEVEL(node)) { MEM_STATUS_ON(env->bt_mem_end, p[i]); } #endif } } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_OPTION: { OnigOptionType options = reg->options; reg->options = BAG_(node)->o.options; r = setup_tree(NODE_BODY(node), reg, state, env); reg->options = options; } break; case BAG_MEMORY: #ifdef USE_CALL state |= en->m.called_state; #endif if ((state & (IN_ALT | IN_NOT | IN_VAR_REPEAT | IN_MULTI_ENTRY)) != 0 || NODE_IS_RECURSION(node)) { MEM_STATUS_ON(env->bt_mem_start, en->m.regnum); } r = setup_tree(NODE_BODY(node), reg, state, env); break; case BAG_STOP_BACKTRACK: { Node* target = NODE_BODY(node); r = setup_tree(target, reg, state, env); if (NODE_TYPE(target) == NODE_QUANT) { QuantNode* tqn = QUANT_(target); if (IS_REPEAT_INFINITE(tqn->upper) && tqn->lower <= 1 && tqn->greedy != 0) { /* (?>a*), a*+ etc... */ if (NODE_IS_SIMPLE_TYPE(NODE_BODY(target))) NODE_STATUS_ADD(node, STOP_BT_SIMPLE_REPEAT); } } } break; case BAG_IF_ELSE: r = setup_tree(NODE_BODY(node), reg, (state | IN_ALT), env); if (r != 0) return r; if (IS_NOT_NULL(en->te.Then)) { r = setup_tree(en->te.Then, reg, (state | IN_ALT), env); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) r = setup_tree(en->te.Else, reg, (state | IN_ALT), env); break; } } break; case NODE_QUANT: r = setup_quant(node, reg, state, env); break; case NODE_ANCHOR: r = setup_anchor(node, reg, state, env); break; #ifdef USE_CALL case NODE_CALL: #endif case NODE_CTYPE: case NODE_CCLASS: case NODE_GIMMICK: default: break; } return r; } static int set_sunday_quick_search_or_bmh_skip_table(regex_t* reg, int case_expand, UChar* s, UChar* end, UChar skip[], int* roffset) { int i, j, k, len, offset; int n, clen; UChar* p; OnigEncoding enc; OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; enc = reg->enc; offset = ENC_GET_SKIP_OFFSET(enc); if (offset == ENC_SKIP_OFFSET_1_OR_0) { UChar* p = s; while (1) { len = enclen(enc, p); if (p + len >= end) { if (len == 1) offset = 1; else offset = 0; break; } p += len; } } len = (int )(end - s); if (len + offset >= UCHAR_MAX) return ONIGERR_PARSER_BUG; *roffset = offset; for (i = 0; i < CHAR_MAP_SIZE; i++) { skip[i] = (UChar )(len + offset); } for (p = s; p < end; ) { int z; clen = enclen(enc, p); if (p + clen > end) clen = (int )(end - p); len = (int )(end - p); for (j = 0; j < clen; j++) { z = len - j + (offset - 1); if (z <= 0) break; skip[p[j]] = z; } if (case_expand != 0) { n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag, p, end, items); for (k = 0; k < n; k++) { ONIGENC_CODE_TO_MBC(enc, items[k].code[0], buf); for (j = 0; j < clen; j++) { z = len - j + (offset - 1); if (z <= 0) break; if (skip[buf[j]] > z) skip[buf[j]] = z; } } } p += clen; } return 0; } #define OPT_EXACT_MAXLEN 24 #if OPT_EXACT_MAXLEN >= UCHAR_MAX #error Too big OPT_EXACT_MAXLEN #endif typedef struct { OnigLen min; /* min byte length */ OnigLen max; /* max byte length */ } MinMax; typedef struct { MinMax mmd; OnigEncoding enc; OnigOptionType options; OnigCaseFoldType case_fold_flag; ScanEnv* scan_env; } OptEnv; typedef struct { int left; int right; } OptAnc; typedef struct { MinMax mmd; /* position */ OptAnc anc; int reach_end; int case_fold; int good_case_fold; int len; UChar s[OPT_EXACT_MAXLEN]; } OptStr; typedef struct { MinMax mmd; /* position */ OptAnc anc; int value; /* weighted value */ UChar map[CHAR_MAP_SIZE]; } OptMap; typedef struct { MinMax len; OptAnc anc; OptStr sb; /* boundary */ OptStr sm; /* middle */ OptStr spr; /* prec read (?=...) */ OptMap map; /* boundary */ } OptNode; static int map_position_value(OnigEncoding enc, int i) { static const short int Vals[] = { 5, 1, 1, 1, 1, 1, 1, 1, 1, 10, 10, 1, 1, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 4, 7, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 5, 5, 5, 5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 1 }; if (i < (int )(sizeof(Vals)/sizeof(Vals[0]))) { if (i == 0 && ONIGENC_MBC_MINLEN(enc) > 1) return 20; else return (int )Vals[i]; } else return 4; /* Take it easy. */ } static int distance_value(MinMax* mm) { /* 1000 / (min-max-dist + 1) */ static const short int dist_vals[] = { 1000, 500, 333, 250, 200, 167, 143, 125, 111, 100, 91, 83, 77, 71, 67, 63, 59, 56, 53, 50, 48, 45, 43, 42, 40, 38, 37, 36, 34, 33, 32, 31, 30, 29, 29, 28, 27, 26, 26, 25, 24, 24, 23, 23, 22, 22, 21, 21, 20, 20, 20, 19, 19, 19, 18, 18, 18, 17, 17, 17, 16, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10 }; OnigLen d; if (mm->max == INFINITE_LEN) return 0; d = mm->max - mm->min; if (d < (OnigLen )(sizeof(dist_vals)/sizeof(dist_vals[0]))) /* return dist_vals[d] * 16 / (mm->min + 12); */ return (int )dist_vals[d]; else return 1; } static int comp_distance_value(MinMax* d1, MinMax* d2, int v1, int v2) { if (v2 <= 0) return -1; if (v1 <= 0) return 1; v1 *= distance_value(d1); v2 *= distance_value(d2); if (v2 > v1) return 1; if (v2 < v1) return -1; if (d2->min < d1->min) return 1; if (d2->min > d1->min) return -1; return 0; } static int is_equal_mml(MinMax* a, MinMax* b) { return a->min == b->min && a->max == b->max; } static void set_mml(MinMax* l, OnigLen min, OnigLen max) { l->min = min; l->max = max; } static void clear_mml(MinMax* l) { l->min = l->max = 0; } static void copy_mml(MinMax* to, MinMax* from) { to->min = from->min; to->max = from->max; } static void add_mml(MinMax* to, MinMax* from) { to->min = distance_add(to->min, from->min); to->max = distance_add(to->max, from->max); } static void alt_merge_mml(MinMax* to, MinMax* from) { if (to->min > from->min) to->min = from->min; if (to->max < from->max) to->max = from->max; } static void copy_opt_env(OptEnv* to, OptEnv* from) { *to = *from; } static void clear_opt_anc_info(OptAnc* a) { a->left = 0; a->right = 0; } static void copy_opt_anc_info(OptAnc* to, OptAnc* from) { *to = *from; } static void concat_opt_anc_info(OptAnc* to, OptAnc* left, OptAnc* right, OnigLen left_len, OnigLen right_len) { clear_opt_anc_info(to); to->left = left->left; if (left_len == 0) { to->left |= right->left; } to->right = right->right; if (right_len == 0) { to->right |= left->right; } else { to->right |= (left->right & ANCR_PREC_READ_NOT); } } static int is_left(int a) { if (a == ANCR_END_BUF || a == ANCR_SEMI_END_BUF || a == ANCR_END_LINE || a == ANCR_PREC_READ || a == ANCR_PREC_READ_NOT) return 0; return 1; } static int is_set_opt_anc_info(OptAnc* to, int anc) { if ((to->left & anc) != 0) return 1; return ((to->right & anc) != 0 ? 1 : 0); } static void add_opt_anc_info(OptAnc* to, int anc) { if (is_left(anc)) to->left |= anc; else to->right |= anc; } static void remove_opt_anc_info(OptAnc* to, int anc) { if (is_left(anc)) to->left &= ~anc; else to->right &= ~anc; } static void alt_merge_opt_anc_info(OptAnc* to, OptAnc* add) { to->left &= add->left; to->right &= add->right; } static int is_full_opt_exact(OptStr* e) { return e->len >= OPT_EXACT_MAXLEN; } static void clear_opt_exact(OptStr* e) { clear_mml(&e->mmd); clear_opt_anc_info(&e->anc); e->reach_end = 0; e->case_fold = 0; e->good_case_fold = 0; e->len = 0; e->s[0] = '\0'; } static void copy_opt_exact(OptStr* to, OptStr* from) { *to = *from; } static int concat_opt_exact(OptStr* to, OptStr* add, OnigEncoding enc) { int i, j, len, r; UChar *p, *end; OptAnc tanc; if (add->case_fold != 0) { if (! to->case_fold) { if (to->len > 1 || to->len >= add->len) return 0; /* avoid */ to->case_fold = 1; } else { if (to->good_case_fold != 0) { if (add->good_case_fold == 0) return 0; } } } r = 0; p = add->s; end = p + add->len; for (i = to->len; p < end; ) { len = enclen(enc, p); if (i + len > OPT_EXACT_MAXLEN) { r = 1; /* 1:full */ break; } for (j = 0; j < len && p < end; j++) to->s[i++] = *p++; } to->len = i; to->reach_end = (p == end ? add->reach_end : 0); concat_opt_anc_info(&tanc, &to->anc, &add->anc, 1, 1); if (! to->reach_end) tanc.right = 0; copy_opt_anc_info(&to->anc, &tanc); return r; } static void concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc) { int i, j, len; UChar *p; for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) { len = enclen(enc, p); if (i + len > OPT_EXACT_MAXLEN) break; for (j = 0; j < len && p < end; j++) to->s[i++] = *p++; } to->len = i; if (p >= end && to->len == (int )(end - s)) to->reach_end = 1; } static void alt_merge_opt_exact(OptStr* to, OptStr* add, OptEnv* env) { int i, j, len; if (add->len == 0 || to->len == 0) { clear_opt_exact(to); return ; } if (! is_equal_mml(&to->mmd, &add->mmd)) { clear_opt_exact(to); return ; } for (i = 0; i < to->len && i < add->len; ) { if (to->s[i] != add->s[i]) break; len = enclen(env->enc, to->s + i); for (j = 1; j < len; j++) { if (to->s[i+j] != add->s[i+j]) break; } if (j < len) break; i += len; } if (! add->reach_end || i < add->len || i < to->len) { to->reach_end = 0; } to->len = i; if (add->case_fold != 0) to->case_fold = 1; if (add->good_case_fold == 0) to->good_case_fold = 0; alt_merge_opt_anc_info(&to->anc, &add->anc); if (! to->reach_end) to->anc.right = 0; } static void select_opt_exact(OnigEncoding enc, OptStr* now, OptStr* alt) { int vn, va; vn = now->len; va = alt->len; if (va == 0) { return ; } else if (vn == 0) { copy_opt_exact(now, alt); return ; } else if (vn <= 2 && va <= 2) { /* ByteValTable[x] is big value --> low price */ va = map_position_value(enc, now->s[0]); vn = map_position_value(enc, alt->s[0]); if (now->len > 1) vn += 5; if (alt->len > 1) va += 5; } if (now->case_fold == 0) vn *= 2; if (alt->case_fold == 0) va *= 2; if (now->good_case_fold != 0) vn *= 4; if (alt->good_case_fold != 0) va *= 4; if (comp_distance_value(&now->mmd, &alt->mmd, vn, va) > 0) copy_opt_exact(now, alt); } static void clear_opt_map(OptMap* map) { static const OptMap clean_info = { {0, 0}, {0, 0}, 0, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; xmemcpy(map, &clean_info, sizeof(OptMap)); } static void copy_opt_map(OptMap* to, OptMap* from) { *to = *from; } static void add_char_opt_map(OptMap* m, UChar c, OnigEncoding enc) { if (m->map[c] == 0) { m->map[c] = 1; m->value += map_position_value(enc, c); } } static int add_char_amb_opt_map(OptMap* map, UChar* p, UChar* end, OnigEncoding enc, OnigCaseFoldType fold_flag) { OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int i, n; add_char_opt_map(map, p[0], enc); fold_flag = DISABLE_CASE_FOLD_MULTI_CHAR(fold_flag); n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, fold_flag, p, end, items); if (n < 0) return n; for (i = 0; i < n; i++) { ONIGENC_CODE_TO_MBC(enc, items[i].code[0], buf); add_char_opt_map(map, buf[0], enc); } return 0; } static void select_opt_map(OptMap* now, OptMap* alt) { static int z = 1<<15; /* 32768: something big value */ int vn, va; if (alt->value == 0) return ; if (now->value == 0) { copy_opt_map(now, alt); return ; } vn = z / now->value; va = z / alt->value; if (comp_distance_value(&now->mmd, &alt->mmd, vn, va) > 0) copy_opt_map(now, alt); } static int comp_opt_exact_or_map(OptStr* e, OptMap* m) { #define COMP_EM_BASE 20 int ae, am; int case_value; if (m->value <= 0) return -1; if (e->case_fold != 0) { if (e->good_case_fold != 0) case_value = 2; else case_value = 1; } else case_value = 3; ae = COMP_EM_BASE * e->len * case_value; am = COMP_EM_BASE * 5 * 2 / m->value; return comp_distance_value(&e->mmd, &m->mmd, ae, am); } static void alt_merge_opt_map(OnigEncoding enc, OptMap* to, OptMap* add) { int i, val; /* if (! is_equal_mml(&to->mmd, &add->mmd)) return ; */ if (to->value == 0) return ; if (add->value == 0 || to->mmd.max < add->mmd.min) { clear_opt_map(to); return ; } alt_merge_mml(&to->mmd, &add->mmd); val = 0; for (i = 0; i < CHAR_MAP_SIZE; i++) { if (add->map[i]) to->map[i] = 1; if (to->map[i]) val += map_position_value(enc, i); } to->value = val; alt_merge_opt_anc_info(&to->anc, &add->anc); } static void set_bound_node_opt_info(OptNode* opt, MinMax* plen) { copy_mml(&(opt->sb.mmd), plen); copy_mml(&(opt->spr.mmd), plen); copy_mml(&(opt->map.mmd), plen); } static void clear_node_opt_info(OptNode* opt) { clear_mml(&opt->len); clear_opt_anc_info(&opt->anc); clear_opt_exact(&opt->sb); clear_opt_exact(&opt->sm); clear_opt_exact(&opt->spr); clear_opt_map(&opt->map); } static void copy_node_opt_info(OptNode* to, OptNode* from) { *to = *from; } static void concat_left_node_opt_info(OnigEncoding enc, OptNode* to, OptNode* add) { int sb_reach, sm_reach; OptAnc tanc; concat_opt_anc_info(&tanc, &to->anc, &add->anc, to->len.max, add->len.max); copy_opt_anc_info(&to->anc, &tanc); if (add->sb.len > 0 && to->len.max == 0) { concat_opt_anc_info(&tanc, &to->anc, &add->sb.anc, to->len.max, add->len.max); copy_opt_anc_info(&add->sb.anc, &tanc); } if (add->map.value > 0 && to->len.max == 0) { if (add->map.mmd.max == 0) add->map.anc.left |= to->anc.left; } sb_reach = to->sb.reach_end; sm_reach = to->sm.reach_end; if (add->len.max != 0) to->sb.reach_end = to->sm.reach_end = 0; if (add->sb.len > 0) { if (sb_reach) { concat_opt_exact(&to->sb, &add->sb, enc); clear_opt_exact(&add->sb); } else if (sm_reach) { concat_opt_exact(&to->sm, &add->sb, enc); clear_opt_exact(&add->sb); } } select_opt_exact(enc, &to->sm, &add->sb); select_opt_exact(enc, &to->sm, &add->sm); if (to->spr.len > 0) { if (add->len.max > 0) { if (to->spr.len > (int )add->len.max) to->spr.len = add->len.max; if (to->spr.mmd.max == 0) select_opt_exact(enc, &to->sb, &to->spr); else select_opt_exact(enc, &to->sm, &to->spr); } } else if (add->spr.len > 0) { copy_opt_exact(&to->spr, &add->spr); } select_opt_map(&to->map, &add->map); add_mml(&to->len, &add->len); } static void alt_merge_node_opt_info(OptNode* to, OptNode* add, OptEnv* env) { alt_merge_opt_anc_info(&to->anc, &add->anc); alt_merge_opt_exact(&to->sb, &add->sb, env); alt_merge_opt_exact(&to->sm, &add->sm, env); alt_merge_opt_exact(&to->spr, &add->spr, env); alt_merge_opt_map(env->enc, &to->map, &add->map); alt_merge_mml(&to->len, &add->len); } #define MAX_NODE_OPT_INFO_REF_COUNT 5 static int optimize_nodes(Node* node, OptNode* opt, OptEnv* env) { int i; int r; OptNode xo; OnigEncoding enc; r = 0; enc = env->enc; clear_node_opt_info(opt); set_bound_node_opt_info(opt, &env->mmd); switch (NODE_TYPE(node)) { case NODE_LIST: { OptEnv nenv; Node* nd = node; copy_opt_env(&nenv, env); do { r = optimize_nodes(NODE_CAR(nd), &xo, &nenv); if (r == 0) { add_mml(&nenv.mmd, &xo.len); concat_left_node_opt_info(enc, opt, &xo); } } while (r == 0 && IS_NOT_NULL(nd = NODE_CDR(nd))); } break; case NODE_ALT: { Node* nd = node; do { r = optimize_nodes(NODE_CAR(nd), &xo, env); if (r == 0) { if (nd == node) copy_node_opt_info(opt, &xo); else alt_merge_node_opt_info(opt, &xo, env); } } while ((r == 0) && IS_NOT_NULL(nd = NODE_CDR(nd))); } break; case NODE_STRING: { StrNode* sn = STR_(node); int slen = (int )(sn->end - sn->s); /* int is_raw = NODE_STRING_IS_RAW(node); */ if (! NODE_STRING_IS_AMBIG(node)) { concat_opt_exact_str(&opt->sb, sn->s, sn->end, enc); if (slen > 0) { add_char_opt_map(&opt->map, *(sn->s), enc); } set_mml(&opt->len, slen, slen); } else { int max; if (NODE_STRING_IS_DONT_GET_OPT_INFO(node)) { int n = onigenc_strlen(enc, sn->s, sn->end); max = ONIGENC_MBC_MAXLEN_DIST(enc) * n; } else { concat_opt_exact_str(&opt->sb, sn->s, sn->end, enc); opt->sb.case_fold = 1; if (NODE_STRING_IS_GOOD_AMBIG(node)) opt->sb.good_case_fold = 1; if (slen > 0) { r = add_char_amb_opt_map(&opt->map, sn->s, sn->end, enc, env->case_fold_flag); if (r != 0) break; } max = slen; } set_mml(&opt->len, slen, max); } } break; case NODE_CCLASS: { int z; CClassNode* cc = CCLASS_(node); /* no need to check ignore case. (set in setup_tree()) */ if (IS_NOT_NULL(cc->mbuf) || IS_NCCLASS_NOT(cc)) { OnigLen min = ONIGENC_MBC_MINLEN(enc); OnigLen max = ONIGENC_MBC_MAXLEN_DIST(enc); set_mml(&opt->len, min, max); } else { for (i = 0; i < SINGLE_BYTE_SIZE; i++) { z = BITSET_AT(cc->bs, i); if ((z && ! IS_NCCLASS_NOT(cc)) || (! z && IS_NCCLASS_NOT(cc))) { add_char_opt_map(&opt->map, (UChar )i, enc); } } set_mml(&opt->len, 1, 1); } } break; case NODE_CTYPE: { int min, max; int range; max = ONIGENC_MBC_MAXLEN_DIST(enc); if (max == 1) { min = 1; switch (CTYPE_(node)->ctype) { case CTYPE_ANYCHAR: break; case ONIGENC_CTYPE_WORD: range = CTYPE_(node)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE; if (CTYPE_(node)->not != 0) { for (i = 0; i < range; i++) { if (! ONIGENC_IS_CODE_WORD(enc, i)) { add_char_opt_map(&opt->map, (UChar )i, enc); } } for (i = range; i < SINGLE_BYTE_SIZE; i++) { add_char_opt_map(&opt->map, (UChar )i, enc); } } else { for (i = 0; i < range; i++) { if (ONIGENC_IS_CODE_WORD(enc, i)) { add_char_opt_map(&opt->map, (UChar )i, enc); } } } break; } } else { min = ONIGENC_MBC_MINLEN(enc); } set_mml(&opt->len, min, max); } break; case NODE_ANCHOR: switch (ANCHOR_(node)->type) { case ANCR_BEGIN_BUF: case ANCR_BEGIN_POSITION: case ANCR_BEGIN_LINE: case ANCR_END_BUF: case ANCR_SEMI_END_BUF: case ANCR_END_LINE: case ANCR_PREC_READ_NOT: case ANCR_LOOK_BEHIND: add_opt_anc_info(&opt->anc, ANCHOR_(node)->type); break; case ANCR_PREC_READ: { r = optimize_nodes(NODE_BODY(node), &xo, env); if (r == 0) { if (xo.sb.len > 0) copy_opt_exact(&opt->spr, &xo.sb); else if (xo.sm.len > 0) copy_opt_exact(&opt->spr, &xo.sm); opt->spr.reach_end = 0; if (xo.map.value > 0) copy_opt_map(&opt->map, &xo.map); } } break; case ANCR_LOOK_BEHIND_NOT: break; } break; case NODE_BACKREF: if (! NODE_IS_CHECKER(node)) { int* backs; OnigLen min, max, tmin, tmax; MemEnv* mem_env = SCANENV_MEMENV(env->scan_env); BackRefNode* br = BACKREF_(node); if (NODE_IS_RECURSION(node)) { set_mml(&opt->len, 0, INFINITE_LEN); break; } backs = BACKREFS_P(br); min = tree_min_len(mem_env[backs[0]].node, env->scan_env); max = tree_max_len(mem_env[backs[0]].node, env->scan_env); for (i = 1; i < br->back_num; i++) { tmin = tree_min_len(mem_env[backs[i]].node, env->scan_env); tmax = tree_max_len(mem_env[backs[i]].node, env->scan_env); if (min > tmin) min = tmin; if (max < tmax) max = tmax; } set_mml(&opt->len, min, max); } break; #ifdef USE_CALL case NODE_CALL: if (NODE_IS_RECURSION(node)) set_mml(&opt->len, 0, INFINITE_LEN); else { OnigOptionType save = env->options; env->options = BAG_(NODE_BODY(node))->o.options; r = optimize_nodes(NODE_BODY(node), opt, env); env->options = save; } break; #endif case NODE_QUANT: { OnigLen min, max; QuantNode* qn = QUANT_(node); r = optimize_nodes(NODE_BODY(node), &xo, env); if (r != 0) break; if (qn->lower > 0) { copy_node_opt_info(opt, &xo); if (xo.sb.len > 0) { if (xo.sb.reach_end) { for (i = 2; i <= qn->lower && ! is_full_opt_exact(&opt->sb); i++) { int rc = concat_opt_exact(&opt->sb, &xo.sb, enc); if (rc > 0) break; } if (i < qn->lower) opt->sb.reach_end = 0; } } if (qn->lower != qn->upper) { opt->sb.reach_end = 0; opt->sm.reach_end = 0; } if (qn->lower > 1) opt->sm.reach_end = 0; } if (IS_REPEAT_INFINITE(qn->upper)) { if (env->mmd.max == 0 && NODE_IS_ANYCHAR(NODE_BODY(node)) && qn->greedy != 0) { if (IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), env))) add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_ML); else add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF); } max = (xo.len.max > 0 ? INFINITE_LEN : 0); } else { max = distance_multiply(xo.len.max, qn->upper); } min = distance_multiply(xo.len.min, qn->lower); set_mml(&opt->len, min, max); } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_OPTION: { OnigOptionType save = env->options; env->options = en->o.options; r = optimize_nodes(NODE_BODY(node), opt, env); env->options = save; } break; case BAG_MEMORY: #ifdef USE_CALL en->opt_count++; if (en->opt_count > MAX_NODE_OPT_INFO_REF_COUNT) { OnigLen min, max; min = 0; max = INFINITE_LEN; if (NODE_IS_MIN_FIXED(node)) min = en->min_len; if (NODE_IS_MAX_FIXED(node)) max = en->max_len; set_mml(&opt->len, min, max); } else #endif { r = optimize_nodes(NODE_BODY(node), opt, env); if (is_set_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK)) { if (MEM_STATUS_AT0(env->scan_env->backrefed_mem, en->m.regnum)) remove_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK); } } break; case BAG_STOP_BACKTRACK: r = optimize_nodes(NODE_BODY(node), opt, env); break; case BAG_IF_ELSE: { OptEnv nenv; copy_opt_env(&nenv, env); r = optimize_nodes(NODE_BAG_BODY(en), &xo, &nenv); if (r == 0) { add_mml(&nenv.mmd, &xo.len); concat_left_node_opt_info(enc, opt, &xo); if (IS_NOT_NULL(en->te.Then)) { r = optimize_nodes(en->te.Then, &xo, &nenv); if (r == 0) { concat_left_node_opt_info(enc, opt, &xo); } } if (IS_NOT_NULL(en->te.Else)) { r = optimize_nodes(en->te.Else, &xo, env); if (r == 0) alt_merge_node_opt_info(opt, &xo, env); } } } break; } } break; case NODE_GIMMICK: break; default: #ifdef ONIG_DEBUG fprintf(stderr, "optimize_nodes: undefined node type %d\n", NODE_TYPE(node)); #endif r = ONIGERR_TYPE_BUG; break; } return r; } static int set_optimize_exact(regex_t* reg, OptStr* e) { int r; if (e->len == 0) return 0; reg->exact = (UChar* )xmalloc(e->len); CHECK_NULL_RETURN_MEMERR(reg->exact); xmemcpy(reg->exact, e->s, e->len); reg->exact_end = reg->exact + e->len; if (e->case_fold) { reg->optimize = OPTIMIZE_STR_CASE_FOLD; if (e->good_case_fold != 0) { if (e->len >= 2) { r = set_sunday_quick_search_or_bmh_skip_table(reg, 1, reg->exact, reg->exact_end, reg->map, &(reg->map_offset)); if (r != 0) return r; reg->optimize = OPTIMIZE_STR_CASE_FOLD_FAST; } } } else { int allow_reverse; allow_reverse = ONIGENC_IS_ALLOWED_REVERSE_MATCH(reg->enc, reg->exact, reg->exact_end); if (e->len >= 2 || (e->len >= 1 && allow_reverse)) { r = set_sunday_quick_search_or_bmh_skip_table(reg, 0, reg->exact, reg->exact_end, reg->map, &(reg->map_offset)); if (r != 0) return r; reg->optimize = (allow_reverse != 0 ? OPTIMIZE_STR_FAST : OPTIMIZE_STR_FAST_STEP_FORWARD); } else { reg->optimize = OPTIMIZE_STR; } } reg->dmin = e->mmd.min; reg->dmax = e->mmd.max; if (reg->dmin != INFINITE_LEN) { reg->threshold_len = reg->dmin + (int )(reg->exact_end - reg->exact); } return 0; } static void set_optimize_map(regex_t* reg, OptMap* m) { int i; for (i = 0; i < CHAR_MAP_SIZE; i++) reg->map[i] = m->map[i]; reg->optimize = OPTIMIZE_MAP; reg->dmin = m->mmd.min; reg->dmax = m->mmd.max; if (reg->dmin != INFINITE_LEN) { reg->threshold_len = reg->dmin + 1; } } static void set_sub_anchor(regex_t* reg, OptAnc* anc) { reg->sub_anchor |= anc->left & ANCR_BEGIN_LINE; reg->sub_anchor |= anc->right & ANCR_END_LINE; } #if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH) static void print_optimize_info(FILE* f, regex_t* reg); #endif static int set_optimize_info_from_tree(Node* node, regex_t* reg, ScanEnv* scan_env) { int r; OptNode opt; OptEnv env; env.enc = reg->enc; env.options = reg->options; env.case_fold_flag = reg->case_fold_flag; env.scan_env = scan_env; clear_mml(&env.mmd); r = optimize_nodes(node, &opt, &env); if (r != 0) return r; reg->anchor = opt.anc.left & (ANCR_BEGIN_BUF | ANCR_BEGIN_POSITION | ANCR_ANYCHAR_INF | ANCR_ANYCHAR_INF_ML | ANCR_LOOK_BEHIND); if ((opt.anc.left & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) != 0) reg->anchor &= ~ANCR_ANYCHAR_INF_ML; reg->anchor |= opt.anc.right & (ANCR_END_BUF | ANCR_SEMI_END_BUF | ANCR_PREC_READ_NOT); if (reg->anchor & (ANCR_END_BUF | ANCR_SEMI_END_BUF)) { reg->anchor_dmin = opt.len.min; reg->anchor_dmax = opt.len.max; } if (opt.sb.len > 0 || opt.sm.len > 0) { select_opt_exact(reg->enc, &opt.sb, &opt.sm); if (opt.map.value > 0 && comp_opt_exact_or_map(&opt.sb, &opt.map) > 0) { goto set_map; } else { r = set_optimize_exact(reg, &opt.sb); set_sub_anchor(reg, &opt.sb.anc); } } else if (opt.map.value > 0) { set_map: set_optimize_map(reg, &opt.map); set_sub_anchor(reg, &opt.map.anc); } else { reg->sub_anchor |= opt.anc.left & ANCR_BEGIN_LINE; if (opt.len.max == 0) reg->sub_anchor |= opt.anc.right & ANCR_END_LINE; } #if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH) print_optimize_info(stderr, reg); #endif return r; } static void clear_optimize_info(regex_t* reg) { reg->optimize = OPTIMIZE_NONE; reg->anchor = 0; reg->anchor_dmin = 0; reg->anchor_dmax = 0; reg->sub_anchor = 0; reg->exact_end = (UChar* )NULL; reg->map_offset = 0; reg->threshold_len = 0; if (IS_NOT_NULL(reg->exact)) { xfree(reg->exact); reg->exact = (UChar* )NULL; } } #ifdef ONIG_DEBUG static void print_enc_string(FILE* fp, OnigEncoding enc, const UChar *s, const UChar *end) { fprintf(fp, "\nPATTERN: /"); if (ONIGENC_MBC_MINLEN(enc) > 1) { const UChar *p; OnigCodePoint code; p = s; while (p < end) { code = ONIGENC_MBC_TO_CODE(enc, p, end); if (code >= 0x80) { fprintf(fp, " 0x%04x ", (int )code); } else { fputc((int )code, fp); } p += enclen(enc, p); } } else { while (s < end) { fputc((int )*s, fp); s++; } } fprintf(fp, "/\n"); } #endif /* ONIG_DEBUG */ #if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH) static void print_distance_range(FILE* f, OnigLen a, OnigLen b) { if (a == INFINITE_LEN) fputs("inf", f); else fprintf(f, "(%u)", a); fputs("-", f); if (b == INFINITE_LEN) fputs("inf", f); else fprintf(f, "(%u)", b); } static void print_anchor(FILE* f, int anchor) { int q = 0; fprintf(f, "["); if (anchor & ANCR_BEGIN_BUF) { fprintf(f, "begin-buf"); q = 1; } if (anchor & ANCR_BEGIN_LINE) { if (q) fprintf(f, ", "); q = 1; fprintf(f, "begin-line"); } if (anchor & ANCR_BEGIN_POSITION) { if (q) fprintf(f, ", "); q = 1; fprintf(f, "begin-pos"); } if (anchor & ANCR_END_BUF) { if (q) fprintf(f, ", "); q = 1; fprintf(f, "end-buf"); } if (anchor & ANCR_SEMI_END_BUF) { if (q) fprintf(f, ", "); q = 1; fprintf(f, "semi-end-buf"); } if (anchor & ANCR_END_LINE) { if (q) fprintf(f, ", "); q = 1; fprintf(f, "end-line"); } if (anchor & ANCR_ANYCHAR_INF) { if (q) fprintf(f, ", "); q = 1; fprintf(f, "anychar-inf"); } if (anchor & ANCR_ANYCHAR_INF_ML) { if (q) fprintf(f, ", "); fprintf(f, "anychar-inf-ml"); } fprintf(f, "]"); } static void print_optimize_info(FILE* f, regex_t* reg) { static const char* on[] = { "NONE", "STR", "STR_FAST", "STR_FAST_STEP_FORWARD", "STR_CASE_FOLD_FAST", "STR_CASE_FOLD", "MAP" }; fprintf(f, "optimize: %s\n", on[reg->optimize]); fprintf(f, " anchor: "); print_anchor(f, reg->anchor); if ((reg->anchor & ANCR_END_BUF_MASK) != 0) print_distance_range(f, reg->anchor_dmin, reg->anchor_dmax); fprintf(f, "\n"); if (reg->optimize) { fprintf(f, " sub anchor: "); print_anchor(f, reg->sub_anchor); fprintf(f, "\n"); } fprintf(f, "\n"); if (reg->exact) { UChar *p; fprintf(f, "exact: ["); for (p = reg->exact; p < reg->exact_end; p++) { fputc(*p, f); } fprintf(f, "]: length: %ld\n", (reg->exact_end - reg->exact)); } else if (reg->optimize & OPTIMIZE_MAP) { int c, i, n = 0; for (i = 0; i < CHAR_MAP_SIZE; i++) if (reg->map[i]) n++; fprintf(f, "map: n=%d\n", n); if (n > 0) { c = 0; fputc('[', f); for (i = 0; i < CHAR_MAP_SIZE; i++) { if (reg->map[i] != 0) { if (c > 0) fputs(", ", f); c++; if (ONIGENC_MBC_MAXLEN(reg->enc) == 1 && ONIGENC_IS_CODE_PRINT(reg->enc, (OnigCodePoint )i)) fputc(i, f); else fprintf(f, "%d", i); } } fprintf(f, "]\n"); } } } #endif extern RegexExt* onig_get_regex_ext(regex_t* reg) { if (IS_NULL(reg->extp)) { RegexExt* ext = (RegexExt* )xmalloc(sizeof(*ext)); if (IS_NULL(ext)) return 0; ext->pattern = 0; ext->pattern_end = 0; #ifdef USE_CALLOUT ext->tag_table = 0; ext->callout_num = 0; ext->callout_list_alloc = 0; ext->callout_list = 0; #endif reg->extp = ext; } return reg->extp; } static void free_regex_ext(RegexExt* ext) { if (IS_NOT_NULL(ext)) { if (IS_NOT_NULL(ext->pattern)) xfree((void* )ext->pattern); #ifdef USE_CALLOUT if (IS_NOT_NULL(ext->tag_table)) onig_callout_tag_table_free(ext->tag_table); if (IS_NOT_NULL(ext->callout_list)) onig_free_reg_callout_list(ext->callout_num, ext->callout_list); #endif xfree(ext); } } extern int onig_ext_set_pattern(regex_t* reg, const UChar* pattern, const UChar* pattern_end) { RegexExt* ext; UChar* s; ext = onig_get_regex_ext(reg); CHECK_NULL_RETURN_MEMERR(ext); s = onigenc_strdup(reg->enc, pattern, pattern_end); CHECK_NULL_RETURN_MEMERR(s); ext->pattern = s; ext->pattern_end = s + (pattern_end - pattern); return ONIG_NORMAL; } extern void onig_free_body(regex_t* reg) { if (IS_NOT_NULL(reg)) { ops_free(reg); if (IS_NOT_NULL(reg->string_pool)) { xfree(reg->string_pool); reg->string_pool_end = reg->string_pool = 0; } if (IS_NOT_NULL(reg->exact)) xfree(reg->exact); if (IS_NOT_NULL(reg->repeat_range)) xfree(reg->repeat_range); if (IS_NOT_NULL(reg->extp)) { free_regex_ext(reg->extp); reg->extp = 0; } onig_names_free(reg); } } extern void onig_free(regex_t* reg) { if (IS_NOT_NULL(reg)) { onig_free_body(reg); xfree(reg); } } #ifdef ONIG_DEBUG_PARSE static void print_tree P_((FILE* f, Node* node)); #endif extern int onig_init_for_match_at(regex_t* reg); extern int onig_compile(regex_t* reg, const UChar* pattern, const UChar* pattern_end, OnigErrorInfo* einfo) { int r; Node* root; ScanEnv scan_env; #ifdef USE_CALL UnsetAddrList uslist; #endif root = 0; if (IS_NOT_NULL(einfo)) { einfo->enc = reg->enc; einfo->par = (UChar* )NULL; } #ifdef ONIG_DEBUG print_enc_string(stderr, reg->enc, pattern, pattern_end); #endif if (reg->ops_alloc == 0) { r = ops_init(reg, OPS_INIT_SIZE); if (r != 0) goto end; } else reg->ops_used = 0; reg->string_pool = 0; reg->string_pool_end = 0; reg->num_mem = 0; reg->num_repeat = 0; reg->num_null_check = 0; reg->repeat_range_alloc = 0; reg->repeat_range = (OnigRepeatRange* )NULL; r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env); if (r != 0) goto err; /* mixed use named group and no-named group */ if (scan_env.num_named > 0 && IS_SYNTAX_BV(scan_env.syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && ! ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { if (scan_env.num_named != scan_env.num_mem) r = disable_noname_group_capture(&root, reg, &scan_env); else r = numbered_ref_check(root); if (r != 0) goto err; } r = check_backrefs(root, &scan_env); if (r != 0) goto err; #ifdef USE_CALL if (scan_env.num_call > 0) { r = unset_addr_list_init(&uslist, scan_env.num_call); if (r != 0) goto err; scan_env.unset_addr_list = &uslist; r = setup_call(root, &scan_env, 0); if (r != 0) goto err_unset; r = setup_call2(root); if (r != 0) goto err_unset; r = recursive_call_check_trav(root, &scan_env, 0); if (r < 0) goto err_unset; r = infinite_recursive_call_check_trav(root, &scan_env); if (r != 0) goto err_unset; setup_called_state(root, 0); } reg->num_call = scan_env.num_call; #endif r = setup_tree(root, reg, 0, &scan_env); if (r != 0) goto err_unset; #ifdef ONIG_DEBUG_PARSE print_tree(stderr, root); #endif reg->capture_history = scan_env.capture_history; reg->bt_mem_start = scan_env.bt_mem_start; reg->bt_mem_start |= reg->capture_history; if (IS_FIND_CONDITION(reg->options)) MEM_STATUS_ON_ALL(reg->bt_mem_end); else { reg->bt_mem_end = scan_env.bt_mem_end; reg->bt_mem_end |= reg->capture_history; } reg->bt_mem_start |= reg->bt_mem_end; clear_optimize_info(reg); #ifndef ONIG_DONT_OPTIMIZE r = set_optimize_info_from_tree(root, reg, &scan_env); if (r != 0) goto err_unset; #endif if (IS_NOT_NULL(scan_env.mem_env_dynamic)) { xfree(scan_env.mem_env_dynamic); scan_env.mem_env_dynamic = (MemEnv* )NULL; } r = compile_tree(root, reg, &scan_env); if (r == 0) { if (scan_env.keep_num > 0) { r = add_op(reg, OP_UPDATE_VAR); if (r != 0) goto err; COP(reg)->update_var.type = UPDATE_VAR_KEEP_FROM_STACK_LAST; COP(reg)->update_var.id = 0; /* not used */ } r = add_op(reg, OP_END); if (r != 0) goto err; #ifdef USE_CALL if (scan_env.num_call > 0) { r = fix_unset_addr_list(&uslist, reg); unset_addr_list_end(&uslist); if (r != 0) goto err; } #endif if ((reg->num_repeat != 0) || (reg->bt_mem_end != 0) #ifdef USE_CALLOUT || (IS_NOT_NULL(reg->extp) && reg->extp->callout_num != 0) #endif ) reg->stack_pop_level = STACK_POP_LEVEL_ALL; else { if (reg->bt_mem_start != 0) reg->stack_pop_level = STACK_POP_LEVEL_MEM_START; else reg->stack_pop_level = STACK_POP_LEVEL_FREE; } r = ops_make_string_pool(reg); if (r != 0) goto err; } #ifdef USE_CALL else if (scan_env.num_call > 0) { unset_addr_list_end(&uslist); } #endif onig_node_free(root); #ifdef ONIG_DEBUG_COMPILE onig_print_names(stderr, reg); onig_print_compiled_byte_code_list(stderr, reg); #endif #ifdef USE_DIRECT_THREADED_CODE /* opcode -> opaddr */ onig_init_for_match_at(reg); #endif end: return r; err_unset: #ifdef USE_CALL if (scan_env.num_call > 0) { unset_addr_list_end(&uslist); } #endif err: if (IS_NOT_NULL(scan_env.error)) { if (IS_NOT_NULL(einfo)) { einfo->par = scan_env.error; einfo->par_end = scan_env.error_end; } } onig_node_free(root); if (IS_NOT_NULL(scan_env.mem_env_dynamic)) xfree(scan_env.mem_env_dynamic); return r; } static int onig_inited = 0; extern int onig_reg_init(regex_t* reg, OnigOptionType option, OnigCaseFoldType case_fold_flag, OnigEncoding enc, OnigSyntaxType* syntax) { int r; xmemset(reg, 0, sizeof(*reg)); if (onig_inited == 0) { #if 0 return ONIGERR_LIBRARY_IS_NOT_INITIALIZED; #else r = onig_initialize(&enc, 1); if (r != 0) return ONIGERR_FAIL_TO_INITIALIZE; onig_warning("You didn't call onig_initialize() explicitly"); #endif } if (IS_NULL(reg)) return ONIGERR_INVALID_ARGUMENT; if (ONIGENC_IS_UNDEF(enc)) return ONIGERR_DEFAULT_ENCODING_IS_NOT_SETTED; if ((option & (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP)) == (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP)) { return ONIGERR_INVALID_COMBINATION_OF_OPTIONS; } if ((option & ONIG_OPTION_NEGATE_SINGLELINE) != 0) { option |= syntax->options; option &= ~ONIG_OPTION_SINGLELINE; } else option |= syntax->options; (reg)->enc = enc; (reg)->options = option; (reg)->syntax = syntax; (reg)->optimize = 0; (reg)->exact = (UChar* )NULL; (reg)->extp = (RegexExt* )NULL; (reg)->ops = (Operation* )NULL; (reg)->ops_curr = (Operation* )NULL; (reg)->ops_used = 0; (reg)->ops_alloc = 0; (reg)->name_table = (void* )NULL; (reg)->case_fold_flag = case_fold_flag; return 0; } extern int onig_new_without_alloc(regex_t* reg, const UChar* pattern, const UChar* pattern_end, OnigOptionType option, OnigEncoding enc, OnigSyntaxType* syntax, OnigErrorInfo* einfo) { int r; r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax); if (r != 0) return r; r = onig_compile(reg, pattern, pattern_end, einfo); return r; } extern int onig_new(regex_t** reg, const UChar* pattern, const UChar* pattern_end, OnigOptionType option, OnigEncoding enc, OnigSyntaxType* syntax, OnigErrorInfo* einfo) { int r; *reg = (regex_t* )xmalloc(sizeof(regex_t)); if (IS_NULL(*reg)) return ONIGERR_MEMORY; r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax); if (r != 0) goto err; r = onig_compile(*reg, pattern, pattern_end, einfo); if (r != 0) { err: onig_free(*reg); *reg = NULL; } return r; } extern int onig_initialize(OnigEncoding encodings[], int n) { int i; int r; if (onig_inited != 0) return 0; onigenc_init(); onig_inited = 1; for (i = 0; i < n; i++) { OnigEncoding enc = encodings[i]; r = onig_initialize_encoding(enc); if (r != 0) return r; } return ONIG_NORMAL; } typedef struct EndCallListItem { struct EndCallListItem* next; void (*func)(void); } EndCallListItemType; static EndCallListItemType* EndCallTop; extern void onig_add_end_call(void (*func)(void)) { EndCallListItemType* item; item = (EndCallListItemType* )xmalloc(sizeof(*item)); if (item == 0) return ; item->next = EndCallTop; item->func = func; EndCallTop = item; } static void exec_end_call_list(void) { EndCallListItemType* prev; void (*func)(void); while (EndCallTop != 0) { func = EndCallTop->func; (*func)(); prev = EndCallTop; EndCallTop = EndCallTop->next; xfree(prev); } } extern int onig_end(void) { exec_end_call_list(); #ifdef USE_CALLOUT onig_global_callout_names_free(); #endif onigenc_end(); onig_inited = 0; return 0; } extern int onig_is_in_code_range(const UChar* p, OnigCodePoint code) { OnigCodePoint n, *data; OnigCodePoint low, high, x; GET_CODE_POINT(n, p); data = (OnigCodePoint* )p; data++; for (low = 0, high = n; low < high; ) { x = (low + high) >> 1; if (code > data[x * 2 + 1]) low = x + 1; else high = x; } return ((low < n && code >= data[low * 2]) ? 1 : 0); } extern int onig_is_code_in_cc_len(int elen, OnigCodePoint code, /* CClassNode* */ void* cc_arg) { int found; CClassNode* cc = (CClassNode* )cc_arg; if (elen > 1 || (code >= SINGLE_BYTE_SIZE)) { if (IS_NULL(cc->mbuf)) { found = 0; } else { found = onig_is_in_code_range(cc->mbuf->p, code) != 0; } } else { found = BITSET_AT(cc->bs, code) != 0; } if (IS_NCCLASS_NOT(cc)) return !found; else return found; } extern int onig_is_code_in_cc(OnigEncoding enc, OnigCodePoint code, CClassNode* cc) { int len; if (ONIGENC_MBC_MINLEN(enc) > 1) { len = 2; } else { len = ONIGENC_CODE_TO_MBCLEN(enc, code); } return onig_is_code_in_cc_len(len, code, cc); } #ifdef ONIG_DEBUG_PARSE static void p_string(FILE* f, int len, UChar* s) { fputs(":", f); while (len-- > 0) { fputc(*s++, f); } } static void Indent(FILE* f, int indent) { int i; for (i = 0; i < indent; i++) putc(' ', f); } static void print_indent_tree(FILE* f, Node* node, int indent) { int i; NodeType type; UChar* p; int add = 3; Indent(f, indent); if (IS_NULL(node)) { fprintf(f, "ERROR: null node!!!\n"); exit (0); } type = NODE_TYPE(node); switch (type) { case NODE_LIST: case NODE_ALT: if (type == NODE_LIST) fprintf(f, "<list:%p>\n", node); else fprintf(f, "<alt:%p>\n", node); print_indent_tree(f, NODE_CAR(node), indent + add); while (IS_NOT_NULL(node = NODE_CDR(node))) { if (NODE_TYPE(node) != type) { fprintf(f, "ERROR: list/alt right is not a cons. %d\n", NODE_TYPE(node)); exit(0); } print_indent_tree(f, NODE_CAR(node), indent + add); } break; case NODE_STRING: { char* mode; char* dont; char* good; if (NODE_STRING_IS_RAW(node)) mode = "-raw"; else if (NODE_STRING_IS_AMBIG(node)) mode = "-ambig"; else mode = ""; if (NODE_STRING_IS_GOOD_AMBIG(node)) good = "-good"; else good = ""; if (NODE_STRING_IS_DONT_GET_OPT_INFO(node)) dont = " (dont-opt)"; else dont = ""; fprintf(f, "<string%s%s%s:%p>", mode, good, dont, node); for (p = STR_(node)->s; p < STR_(node)->end; p++) { if (*p >= 0x20 && *p < 0x7f) fputc(*p, f); else { fprintf(f, " 0x%02x", *p); } } } break; case NODE_CCLASS: fprintf(f, "<cclass:%p>", node); if (IS_NCCLASS_NOT(CCLASS_(node))) fputs(" not", f); if (CCLASS_(node)->mbuf) { BBuf* bbuf = CCLASS_(node)->mbuf; for (i = 0; i < bbuf->used; i++) { if (i > 0) fprintf(f, ","); fprintf(f, "%0x", bbuf->p[i]); } } break; case NODE_CTYPE: fprintf(f, "<ctype:%p> ", node); switch (CTYPE_(node)->ctype) { case CTYPE_ANYCHAR: fprintf(f, "<anychar:%p>", node); break; case ONIGENC_CTYPE_WORD: if (CTYPE_(node)->not != 0) fputs("not word", f); else fputs("word", f); if (CTYPE_(node)->ascii_mode != 0) fputs(" (ascii)", f); break; default: fprintf(f, "ERROR: undefined ctype.\n"); exit(0); } break; case NODE_ANCHOR: fprintf(f, "<anchor:%p> ", node); switch (ANCHOR_(node)->type) { case ANCR_BEGIN_BUF: fputs("begin buf", f); break; case ANCR_END_BUF: fputs("end buf", f); break; case ANCR_BEGIN_LINE: fputs("begin line", f); break; case ANCR_END_LINE: fputs("end line", f); break; case ANCR_SEMI_END_BUF: fputs("semi end buf", f); break; case ANCR_BEGIN_POSITION: fputs("begin position", f); break; case ANCR_WORD_BOUNDARY: fputs("word boundary", f); break; case ANCR_NO_WORD_BOUNDARY: fputs("not word boundary", f); break; #ifdef USE_WORD_BEGIN_END case ANCR_WORD_BEGIN: fputs("word begin", f); break; case ANCR_WORD_END: fputs("word end", f); break; #endif case ANCR_TEXT_SEGMENT_BOUNDARY: fputs("text-segment boundary", f); break; case ANCR_NO_TEXT_SEGMENT_BOUNDARY: fputs("no text-segment boundary", f); break; case ANCR_PREC_READ: fprintf(f, "prec read\n"); print_indent_tree(f, NODE_BODY(node), indent + add); break; case ANCR_PREC_READ_NOT: fprintf(f, "prec read not\n"); print_indent_tree(f, NODE_BODY(node), indent + add); break; case ANCR_LOOK_BEHIND: fprintf(f, "look behind\n"); print_indent_tree(f, NODE_BODY(node), indent + add); break; case ANCR_LOOK_BEHIND_NOT: fprintf(f, "look behind not\n"); print_indent_tree(f, NODE_BODY(node), indent + add); break; default: fprintf(f, "ERROR: undefined anchor type.\n"); break; } break; case NODE_BACKREF: { int* p; BackRefNode* br = BACKREF_(node); p = BACKREFS_P(br); fprintf(f, "<backref%s:%p>", NODE_IS_CHECKER(node) ? "-checker" : "", node); for (i = 0; i < br->back_num; i++) { if (i > 0) fputs(", ", f); fprintf(f, "%d", p[i]); } } break; #ifdef USE_CALL case NODE_CALL: { CallNode* cn = CALL_(node); fprintf(f, "<call:%p>", node); p_string(f, cn->name_end - cn->name, cn->name); } break; #endif case NODE_QUANT: fprintf(f, "<quantifier:%p>{%d,%d}%s\n", node, QUANT_(node)->lower, QUANT_(node)->upper, (QUANT_(node)->greedy ? "" : "?")); print_indent_tree(f, NODE_BODY(node), indent + add); break; case NODE_BAG: fprintf(f, "<bag:%p> ", node); switch (BAG_(node)->type) { case BAG_OPTION: fprintf(f, "option:%d", BAG_(node)->o.options); break; case BAG_MEMORY: fprintf(f, "memory:%d", BAG_(node)->m.regnum); break; case BAG_STOP_BACKTRACK: fprintf(f, "stop-bt"); break; case BAG_IF_ELSE: fprintf(f, "if-else"); break; } fprintf(f, "\n"); print_indent_tree(f, NODE_BODY(node), indent + add); break; case NODE_GIMMICK: fprintf(f, "<gimmick:%p> ", node); switch (GIMMICK_(node)->type) { case GIMMICK_FAIL: fprintf(f, "fail"); break; case GIMMICK_SAVE: fprintf(f, "save:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id); break; case GIMMICK_UPDATE_VAR: fprintf(f, "update_var:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id); break; #ifdef USE_CALLOUT case GIMMICK_CALLOUT: switch (GIMMICK_(node)->detail_type) { case ONIG_CALLOUT_OF_CONTENTS: fprintf(f, "callout:contents:%d", GIMMICK_(node)->num); break; case ONIG_CALLOUT_OF_NAME: fprintf(f, "callout:name:%d:%d", GIMMICK_(node)->id, GIMMICK_(node)->num); break; } #endif } break; default: fprintf(f, "print_indent_tree: undefined node type %d\n", NODE_TYPE(node)); break; } if (type != NODE_LIST && type != NODE_ALT && type != NODE_QUANT && type != NODE_BAG) fprintf(f, "\n"); fflush(f); } static void print_tree(FILE* f, Node* node) { print_indent_tree(f, node, 0); } #endif
./CrossVul/dataset_final_sorted/CWE-476/c/bad_914_0
crossvul-cpp_data_bad_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; TSRMLS_FETCH(); 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_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); 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); PHP_CLEANUP_CLASS_ATTRIBUTES(); 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_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); 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); PHP_CLEANUP_CLASS_ATTRIBUTES(); 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); } 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; } /* 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/bad_5514_4
crossvul-cpp_data_bad_3060_14
/* Keyring handling * * Copyright (C) 2004-2005, 2008, 2013 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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/security.h> #include <linux/seq_file.h> #include <linux/err.h> #include <keys/keyring-type.h> #include <keys/user-type.h> #include <linux/assoc_array_priv.h> #include <linux/uaccess.h> #include "internal.h" /* * When plumbing the depths of the key tree, this sets a hard limit * set on how deep we're willing to go. */ #define KEYRING_SEARCH_MAX_DEPTH 6 /* * We keep all named keyrings in a hash to speed looking them up. */ #define KEYRING_NAME_HASH_SIZE (1 << 5) /* * We mark pointers we pass to the associative array with bit 1 set if * they're keyrings and clear otherwise. */ #define KEYRING_PTR_SUBTYPE 0x2UL static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x) { return (unsigned long)x & KEYRING_PTR_SUBTYPE; } static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x) { void *object = assoc_array_ptr_to_leaf(x); return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE); } static inline void *keyring_key_to_ptr(struct key *key) { if (key->type == &key_type_keyring) return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE); return key; } static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE]; static DEFINE_RWLOCK(keyring_name_lock); static inline unsigned keyring_hash(const char *desc) { unsigned bucket = 0; for (; *desc; desc++) bucket += (unsigned char)*desc; return bucket & (KEYRING_NAME_HASH_SIZE - 1); } /* * The keyring key type definition. Keyrings are simply keys of this type and * can be treated as ordinary keys in addition to having their own special * operations. */ static int keyring_preparse(struct key_preparsed_payload *prep); static void keyring_free_preparse(struct key_preparsed_payload *prep); static int keyring_instantiate(struct key *keyring, struct key_preparsed_payload *prep); static void keyring_revoke(struct key *keyring); static void keyring_destroy(struct key *keyring); static void keyring_describe(const struct key *keyring, struct seq_file *m); static long keyring_read(const struct key *keyring, char __user *buffer, size_t buflen); struct key_type key_type_keyring = { .name = "keyring", .def_datalen = 0, .preparse = keyring_preparse, .free_preparse = keyring_free_preparse, .instantiate = keyring_instantiate, .match = user_match, .revoke = keyring_revoke, .destroy = keyring_destroy, .describe = keyring_describe, .read = keyring_read, }; EXPORT_SYMBOL(key_type_keyring); /* * Semaphore to serialise link/link calls to prevent two link calls in parallel * introducing a cycle. */ static DECLARE_RWSEM(keyring_serialise_link_sem); /* * Publish the name of a keyring so that it can be found by name (if it has * one). */ static void keyring_publish_name(struct key *keyring) { int bucket; if (keyring->description) { bucket = keyring_hash(keyring->description); write_lock(&keyring_name_lock); if (!keyring_name_hash[bucket].next) INIT_LIST_HEAD(&keyring_name_hash[bucket]); list_add_tail(&keyring->type_data.link, &keyring_name_hash[bucket]); write_unlock(&keyring_name_lock); } } /* * Preparse a keyring payload */ static int keyring_preparse(struct key_preparsed_payload *prep) { return prep->datalen != 0 ? -EINVAL : 0; } /* * Free a preparse of a user defined key payload */ static void keyring_free_preparse(struct key_preparsed_payload *prep) { } /* * Initialise a keyring. * * Returns 0 on success, -EINVAL if given any data. */ static int keyring_instantiate(struct key *keyring, struct key_preparsed_payload *prep) { assoc_array_init(&keyring->keys); /* make the keyring available by name if it has one */ keyring_publish_name(keyring); return 0; } /* * Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd * fold the carry back too, but that requires inline asm. */ static u64 mult_64x32_and_fold(u64 x, u32 y) { u64 hi = (u64)(u32)(x >> 32) * y; u64 lo = (u64)(u32)(x) * y; return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32); } /* * Hash a key type and description. */ static unsigned long hash_key_type_and_desc(const struct keyring_index_key *index_key) { const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP; const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK; const char *description = index_key->description; unsigned long hash, type; u32 piece; u64 acc; int n, desc_len = index_key->desc_len; type = (unsigned long)index_key->type; acc = mult_64x32_and_fold(type, desc_len + 13); acc = mult_64x32_and_fold(acc, 9207); for (;;) { n = desc_len; if (n <= 0) break; if (n > 4) n = 4; piece = 0; memcpy(&piece, description, n); description += n; desc_len -= n; acc = mult_64x32_and_fold(acc, piece); acc = mult_64x32_and_fold(acc, 9207); } /* Fold the hash down to 32 bits if need be. */ hash = acc; if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32) hash ^= acc >> 32; /* Squidge all the keyrings into a separate part of the tree to * ordinary keys by making sure the lowest level segment in the hash is * zero for keyrings and non-zero otherwise. */ if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0) return hash | (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1; if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0) return (hash + (hash << level_shift)) & ~fan_mask; return hash; } /* * Build the next index key chunk. * * On 32-bit systems the index key is laid out as: * * 0 4 5 9... * hash desclen typeptr desc[] * * On 64-bit systems: * * 0 8 9 17... * hash desclen typeptr desc[] * * We return it one word-sized chunk at a time. */ static unsigned long keyring_get_key_chunk(const void *data, int level) { const struct keyring_index_key *index_key = data; unsigned long chunk = 0; long offset = 0; int desc_len = index_key->desc_len, n = sizeof(chunk); level /= ASSOC_ARRAY_KEY_CHUNK_SIZE; switch (level) { case 0: return hash_key_type_and_desc(index_key); case 1: return ((unsigned long)index_key->type << 8) | desc_len; case 2: if (desc_len == 0) return (u8)((unsigned long)index_key->type >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - 8)); n--; offset = 1; default: offset += sizeof(chunk) - 1; offset += (level - 3) * sizeof(chunk); if (offset >= desc_len) return 0; desc_len -= offset; if (desc_len > n) desc_len = n; offset += desc_len; do { chunk <<= 8; chunk |= ((u8*)index_key->description)[--offset]; } while (--desc_len > 0); if (level == 2) { chunk <<= 8; chunk |= (u8)((unsigned long)index_key->type >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - 8)); } return chunk; } } static unsigned long keyring_get_object_key_chunk(const void *object, int level) { const struct key *key = keyring_ptr_to_key(object); return keyring_get_key_chunk(&key->index_key, level); } static bool keyring_compare_object(const void *object, const void *data) { const struct keyring_index_key *index_key = data; const struct key *key = keyring_ptr_to_key(object); return key->index_key.type == index_key->type && key->index_key.desc_len == index_key->desc_len && memcmp(key->index_key.description, index_key->description, index_key->desc_len) == 0; } /* * Compare the index keys of a pair of objects and determine the bit position * at which they differ - if they differ. */ static int keyring_diff_objects(const void *object, const void *data) { const struct key *key_a = keyring_ptr_to_key(object); const struct keyring_index_key *a = &key_a->index_key; const struct keyring_index_key *b = data; unsigned long seg_a, seg_b; int level, i; level = 0; seg_a = hash_key_type_and_desc(a); seg_b = hash_key_type_and_desc(b); if ((seg_a ^ seg_b) != 0) goto differ; /* The number of bits contributed by the hash is controlled by a * constant in the assoc_array headers. Everything else thereafter we * can deal with as being machine word-size dependent. */ level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8; seg_a = a->desc_len; seg_b = b->desc_len; if ((seg_a ^ seg_b) != 0) goto differ; /* The next bit may not work on big endian */ level++; seg_a = (unsigned long)a->type; seg_b = (unsigned long)b->type; if ((seg_a ^ seg_b) != 0) goto differ; level += sizeof(unsigned long); if (a->desc_len == 0) goto same; i = 0; if (((unsigned long)a->description | (unsigned long)b->description) & (sizeof(unsigned long) - 1)) { do { seg_a = *(unsigned long *)(a->description + i); seg_b = *(unsigned long *)(b->description + i); if ((seg_a ^ seg_b) != 0) goto differ_plus_i; i += sizeof(unsigned long); } while (i < (a->desc_len & (sizeof(unsigned long) - 1))); } for (; i < a->desc_len; i++) { seg_a = *(unsigned char *)(a->description + i); seg_b = *(unsigned char *)(b->description + i); if ((seg_a ^ seg_b) != 0) goto differ_plus_i; } same: return -1; differ_plus_i: level += i; differ: i = level * 8 + __ffs(seg_a ^ seg_b); return i; } /* * Free an object after stripping the keyring flag off of the pointer. */ static void keyring_free_object(void *object) { key_put(keyring_ptr_to_key(object)); } /* * Operations for keyring management by the index-tree routines. */ static const struct assoc_array_ops keyring_assoc_array_ops = { .get_key_chunk = keyring_get_key_chunk, .get_object_key_chunk = keyring_get_object_key_chunk, .compare_object = keyring_compare_object, .diff_objects = keyring_diff_objects, .free_object = keyring_free_object, }; /* * Clean up a keyring when it is destroyed. Unpublish its name if it had one * and dispose of its data. * * The garbage collector detects the final key_put(), removes the keyring from * the serial number tree and then does RCU synchronisation before coming here, * so we shouldn't need to worry about code poking around here with the RCU * readlock held by this time. */ static void keyring_destroy(struct key *keyring) { if (keyring->description) { write_lock(&keyring_name_lock); if (keyring->type_data.link.next != NULL && !list_empty(&keyring->type_data.link)) list_del(&keyring->type_data.link); write_unlock(&keyring_name_lock); } assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops); } /* * Describe a keyring for /proc. */ static void keyring_describe(const struct key *keyring, struct seq_file *m) { if (keyring->description) seq_puts(m, keyring->description); else seq_puts(m, "[anon]"); if (key_is_instantiated(keyring)) { if (keyring->keys.nr_leaves_on_tree != 0) seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree); else seq_puts(m, ": empty"); } } struct keyring_read_iterator_context { size_t qty; size_t count; key_serial_t __user *buffer; }; static int keyring_read_iterator(const void *object, void *data) { struct keyring_read_iterator_context *ctx = data; const struct key *key = keyring_ptr_to_key(object); int ret; kenter("{%s,%d},,{%zu/%zu}", key->type->name, key->serial, ctx->count, ctx->qty); if (ctx->count >= ctx->qty) return 1; ret = put_user(key->serial, ctx->buffer); if (ret < 0) return ret; ctx->buffer++; ctx->count += sizeof(key->serial); return 0; } /* * Read a list of key IDs from the keyring's contents in binary form * * The keyring's semaphore is read-locked by the caller. This prevents someone * from modifying it under us - which could cause us to read key IDs multiple * times. */ static long keyring_read(const struct key *keyring, char __user *buffer, size_t buflen) { struct keyring_read_iterator_context ctx; unsigned long nr_keys; int ret; kenter("{%d},,%zu", key_serial(keyring), buflen); if (buflen & (sizeof(key_serial_t) - 1)) return -EINVAL; nr_keys = keyring->keys.nr_leaves_on_tree; if (nr_keys == 0) return 0; /* Calculate how much data we could return */ ctx.qty = nr_keys * sizeof(key_serial_t); if (!buffer || !buflen) return ctx.qty; if (buflen > ctx.qty) ctx.qty = buflen; /* Copy the IDs of the subscribed keys into the buffer */ ctx.buffer = (key_serial_t __user *)buffer; ctx.count = 0; ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx); if (ret < 0) { kleave(" = %d [iterate]", ret); return ret; } kleave(" = %zu [ok]", ctx.count); return ctx.count; } /* * Allocate a keyring and link into the destination keyring. */ struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key *dest) { struct key *keyring; int ret; keyring = key_alloc(&key_type_keyring, description, uid, gid, cred, perm, flags); if (!IS_ERR(keyring)) { ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL); if (ret < 0) { key_put(keyring); keyring = ERR_PTR(ret); } } return keyring; } EXPORT_SYMBOL(keyring_alloc); /* * Iteration function to consider each key found. */ static int keyring_search_iterator(const void *object, void *iterator_data) { struct keyring_search_context *ctx = iterator_data; const struct key *key = keyring_ptr_to_key(object); unsigned long kflags = key->flags; kenter("{%d}", key->serial); /* ignore keys not of this type */ if (key->type != ctx->index_key.type) { kleave(" = 0 [!type]"); return 0; } /* skip invalidated, revoked and expired keys */ if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { if (kflags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED))) { ctx->result = ERR_PTR(-EKEYREVOKED); kleave(" = %d [invrev]", ctx->skipped_ret); goto skipped; } if (key->expiry && ctx->now.tv_sec >= key->expiry) { ctx->result = ERR_PTR(-EKEYEXPIRED); kleave(" = %d [expire]", ctx->skipped_ret); goto skipped; } } /* keys that don't match */ if (!ctx->match_data.cmp(key, &ctx->match_data)) { kleave(" = 0 [!match]"); return 0; } /* key must have search permissions */ if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) && key_task_permission(make_key_ref(key, ctx->possessed), ctx->cred, KEY_NEED_SEARCH) < 0) { ctx->result = ERR_PTR(-EACCES); kleave(" = %d [!perm]", ctx->skipped_ret); goto skipped; } if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { /* we set a different error code if we pass a negative key */ if (kflags & (1 << KEY_FLAG_NEGATIVE)) { smp_rmb(); ctx->result = ERR_PTR(key->type_data.reject_error); kleave(" = %d [neg]", ctx->skipped_ret); goto skipped; } } /* Found */ ctx->result = make_key_ref(key, ctx->possessed); kleave(" = 1 [found]"); return 1; skipped: return ctx->skipped_ret; } /* * Search inside a keyring for a key. We can search by walking to it * directly based on its index-key or we can iterate over the entire * tree looking for it, based on the match function. */ static int search_keyring(struct key *keyring, struct keyring_search_context *ctx) { if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) { const void *object; object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops, &ctx->index_key); return object ? ctx->iterator(object, ctx) : 0; } return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx); } /* * Search a tree of keyrings that point to other keyrings up to the maximum * depth. */ static bool search_nested_keyrings(struct key *keyring, struct keyring_search_context *ctx) { struct { struct key *keyring; struct assoc_array_node *node; int slot; } stack[KEYRING_SEARCH_MAX_DEPTH]; struct assoc_array_shortcut *shortcut; struct assoc_array_node *node; struct assoc_array_ptr *ptr; struct key *key; int sp = 0, slot; kenter("{%d},{%s,%s}", keyring->serial, ctx->index_key.type->name, ctx->index_key.description); if (ctx->index_key.description) ctx->index_key.desc_len = strlen(ctx->index_key.description); /* Check to see if this top-level keyring is what we are looking for * and whether it is valid or not. */ if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE || keyring_compare_object(keyring, &ctx->index_key)) { ctx->skipped_ret = 2; ctx->flags |= KEYRING_SEARCH_DO_STATE_CHECK; switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) { case 1: goto found; case 2: return false; default: break; } } ctx->skipped_ret = 0; if (ctx->flags & KEYRING_SEARCH_NO_STATE_CHECK) ctx->flags &= ~KEYRING_SEARCH_DO_STATE_CHECK; /* Start processing a new keyring */ descend_to_keyring: kdebug("descend to %d", keyring->serial); if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED))) goto not_this_keyring; /* Search through the keys in this keyring before its searching its * subtrees. */ if (search_keyring(keyring, ctx)) goto found; /* Then manually iterate through the keyrings nested in this one. * * Start from the root node of the index tree. Because of the way the * hash function has been set up, keyrings cluster on the leftmost * branch of the root node (root slot 0) or in the root node itself. * Non-keyrings avoid the leftmost branch of the root entirely (root * slots 1-15). */ ptr = ACCESS_ONCE(keyring->keys.root); if (!ptr) goto not_this_keyring; if (assoc_array_ptr_is_shortcut(ptr)) { /* If the root is a shortcut, either the keyring only contains * keyring pointers (everything clusters behind root slot 0) or * doesn't contain any keyring pointers. */ shortcut = assoc_array_ptr_to_shortcut(ptr); smp_read_barrier_depends(); if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0) goto not_this_keyring; ptr = ACCESS_ONCE(shortcut->next_node); node = assoc_array_ptr_to_node(ptr); goto begin_node; } node = assoc_array_ptr_to_node(ptr); smp_read_barrier_depends(); ptr = node->slots[0]; if (!assoc_array_ptr_is_meta(ptr)) goto begin_node; descend_to_node: /* Descend to a more distal node in this keyring's content tree and go * through that. */ kdebug("descend"); if (assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); smp_read_barrier_depends(); ptr = ACCESS_ONCE(shortcut->next_node); BUG_ON(!assoc_array_ptr_is_node(ptr)); } node = assoc_array_ptr_to_node(ptr); begin_node: kdebug("begin_node"); smp_read_barrier_depends(); slot = 0; ascend_to_node: /* Go through the slots in a node */ for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { ptr = ACCESS_ONCE(node->slots[slot]); if (assoc_array_ptr_is_meta(ptr) && node->back_pointer) goto descend_to_node; if (!keyring_ptr_is_keyring(ptr)) continue; key = keyring_ptr_to_key(ptr); if (sp >= KEYRING_SEARCH_MAX_DEPTH) { if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) { ctx->result = ERR_PTR(-ELOOP); return false; } goto not_this_keyring; } /* Search a nested keyring */ if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) && key_task_permission(make_key_ref(key, ctx->possessed), ctx->cred, KEY_NEED_SEARCH) < 0) continue; /* stack the current position */ stack[sp].keyring = keyring; stack[sp].node = node; stack[sp].slot = slot; sp++; /* begin again with the new keyring */ keyring = key; goto descend_to_keyring; } /* We've dealt with all the slots in the current node, so now we need * to ascend to the parent and continue processing there. */ ptr = ACCESS_ONCE(node->back_pointer); slot = node->parent_slot; if (ptr && assoc_array_ptr_is_shortcut(ptr)) { shortcut = assoc_array_ptr_to_shortcut(ptr); smp_read_barrier_depends(); ptr = ACCESS_ONCE(shortcut->back_pointer); slot = shortcut->parent_slot; } if (!ptr) goto not_this_keyring; node = assoc_array_ptr_to_node(ptr); smp_read_barrier_depends(); slot++; /* If we've ascended to the root (zero backpointer), we must have just * finished processing the leftmost branch rather than the root slots - * so there can't be any more keyrings for us to find. */ if (node->back_pointer) { kdebug("ascend %d", slot); goto ascend_to_node; } /* The keyring we're looking at was disqualified or didn't contain a * matching key. */ not_this_keyring: kdebug("not_this_keyring %d", sp); if (sp <= 0) { kleave(" = false"); return false; } /* Resume the processing of a keyring higher up in the tree */ sp--; keyring = stack[sp].keyring; node = stack[sp].node; slot = stack[sp].slot + 1; kdebug("ascend to %d [%d]", keyring->serial, slot); goto ascend_to_node; /* We found a viable match */ found: key = key_ref_to_ptr(ctx->result); key_check(key); if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) { key->last_used_at = ctx->now.tv_sec; keyring->last_used_at = ctx->now.tv_sec; while (sp > 0) stack[--sp].keyring->last_used_at = ctx->now.tv_sec; } kleave(" = true"); return true; } /** * keyring_search_aux - Search a keyring tree for a key matching some criteria * @keyring_ref: A pointer to the keyring with possession indicator. * @ctx: The keyring search context. * * Search the supplied keyring tree for a key that matches the criteria given. * The root keyring and any linked keyrings must grant Search permission to the * caller to be searchable and keys can only be found if they too grant Search * to the caller. The possession flag on the root keyring pointer controls use * of the possessor bits in permissions checking of the entire tree. In * addition, the LSM gets to forbid keyring searches and key matches. * * The search is performed as a breadth-then-depth search up to the prescribed * limit (KEYRING_SEARCH_MAX_DEPTH). * * Keys are matched to the type provided and are then filtered by the match * function, which is given the description to use in any way it sees fit. The * match function may use any attributes of a key that it wishes to to * determine the match. Normally the match function from the key type would be * used. * * RCU can be used to prevent the keyring key lists from disappearing without * the need to take lots of locks. * * Returns a pointer to the found key and increments the key usage count if * successful; -EAGAIN if no matching keys were found, or if expired or revoked * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the * specified keyring wasn't a keyring. * * In the case of a successful return, the possession attribute from * @keyring_ref is propagated to the returned key reference. */ key_ref_t keyring_search_aux(key_ref_t keyring_ref, struct keyring_search_context *ctx) { struct key *keyring; long err; ctx->iterator = keyring_search_iterator; ctx->possessed = is_key_possessed(keyring_ref); ctx->result = ERR_PTR(-EAGAIN); keyring = key_ref_to_ptr(keyring_ref); key_check(keyring); if (keyring->type != &key_type_keyring) return ERR_PTR(-ENOTDIR); if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) { err = key_task_permission(keyring_ref, ctx->cred, KEY_NEED_SEARCH); if (err < 0) return ERR_PTR(err); } rcu_read_lock(); ctx->now = current_kernel_time(); if (search_nested_keyrings(keyring, ctx)) __key_get(key_ref_to_ptr(ctx->result)); rcu_read_unlock(); return ctx->result; } /** * keyring_search - Search the supplied keyring tree for a matching key * @keyring: The root of the keyring tree to be searched. * @type: The type of keyring we want to find. * @description: The name of the keyring we want to find. * * As keyring_search_aux() above, but using the current task's credentials and * type's default matching function and preferred search method. */ key_ref_t keyring_search(key_ref_t keyring, struct key_type *type, const char *description) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; int ret; if (!ctx.match_data.cmp) return ERR_PTR(-ENOKEY); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) return ERR_PTR(ret); } key = keyring_search_aux(keyring, &ctx); if (type->match_free) type->match_free(&ctx.match_data); return key; } EXPORT_SYMBOL(keyring_search); /* * Search the given keyring for a key that might be updated. * * The caller must guarantee that the keyring is a keyring and that the * permission is granted to modify the keyring as no check is made here. The * caller must also hold a lock on the keyring semaphore. * * Returns a pointer to the found key with usage count incremented if * successful and returns NULL if not found. Revoked and invalidated keys are * skipped over. * * If successful, the possession indicator is propagated from the keyring ref * to the returned key reference. */ key_ref_t find_key_to_update(key_ref_t keyring_ref, const struct keyring_index_key *index_key) { struct key *keyring, *key; const void *object; keyring = key_ref_to_ptr(keyring_ref); kenter("{%d},{%s,%s}", keyring->serial, index_key->type->name, index_key->description); object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops, index_key); if (object) goto found; kleave(" = NULL"); return NULL; found: key = keyring_ptr_to_key(object); if (key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED))) { kleave(" = NULL [x]"); return NULL; } __key_get(key); kleave(" = {%d}", key->serial); return make_key_ref(key, is_key_possessed(keyring_ref)); } /* * Find a keyring with the specified name. * * All named keyrings in the current user namespace are searched, provided they * grant Search permission directly to the caller (unless this check is * skipped). Keyrings whose usage points have reached zero or who have been * revoked are skipped. * * Returns a pointer to the keyring with the keyring's refcount having being * incremented on success. -ENOKEY is returned if a key could not be found. */ struct key *find_keyring_by_name(const char *name, bool skip_perm_check) { struct key *keyring; int bucket; if (!name) return ERR_PTR(-EINVAL); bucket = keyring_hash(name); read_lock(&keyring_name_lock); if (keyring_name_hash[bucket].next) { /* search this hash bucket for a keyring with a matching name * that's readable and that hasn't been revoked */ list_for_each_entry(keyring, &keyring_name_hash[bucket], type_data.link ) { if (!kuid_has_mapping(current_user_ns(), keyring->user->uid)) continue; if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) continue; if (strcmp(keyring->description, name) != 0) continue; if (!skip_perm_check && key_permission(make_key_ref(keyring, 0), KEY_NEED_SEARCH) < 0) continue; /* we've got a match but we might end up racing with * key_cleanup() if the keyring is currently 'dead' * (ie. it has a zero usage count) */ if (!atomic_inc_not_zero(&keyring->usage)) continue; keyring->last_used_at = current_kernel_time().tv_sec; goto out; } } keyring = ERR_PTR(-ENOKEY); out: read_unlock(&keyring_name_lock); return keyring; } static int keyring_detect_cycle_iterator(const void *object, void *iterator_data) { struct keyring_search_context *ctx = iterator_data; const struct key *key = keyring_ptr_to_key(object); kenter("{%d}", key->serial); /* We might get a keyring with matching index-key that is nonetheless a * different keyring. */ if (key != ctx->match_data.raw_data) return 0; ctx->result = ERR_PTR(-EDEADLK); return 1; } /* * See if a cycle will will be created by inserting acyclic tree B in acyclic * tree A at the topmost level (ie: as a direct child of A). * * Since we are adding B to A at the top level, checking for cycles should just * be a matter of seeing if node A is somewhere in tree B. */ static int keyring_detect_cycle(struct key *A, struct key *B) { struct keyring_search_context ctx = { .index_key = A->index_key, .match_data.raw_data = A, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .iterator = keyring_detect_cycle_iterator, .flags = (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_NO_UPDATE_TIME | KEYRING_SEARCH_NO_CHECK_PERM | KEYRING_SEARCH_DETECT_TOO_DEEP), }; rcu_read_lock(); search_nested_keyrings(B, &ctx); rcu_read_unlock(); return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result); } /* * Preallocate memory so that a key can be linked into to a keyring. */ int __key_link_begin(struct key *keyring, const struct keyring_index_key *index_key, struct assoc_array_edit **_edit) __acquires(&keyring->sem) __acquires(&keyring_serialise_link_sem) { struct assoc_array_edit *edit; int ret; kenter("%d,%s,%s,", keyring->serial, index_key->type->name, index_key->description); BUG_ON(index_key->desc_len == 0); if (keyring->type != &key_type_keyring) return -ENOTDIR; down_write(&keyring->sem); ret = -EKEYREVOKED; if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) goto error_krsem; /* serialise link/link calls to prevent parallel calls causing a cycle * when linking two keyring in opposite orders */ if (index_key->type == &key_type_keyring) down_write(&keyring_serialise_link_sem); /* Create an edit script that will insert/replace the key in the * keyring tree. */ edit = assoc_array_insert(&keyring->keys, &keyring_assoc_array_ops, index_key, NULL); if (IS_ERR(edit)) { ret = PTR_ERR(edit); goto error_sem; } /* If we're not replacing a link in-place then we're going to need some * extra quota. */ if (!edit->dead_leaf) { ret = key_payload_reserve(keyring, keyring->datalen + KEYQUOTA_LINK_BYTES); if (ret < 0) goto error_cancel; } *_edit = edit; kleave(" = 0"); return 0; error_cancel: assoc_array_cancel_edit(edit); error_sem: if (index_key->type == &key_type_keyring) up_write(&keyring_serialise_link_sem); error_krsem: up_write(&keyring->sem); kleave(" = %d", ret); return ret; } /* * Check already instantiated keys aren't going to be a problem. * * The caller must have called __key_link_begin(). Don't need to call this for * keys that were created since __key_link_begin() was called. */ int __key_link_check_live_key(struct key *keyring, struct key *key) { if (key->type == &key_type_keyring) /* check that we aren't going to create a cycle by linking one * keyring to another */ return keyring_detect_cycle(keyring, key); return 0; } /* * Link a key into to a keyring. * * Must be called with __key_link_begin() having being called. Discards any * already extant link to matching key if there is one, so that each keyring * holds at most one link to any given key of a particular type+description * combination. */ void __key_link(struct key *key, struct assoc_array_edit **_edit) { __key_get(key); assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key)); assoc_array_apply_edit(*_edit); *_edit = NULL; } /* * Finish linking a key into to a keyring. * * Must be called with __key_link_begin() having being called. */ void __key_link_end(struct key *keyring, const struct keyring_index_key *index_key, struct assoc_array_edit *edit) __releases(&keyring->sem) __releases(&keyring_serialise_link_sem) { BUG_ON(index_key->type == NULL); kenter("%d,%s,", keyring->serial, index_key->type->name); if (index_key->type == &key_type_keyring) up_write(&keyring_serialise_link_sem); if (edit && !edit->dead_leaf) { key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES); assoc_array_cancel_edit(edit); } up_write(&keyring->sem); } /** * key_link - Link a key to a keyring * @keyring: The keyring to make the link in. * @key: The key to link to. * * Make a link in a keyring to a key, such that the keyring holds a reference * on that key and the key can potentially be found by searching that keyring. * * This function will write-lock the keyring's semaphore and will consume some * of the user's key data quota to hold the link. * * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is * full, -EDQUOT if there is insufficient key data quota remaining to add * another link or -ENOMEM if there's insufficient memory. * * It is assumed that the caller has checked that it is permitted for a link to * be made (the keyring should have Write permission and the key Link * permission). */ int key_link(struct key *keyring, struct key *key) { struct assoc_array_edit *edit; int ret; kenter("{%d,%d}", keyring->serial, atomic_read(&keyring->usage)); key_check(keyring); key_check(key); if (test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags) && !test_bit(KEY_FLAG_TRUSTED, &key->flags)) return -EPERM; ret = __key_link_begin(keyring, &key->index_key, &edit); if (ret == 0) { kdebug("begun {%d,%d}", keyring->serial, atomic_read(&keyring->usage)); ret = __key_link_check_live_key(keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(keyring, &key->index_key, edit); } kleave(" = %d {%d,%d}", ret, keyring->serial, atomic_read(&keyring->usage)); return ret; } EXPORT_SYMBOL(key_link); /** * key_unlink - Unlink the first link to a key from a keyring. * @keyring: The keyring to remove the link from. * @key: The key the link is to. * * Remove a link from a keyring to a key. * * This function will write-lock the keyring's semaphore. * * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if * the key isn't linked to by the keyring or -ENOMEM if there's insufficient * memory. * * It is assumed that the caller has checked that it is permitted for a link to * be removed (the keyring should have Write permission; no permissions are * required on the key). */ int key_unlink(struct key *keyring, struct key *key) { struct assoc_array_edit *edit; int ret; key_check(keyring); key_check(key); if (keyring->type != &key_type_keyring) return -ENOTDIR; down_write(&keyring->sem); edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops, &key->index_key); if (IS_ERR(edit)) { ret = PTR_ERR(edit); goto error; } ret = -ENOENT; if (edit == NULL) goto error; assoc_array_apply_edit(edit); key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES); ret = 0; error: up_write(&keyring->sem); return ret; } EXPORT_SYMBOL(key_unlink); /** * keyring_clear - Clear a keyring * @keyring: The keyring to clear. * * Clear the contents of the specified keyring. * * Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring. */ int keyring_clear(struct key *keyring) { struct assoc_array_edit *edit; int ret; if (keyring->type != &key_type_keyring) return -ENOTDIR; down_write(&keyring->sem); edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops); if (IS_ERR(edit)) { ret = PTR_ERR(edit); } else { if (edit) assoc_array_apply_edit(edit); key_payload_reserve(keyring, 0); ret = 0; } up_write(&keyring->sem); return ret; } EXPORT_SYMBOL(keyring_clear); /* * Dispose of the links from a revoked keyring. * * This is called with the key sem write-locked. */ static void keyring_revoke(struct key *keyring) { struct assoc_array_edit *edit; edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops); if (!IS_ERR(edit)) { if (edit) assoc_array_apply_edit(edit); key_payload_reserve(keyring, 0); } } static bool keyring_gc_select_iterator(void *object, void *iterator_data) { struct key *key = keyring_ptr_to_key(object); time_t *limit = iterator_data; if (key_is_dead(key, *limit)) return false; key_get(key); return true; } static int keyring_gc_check_iterator(const void *object, void *iterator_data) { const struct key *key = keyring_ptr_to_key(object); time_t *limit = iterator_data; key_check(key); return key_is_dead(key, *limit); } /* * Garbage collect pointers from a keyring. * * Not called with any locks held. The keyring's key struct will not be * deallocated under us as only our caller may deallocate it. */ void keyring_gc(struct key *keyring, time_t limit) { int result; kenter("%x{%s}", keyring->serial, keyring->description ?: ""); if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED))) goto dont_gc; /* scan the keyring looking for dead keys */ rcu_read_lock(); result = assoc_array_iterate(&keyring->keys, keyring_gc_check_iterator, &limit); rcu_read_unlock(); if (result == true) goto do_gc; dont_gc: kleave(" [no gc]"); return; do_gc: down_write(&keyring->sem); assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops, keyring_gc_select_iterator, &limit); up_write(&keyring->sem); kleave(" [gc]"); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3060_14
crossvul-cpp_data_good_3194_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % 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/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.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/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; break; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image, ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(option) == MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=MagickTrue; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length-16)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); SetPixelRGBO(q,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(indexes+x))); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels == 1 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelGreen(q,pixel); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels, const size_t row,const ssize_t type,const unsigned char *pixels, ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { mask->matte=MagickFalse; channel_image=mask; } } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->matte=MagickTrue; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } (void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image* image,const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == 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); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties 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 RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,&image->exception) != MagickFalse) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBLong(image,mask->rows+mask->page.y); size+=WriteBlobMSBLong(image,mask->columns+mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_3194_0
crossvul-cpp_data_bad_3164_1
/* radare - LGPL - Copyright 2011-2016 - pancake */ #include <r_cons.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_bin.h> #include "dex/dex.h" #define r_hash_adler32 __adler32 #include "../../hash/adler32.c" extern struct r_bin_dbginfo_t r_bin_dbginfo_dex; #define DEBUG_PRINTF 0 #if DEBUG_PRINTF #define dprintf eprintf #else #define dprintf if (0)eprintf #endif static bool dexdump = false; static Sdb *mdb = NULL; static Sdb *cdb = NULL; // TODO: remove if it is not used static char *getstr(RBinDexObj *bin, int idx) { ut8 buf[6]; ut64 len; int uleblen; if (!bin || idx < 0 || idx >= bin->header.strings_size || !bin->strings) { return NULL; } if (bin->strings[idx] >= bin->size) { return NULL; } if (r_buf_read_at (bin->b, bin->strings[idx], buf, sizeof (buf)) < 1) { return NULL; } uleblen = r_uleb128 (buf, sizeof (buf), &len) - buf; if (!uleblen || uleblen >= bin->size) { return NULL; } if (!len || len >= bin->size) { return NULL; } // TODO: improve this ugly fix char c = 'a'; while (c) { ut64 offset = bin->strings[idx] + uleblen + len; if (offset >= bin->size || offset < len) { return NULL; } r_buf_read_at (bin->b, offset, (ut8*)&c, 1); len++; } if ((int)len > 0 && len < R_BIN_SIZEOF_STRINGS) { char *str = calloc (1, len + 1); if (str) { r_buf_read_at (bin->b, (bin->strings[idx]) + uleblen, (ut8 *)str, len); str[len] = 0; return str; } } return NULL; } static int countOnes(ut32 val) { int count = 0; val = val - ((val >> 1) & 0x55555555); val = (val & 0x33333333) + ((val >> 2) & 0x33333333); count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; return count; } typedef enum { kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX } AccessFor; static char *createAccessFlagStr(ut32 flags, AccessFor forWhat) { #define NUM_FLAGS 18 static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = { { /* class, inner class */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "?", /* 0x0040 */ "?", /* 0x0080 */ "?", /* 0x0100 */ "INTERFACE", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "ANNOTATION", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "VERIFIED", /* 0x10000 */ "OPTIMIZED", /* 0x20000 */ }, { /* method */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "SYNCHRONIZED", /* 0x0020 */ "BRIDGE", /* 0x0040 */ "VARARGS", /* 0x0080 */ "NATIVE", /* 0x0100 */ "?", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "STRICT", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "?", /* 0x4000 */ "MIRANDA", /* 0x8000 */ "CONSTRUCTOR", /* 0x10000 */ "DECLARED_SYNCHRONIZED", /* 0x20000 */ }, { /* field */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "VOLATILE", /* 0x0040 */ "TRANSIENT", /* 0x0080 */ "?", /* 0x0100 */ "?", /* 0x0200 */ "?", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "?", /* 0x10000 */ "?", /* 0x20000 */ }, }; const int kLongest = 21; int i, count; char* str; char* cp; count = countOnes(flags); // XXX check if this allocation is safe what if all the arithmetic // produces a huge number???? cp = str = (char*) malloc (count * (kLongest + 1) + 1); for (i = 0; i < NUM_FLAGS; i++) { if (flags & 0x01) { const char* accessStr = kAccessStrings[forWhat][i]; int len = strlen(accessStr); if (cp != str) { *cp++ = ' '; } memcpy(cp, accessStr, len); cp += len; } flags >>= 1; } *cp = '\0'; return str; } static char *dex_type_descriptor(RBinDexObj *bin, int type_idx) { if (type_idx < 0 || type_idx >= bin->header.types_size) { return NULL; } return getstr (bin, bin->types[type_idx].descriptor_id); } static char *dex_method_signature(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, type_id, list_size; char *r, *return_type = NULL, *signature = NULL, *buff = NULL; ut8 *bufptr; ut16 type_idx; int pos = 0, i, size = 1; if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { return NULL; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { return NULL; } type_id = bin->protos[proto_id].return_type_id; if (type_id >= bin->header.types_size ) { return NULL; } return_type = getstr (bin, bin->types[type_id].descriptor_id); if (!return_type) { return NULL; } if (!params_off) { return r_str_newf ("()%s", return_type);; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX again list_size is user controlled huge loop for (i = 0; i < list_size; i++) { int buff_len = 0; if (params_off + 4 + (i * 2) >= bin->size) { break; } type_idx = r_read_le16 (bufptr + params_off + 4 + (i * 2)); if (type_idx < 0 || type_idx >= bin->header.types_size || type_idx >= bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } buff_len = strlen (buff); size += buff_len + 1; signature = realloc (signature, size); strcpy (signature + pos, buff); pos += buff_len; signature[pos] = '\0'; } r = r_str_newf ("(%s)%s", signature, return_type); free (buff); free (signature); return r; } static RList *dex_method_signature2(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, list_size; char *buff = NULL; ut8 *bufptr; ut16 type_idx; int i; RList *params = r_list_newf (free); if (!params) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { goto out_error; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { goto out_error; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { goto out_error; } if (!params_off) { return params; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX list_size tainted it may produce huge loop for (i = 0; i < list_size; i++) { ut64 of = params_off + 4 + (i * 2); if (of >= bin->size || of < params_off) { break; } type_idx = r_read_le16 (bufptr + of); if (type_idx >= bin->header.types_size || type_idx > bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } r_list_append (params, buff); } return params; out_error: r_list_free (params); return NULL; } // TODO: fix this, now has more registers that it should // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L312 // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L141 static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg >= regsz) { //return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); } static int check (RBinFile *arch); static int check_bytes (const ut8 *buf, ut64 length); static Sdb *get_sdb (RBinObject *o) { if (!o || !o->bin_obj) { return NULL; } struct r_bin_dex_obj_t *bin = (struct r_bin_dex_obj_t *) o->bin_obj; if (bin->kv) { return bin->kv; } return NULL; } static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb){ void *res = NULL; RBuffer *tbuf = NULL; if (!buf || !sz || sz == UT64_MAX) { return NULL; } tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); res = r_bin_dex_new_buf (tbuf); r_buf_free (tbuf); return res; } static int load(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; if (!arch || !arch->o) { return false; } arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb); return arch->o->bin_obj ? true: false; } static ut64 baddr(RBinFile *arch) { return 0; } static int check(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; return check_bytes (bytes, sz); } static int check_bytes(const ut8 *buf, ut64 length) { if (!buf || length < 8) { return false; } // Non-extended opcode dex file if (!memcmp (buf, "dex\n035\0", 8)) { return true; } // Extended (jumnbo) opcode dex file, ICS+ only (sdk level 14+) if (!memcmp (buf, "dex\n036\0", 8)) { return true; } // M3 (Nov-Dec 07) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // M5 (Feb-Mar 08) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // Default fall through, should still be a dex file if (!memcmp (buf, "dex\n", 4)) { return true; } return false; } static RBinInfo *info(RBinFile *arch) { RBinHash *h; RBinInfo *ret = R_NEW0 (RBinInfo); if (!ret) { return NULL; } ret->file = arch->file? strdup (arch->file): NULL; ret->type = strdup ("DEX CLASS"); ret->has_va = false; ret->bclass = r_bin_dex_get_version (arch->o->bin_obj); ret->rclass = strdup ("class"); ret->os = strdup ("linux"); ret->subsystem = strdup ("any"); ret->machine = strdup ("Dalvik VM"); h = &ret->sum[0]; h->type = "sha1"; h->len = 20; h->addr = 12; h->from = 12; h->to = arch->buf->length-32; memcpy (h->buf, arch->buf->buf+12, 20); h = &ret->sum[1]; h->type = "adler32"; h->len = 4; h->addr = 0x8; h->from = 12; h->to = arch->buf->length-h->from; h = &ret->sum[2]; h->type = 0; memcpy (h->buf, arch->buf->buf + 8, 4); { ut32 *fc = (ut32 *)(arch->buf->buf + 8); ut32 cc = __adler32 (arch->buf->buf + 12, arch->buf->length - 12); if (*fc != cc) { eprintf ("# adler32 checksum doesn't match. Type this to fix it:\n"); eprintf ("wx `#sha1 $s-32 @32` @12 ; wx `#adler32 $s-12 @12` @8\n"); } } ret->arch = strdup ("dalvik"); ret->lang = "dalvik"; ret->bits = 32; ret->big_endian = 0; ret->dbg_info = 0; //1 | 4 | 8; /* Stripped | LineNums | Syms */ return ret; } static RList *strings(RBinFile *arch) { struct r_bin_dex_obj_t *bin = NULL; RBinString *ptr = NULL; RList *ret = NULL; int i, len; ut8 buf[6]; ut64 off; if (!arch || !arch->o) { return NULL; } bin = (struct r_bin_dex_obj_t *) arch->o->bin_obj; if (!bin || !bin->strings) { return NULL; } if (bin->header.strings_size > bin->size) { bin->strings = NULL; return NULL; } if (!(ret = r_list_newf (free))) { return NULL; } for (i = 0; i < bin->header.strings_size; i++) { if (!(ptr = R_NEW0 (RBinString))) { break; } if (bin->strings[i] > bin->size || bin->strings[i] + 6 > bin->size) { goto out_error; } r_buf_read_at (bin->b, bin->strings[i], (ut8*)&buf, 6); len = dex_read_uleb128 (buf); if (len > 1 && len < R_BIN_SIZEOF_STRINGS) { ptr->string = malloc (len + 1); if (!ptr->string) { goto out_error; } off = bin->strings[i] + dex_uleb128_len (buf); if (off + len >= bin->size || off + len < len) { free (ptr->string); goto out_error; } r_buf_read_at (bin->b, off, (ut8*)ptr->string, len); ptr->string[len] = 0; ptr->vaddr = ptr->paddr = bin->strings[i]; ptr->size = len; ptr->length = len; ptr->ordinal = i+1; r_list_append (ret, ptr); } else { free (ptr); } } return ret; out_error: r_list_free (ret); free (ptr); return NULL; } static char *dex_method_name(RBinDexObj *bin, int idx) { if (idx < 0 || idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[idx].class_id; if (cid < 0 || cid >= bin->header.strings_size) { return NULL; } int tid = bin->methods[idx].name_id; if (tid < 0 || tid >= bin->header.strings_size) { return NULL; } return getstr (bin, tid); } static char *dex_class_name_byid(RBinDexObj *bin, int cid) { int tid; if (!bin || !bin->types) { return NULL; } if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) { return dex_class_name_byid (bin, c->class_id); } static char *dex_field_name(RBinDexObj *bin, int fid) { int cid, tid, type_id; if (!bin || !bin->fields) { return NULL; } if (fid < 0 || fid >= bin->header.fields_size) { return NULL; } cid = bin->fields[fid].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } type_id = bin->fields[fid].type_id; if (type_id < 0 || type_id >= bin->header.types_size) { return NULL; } tid = bin->fields[fid].name_id; return r_str_newf ("%s->%s %s", getstr (bin, bin->types[cid].descriptor_id), getstr (bin, tid), getstr (bin, bin->types[type_id].descriptor_id)); } static char *dex_method_fullname(RBinDexObj *bin, int method_idx) { if (!bin || !bin->types) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[method_idx].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } char *name = dex_method_name (bin, method_idx); char *class_name = dex_class_name_byid (bin, cid); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func char *signature = dex_method_signature (bin, method_idx); char *flagname = r_str_newf ("%s.%s%s", class_name, name, signature); free (name); free (class_name); free (signature); return flagname; } static ut64 dex_get_type_offset(RBinFile *arch, int type_idx) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin || !bin->types) { return 0; } if (type_idx < 0 || type_idx >= bin->header.types_size) { return 0; } return bin->header.types_offset + type_idx * 0x04; //&bin->types[type_idx]; } static void __r_bin_class_free(RBinClass *p) { r_list_free (p->methods); r_list_free (p->fields); r_bin_class_free (p); } static char *dex_class_super_name(RBinDexObj *bin, RBinDexClass *c) { int cid, tid; if (!bin || !c || !bin->types) { return NULL; } cid = c->super_class; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static const ut8 *parse_dex_class_fields(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 fields_count, bool is_sfield) { struct r_bin_t *rbin = binfile->rbin; ut64 lastIndex = 0; ut8 ff[sizeof (DexField)] = {0}; int total, i, tid; DexField field; const char* type_str; for (i = 0; i < fields_count; i++) { ut64 fieldIndex, accessFlags; p = r_uleb128 (p, p_end - p, &fieldIndex); // fieldIndex p = r_uleb128 (p, p_end - p, &accessFlags); // accessFlags fieldIndex += lastIndex; total = bin->header.fields_offset + (sizeof (DexField) * fieldIndex); if (total >= bin->size || total < bin->header.fields_offset) { break; } if (r_buf_read_at (binfile->buf, total, ff, sizeof (DexField)) != sizeof (DexField)) { break; } field.class_id = r_read_le16 (ff); field.type_id = r_read_le16 (ff + 2); field.name_id = r_read_le32 (ff + 4); char *fieldName = getstr (bin, field.name_id); if (field.type_id >= bin->header.types_size) { break; } tid = bin->types[field.type_id].descriptor_id; type_str = getstr (bin, tid); RBinSymbol *sym = R_NEW0 (RBinSymbol); if (is_sfield) { sym->name = r_str_newf ("%s.sfield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("STATIC"); } else { sym->name = r_str_newf ("%s.ifield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("FIELD"); } sym->name = r_str_replace (sym->name, "method.", "", 0); //sym->name = r_str_replace (sym->name, ";", "", 0); sym->paddr = sym->vaddr = total; sym->ordinal = (*sym_count)++; if (dexdump) { const char *accessStr = createAccessFlagStr ( accessFlags, kAccessForField); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", fieldName); rbin->cb_printf (" type : '%s'\n", type_str); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)accessFlags, accessStr); } r_list_append (bin->methods_list, sym); r_list_append (cls->fields, sym); lastIndex = fieldIndex; } return p; } // TODO: refactor this method // XXX it needs a lot of love!!! static const ut8 *parse_dex_class_method(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 DM, int *methods, bool is_direct) { struct r_bin_t *rbin = binfile->rbin; ut8 ff2[16] = {0}; ut8 ff3[8] = {0}; int i; ut64 omi = 0; bool catchAll; ut16 regsz, ins_size, outs_size, tries_size; ut16 handler_off, start_addr, insn_count; ut32 debug_info_off, insns_size; const ut8 *encoded_method_addr; for (i = 0; i < DM; i++) { encoded_method_addr = p; char *method_name, *flag_name; ut64 MI, MA, MC; p = r_uleb128 (p, p_end - p, &MI); MI += omi; omi = MI; p = r_uleb128 (p, p_end - p, &MA); p = r_uleb128 (p, p_end - p, &MC); // TODO: MOVE CHECKS OUTSIDE! if (MI < bin->header.method_size) { if (methods) { methods[MI] = 1; } } method_name = dex_method_name (bin, MI); char *signature = dex_method_signature (bin, MI); if (!method_name) { method_name = strdup ("unknown"); } flag_name = r_str_newf ("%s.method.%s%s", cls->name, method_name, signature); if (!flag_name) { R_FREE (method_name); R_FREE (signature); continue; } // TODO: check size // ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; ut64 v2, handler_type, handler_addr; int t; if (MC > 0) { // TODO: parse debug info // XXX why binfile->buf->base??? if (MC + 16 >= bin->size || MC + 16 < MC) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } regsz = r_read_le16 (ff2); ins_size = r_read_le16 (ff2 + 2); outs_size = r_read_le16 (ff2 + 4); tries_size = r_read_le16 (ff2 + 6); debug_info_off = r_read_le32 (ff2 + 8); insns_size = r_read_le32 (ff2 + 12); int padd = 0; if (tries_size > 0 && insns_size % 2) { padd = 2; } t = 16 + 2 * insns_size + padd; } if (dexdump) { const char* accessStr = createAccessFlagStr (MA, kAccessForMethod); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", method_name); rbin->cb_printf (" type : '%s'\n", signature); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)MA, accessStr); } if (MC > 0) { if (dexdump) { rbin->cb_printf (" code -\n"); rbin->cb_printf (" registers : %d\n", regsz); rbin->cb_printf (" ins : %d\n", ins_size); rbin->cb_printf (" outs : %d\n", outs_size); rbin->cb_printf ( " insns size : %d 16-bit code " "units\n", insns_size); } if (tries_size > 0) { if (dexdump) { rbin->cb_printf (" catches : %d\n", tries_size); } int j, m = 0; //XXX bucle controlled by tainted variable it could produces huge loop for (j = 0; j < tries_size; ++j) { ut64 offset = MC + t + j * 8; if (offset >= bin->size || offset < MC) { R_FREE (signature); break; } if (r_buf_read_at ( binfile->buf, binfile->buf->base + offset, ff3, 8) < 1) { // free (method_name); R_FREE (signature); break; } start_addr = r_read_le32 (ff3); insn_count = r_read_le16 (ff3 + 4); handler_off = r_read_le16 (ff3 + 6); char* s = NULL; if (dexdump) { rbin->cb_printf ( " 0x%04x - " "0x%04x\n", start_addr, (start_addr + insn_count)); } const ut8 *p3, *p3_end; //XXX tries_size is tainted and oob here int off = MC + t + tries_size * 8 + handler_off; if (off >= bin->size || off < tries_size) { R_FREE (signature); break; } p3 = r_buf_get_at (binfile->buf, off, NULL); p3_end = p3 + binfile->buf->length - off; st64 size = r_sleb128 (&p3, p3_end); if (size <= 0) { catchAll = true; size = -size; } else { catchAll = false; } for (m = 0; m < size; m++) { p3 = r_uleb128 (p3, p3_end - p3, &handler_type); p3 = r_uleb128 (p3, p3_end - p3, &handler_addr); if (handler_type > 0 && handler_type < bin->header.types_size) { s = getstr (bin, bin->types[handler_type].descriptor_id); if (dexdump) { rbin->cb_printf ( " %s " "-> 0x%04llx\n", s, handler_addr); } } else { if (dexdump) { rbin->cb_printf ( " " "(error) -> " "0x%04llx\n", handler_addr); } } } if (catchAll) { p3 = r_uleb128 (p3, p3_end - p3, &v2); if (dexdump) { rbin->cb_printf ( " " "<any> -> " "0x%04llx\n", v2); } } } } else { if (dexdump) { rbin->cb_printf ( " catches : " "(none)\n"); } } } else { if (dexdump) { rbin->cb_printf ( " code : (none)\n"); } } if (*flag_name) { RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = flag_name; // is_direct is no longer used // if method has code *addr points to code // otherwise it points to the encoded method if (MC > 0) { sym->type = r_str_const ("FUNC"); sym->paddr = MC;// + 0x10; sym->vaddr = MC;// + 0x10; } else { sym->type = r_str_const ("METH"); sym->paddr = encoded_method_addr - binfile->buf->buf; sym->vaddr = encoded_method_addr - binfile->buf->buf; } if ((MA & 0x1) == 0x1) { sym->bind = r_str_const ("GLOBAL"); } else { sym->bind = r_str_const ("LOCAL"); } sym->ordinal = (*sym_count)++; if (MC > 0) { if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (sym); R_FREE (signature); continue; } //ut16 regsz = r_read_le16 (ff2); //ut16 ins_size = r_read_le16 (ff2 + 2); //ut16 outs_size = r_read_le16 (ff2 + 4); ut16 tries_size = r_read_le16 (ff2 + 6); //ut32 debug_info_off = r_read_le32 (ff2 + 8); ut32 insns_size = r_read_le32 (ff2 + 12); ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; if (tries_size > 0) { //prolog_size += 2 + 8*tries_size; // we need to parse all so the catch info... } // TODO: prolog_size sym->paddr = MC + prolog_size;// + 0x10; sym->vaddr = MC + prolog_size;// + 0x10; //if (is_direct) { sym->size = insns_size * 2; //} //eprintf("%s (0x%x-0x%x) size=%d\nregsz=%d\ninsns_size=%d\nouts_size=%d\ntries_size=%d\ninsns_size=%d\n", flag_name, sym->vaddr, sym->vaddr+sym->size, prolog_size, regsz, ins_size, outs_size, tries_size, insns_size); r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); if (bin->code_from > sym->paddr) { bin->code_from = sym->paddr; } if (bin->code_to < sym->paddr) { bin->code_to = sym->paddr; } if (!mdb) { mdb = sdb_new0 (); } sdb_num_set (mdb, sdb_fmt (0, "method.%d", MI), sym->paddr, 0); // ----------------- // WORK IN PROGRESS // ----------------- if (0) { if (MA & 0x10000) { //ACC_CONSTRUCTOR if (!cdb) { cdb = sdb_new0 (); } sdb_num_set (cdb, sdb_fmt (0, "%d", c->class_id), sym->paddr, 0); } } } else { sym->size = 0; r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); } if (MC > 0 && debug_info_off > 0 && bin->header.data_offset < debug_info_off && debug_info_off < bin->header.data_offset + bin->header.data_size) { dex_parse_debug_item (binfile, bin, c, MI, MA, sym->paddr, ins_size, insns_size, cls->name, regsz, debug_info_off); } else if (MC > 0) { if (dexdump) { rbin->cb_printf (" positions :\n"); rbin->cb_printf (" locals :\n"); } } } else { R_FREE (flag_name); } R_FREE (signature); R_FREE (method_name); } return p; } static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf (" Class descriptor : '%s;'\n", class_name); rbin->cb_printf ( " Access flags : 0x%04x (%s)\n", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf (" Superclass : '%s'\n", dex_class_super_name (bin, c)); rbin->cb_printf (" Interfaces -\n"); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32(p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( " #%d : '%s'\n", z, getstr (bin, tid)); } } } } // TODO: this is quite ugly if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( " Static fields -\n Instance fields " "-\n Direct methods -\n Virtual methods " "-\n"); } } else { // TODO: move to func, def or inline // class_data_offset => [class_offset, class_defs_off+class_defs_size*32] if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; //XXX check for NULL!! c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf (" Static fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf (" Instance fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf (" Direct methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf (" Virtual methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( " source_file_idx : %d (unknown)\n\n", c->source_file); } else { rbin->cb_printf (" source_file_idx : %d (%s)\n\n", c->source_file, source_file); } } // TODO:!!!! // FIX: FREE BEFORE ALLOCATE!!! //free (class_name); } static bool is_class_idx_in_code_classes(RBinDexObj *bin, int class_idx) { int i; for (i = 0; i < bin->header.class_size; i++) { if (class_idx == bin->classes[i].class_id) { return true; } } return false; } static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size - 1) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; } static RList* imports(RBinFile *arch) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin) { return NULL; } if (bin && bin->imports_list) { return bin->imports_list; } dex_loadcode (arch, bin); return bin->imports_list; } static RList *methods(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->methods_list) { dex_loadcode (arch, bin); } return bin->methods_list; } static RList *classes(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->classes_list) { dex_loadcode (arch, bin); } return bin->classes_list; } static int already_entry(RList *entries, ut64 vaddr) { RBinAddr *e; RListIter *iter; r_list_foreach (entries, iter, e) { if (e->vaddr == vaddr) { return 1; } } return 0; } static RList *entries(RBinFile *arch) { RListIter *iter; RBinDexObj *bin; RBinSymbol *m; RBinAddr *ptr; RList *ret; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; ret = r_list_newf ((RListFree)free); if (!bin->methods_list) { dex_loadcode (arch, bin); } // STEP 1. ".onCreate(Landroid/os/Bundle;)V" r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 30 && m->bind && !strcmp(m->bind, "GLOBAL") && !strcmp (m->name + strlen (m->name) - 31, ".onCreate(Landroid/os/Bundle;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } // STEP 2. ".main([Ljava/lang/String;)V" if (r_list_empty (ret)) { r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 26 && !strcmp (m->name + strlen (m->name) - 27, ".main([Ljava/lang/String;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } } // STEP 3. NOTHING FOUND POINT TO CODE_INIT if (r_list_empty (ret)) { if (!already_entry (ret, bin->code_from)) { ptr = R_NEW0 (RBinAddr); if (ptr) { ptr->paddr = ptr->vaddr = bin->code_from; r_list_append (ret, ptr); } } } return ret; } static ut64 offset_of_method_idx(RBinFile *arch, struct r_bin_dex_obj_t *dex, int idx) { ut64 off = dex->header.method_offset + idx; off = sdb_num_get (mdb, sdb_fmt (0, "method.%d", idx), 0); return (ut64) off; } // TODO: change all return type for all getoffset static int getoffset(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods // TODO: ADD CHECK return offset_of_method_idx (arch, dex, idx); case 'o': // objects break; case 's': // strings if (dex->header.strings_size > idx) { if (dex->strings) return dex->strings[idx]; } break; case 't': // type return dex_get_type_offset (arch, idx); case 'c': // class return dex_get_type_offset (arch, idx); //return sdb_num_get (cdb, sdb_fmt (0, "%d", idx), 0); } return -1; } static char *getname(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods return dex_method_fullname (dex, idx); case 'c': // classes return dex_class_name_byid (dex, idx); case 'f': // fields return dex_field_name (dex, idx); } return NULL; } static RList *sections(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; RList *ml = methods (arch); RBinSection *ptr = NULL; int ns, fsymsz = 0; RList *ret = NULL; RListIter *iter; RBinSymbol *m; int fsym = 0; r_list_foreach (ml, iter, m) { if (!fsym || m->paddr < fsym) { fsym = m->paddr; } ns = m->paddr + m->size; if (ns > arch->buf->length) { continue; } if (ns > fsymsz) { fsymsz = ns; } } if (!fsym) { return NULL; } if (!(ret = r_list_new ())) { return NULL; } ret->free = free; if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "header"); ptr->size = ptr->vsize = sizeof (struct dex_header_t); ptr->paddr= ptr->vaddr = 0; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "constpool"); //ptr->size = ptr->vsize = fsym; ptr->paddr= ptr->vaddr = sizeof (struct dex_header_t); ptr->size = bin->code_from - ptr->vaddr; // fix size ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "code"); ptr->vaddr = ptr->paddr = bin->code_from; //ptr->vaddr = fsym; ptr->size = bin->code_to - ptr->paddr; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { //ut64 sz = arch ? r_buf_size (arch->buf): 0; strcpy (ptr->name, "data"); ptr->paddr = ptr->vaddr = fsymsz+fsym; if (ptr->vaddr > arch->buf->length) { ptr->paddr = ptr->vaddr = bin->code_to; ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; } else { ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; // hacky workaround //dprintf ("Hack\n"); //ptr->size = ptr->vsize = 1024; } ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; //|2; ptr->add = true; r_list_append (ret, ptr); } return ret; } static void header(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; struct r_bin_t *rbin = arch->rbin; rbin->cb_printf ("DEX file header:\n"); rbin->cb_printf ("magic : 'dex\\n035\\0'\n"); rbin->cb_printf ("checksum : %x\n", bin->header.checksum); rbin->cb_printf ("signature : %02x%02x...%02x%02x\n", bin->header.signature[0], bin->header.signature[1], bin->header.signature[18], bin->header.signature[19]); rbin->cb_printf ("file_size : %d\n", bin->header.size); rbin->cb_printf ("header_size : %d\n", bin->header.header_size); rbin->cb_printf ("link_size : %d\n", bin->header.linksection_size); rbin->cb_printf ("link_off : %d (0x%06x)\n", bin->header.linksection_offset, bin->header.linksection_offset); rbin->cb_printf ("string_ids_size : %d\n", bin->header.strings_size); rbin->cb_printf ("string_ids_off : %d (0x%06x)\n", bin->header.strings_offset, bin->header.strings_offset); rbin->cb_printf ("type_ids_size : %d\n", bin->header.types_size); rbin->cb_printf ("type_ids_off : %d (0x%06x)\n", bin->header.types_offset, bin->header.types_offset); rbin->cb_printf ("proto_ids_size : %d\n", bin->header.prototypes_size); rbin->cb_printf ("proto_ids_off : %d (0x%06x)\n", bin->header.prototypes_offset, bin->header.prototypes_offset); rbin->cb_printf ("field_ids_size : %d\n", bin->header.fields_size); rbin->cb_printf ("field_ids_off : %d (0x%06x)\n", bin->header.fields_offset, bin->header.fields_offset); rbin->cb_printf ("method_ids_size : %d\n", bin->header.method_size); rbin->cb_printf ("method_ids_off : %d (0x%06x)\n", bin->header.method_offset, bin->header.method_offset); rbin->cb_printf ("class_defs_size : %d\n", bin->header.class_size); rbin->cb_printf ("class_defs_off : %d (0x%06x)\n", bin->header.class_offset, bin->header.class_offset); rbin->cb_printf ("data_size : %d\n", bin->header.data_size); rbin->cb_printf ("data_off : %d (0x%06x)\n\n", bin->header.data_offset, bin->header.data_offset); // TODO: print information stored in the RBIN not this ugly fix dexdump = true; bin->methods_list = NULL; dex_loadcode (arch, bin); dexdump = false; } static ut64 size(RBinFile *arch) { int ret; ut32 off = 0, len = 0; ut8 u32s[sizeof (ut32)] = {0}; ret = r_buf_read_at (arch->buf, 108, u32s, 4); if (ret != 4) { return 0; } off = r_read_le32 (u32s); ret = r_buf_read_at (arch->buf, 104, u32s, 4); if (ret != 4) { return 0; } len = r_read_le32 (u32s); return off + len; } RBinPlugin r_bin_plugin_dex = { .name = "dex", .desc = "dex format bin plugin", .license = "LGPL3", .get_sdb = &get_sdb, .load = &load, .load_bytes = &load_bytes, .check = &check, .check_bytes = &check_bytes, .baddr = &baddr, .entries = entries, .classes = classes, .sections = sections, .symbols = methods, .imports = imports, .strings = strings, .info = &info, .header = &header, .size = &size, .get_offset = &getoffset, .get_name = &getname, .dbginfo = &r_bin_dbginfo_dex, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_BIN, .data = &r_bin_plugin_dex, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3164_1
crossvul-cpp_data_bad_5363_0
/* * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Image Information Program * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <assert.h> #include <jasper/jasper.h> /******************************************************************************\ * \******************************************************************************/ typedef enum { OPT_HELP, OPT_VERSION, OPT_VERBOSE, OPT_INFILE } optid_t; /******************************************************************************\ * \******************************************************************************/ static void usage(void); static void cmdinfo(void); /******************************************************************************\ * \******************************************************************************/ static jas_opt_t opts[] = { {OPT_HELP, "help", 0}, {OPT_VERSION, "version", 0}, {OPT_VERBOSE, "verbose", 0}, {OPT_INFILE, "f", JAS_OPT_HASARG}, {-1, 0, 0} }; static char *cmdname = 0; /******************************************************************************\ * Main program. \******************************************************************************/ int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_HELP: default: usage(); break; } } /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); numcmpts = jas_image_numcmpts(image); width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; } /******************************************************************************\ * \******************************************************************************/ static void cmdinfo() { fprintf(stderr, "Image Information Utility (Version %s).\n", JAS_VERSION); fprintf(stderr, "Copyright (c) 2001 Michael David Adams.\n" "All rights reserved.\n" ); } static void usage() { cmdinfo(); fprintf(stderr, "usage:\n"); fprintf(stderr,"%s ", cmdname); fprintf(stderr, "[-f image_file]\n"); exit(EXIT_FAILURE); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5363_0
crossvul-cpp_data_good_5410_0
/* Large capacity key type * * Copyright (C) 2013 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. */ #define pr_fmt(fmt) "big_key: "fmt #include <linux/init.h> #include <linux/seq_file.h> #include <linux/file.h> #include <linux/shmem_fs.h> #include <linux/err.h> #include <linux/scatterlist.h> #include <keys/user-type.h> #include <keys/big_key-type.h> #include <crypto/rng.h> #include <crypto/skcipher.h> /* * Layout of key payload words. */ enum { big_key_data, big_key_path, big_key_path_2nd_part, big_key_len, }; /* * Crypto operation with big_key data */ enum big_key_op { BIG_KEY_ENC, BIG_KEY_DEC, }; /* * If the data is under this limit, there's no point creating a shm file to * hold it as the permanently resident metadata for the shmem fs will be at * least as large as the data. */ #define BIG_KEY_FILE_THRESHOLD (sizeof(struct inode) + sizeof(struct dentry)) /* * Key size for big_key data encryption */ #define ENC_KEY_SIZE 16 /* * big_key defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_big_key = { .name = "big_key", .preparse = big_key_preparse, .free_preparse = big_key_free_preparse, .instantiate = generic_key_instantiate, .revoke = big_key_revoke, .destroy = big_key_destroy, .describe = big_key_describe, .read = big_key_read, }; /* * Crypto names for big_key data encryption */ static const char big_key_rng_name[] = "stdrng"; static const char big_key_alg_name[] = "ecb(aes)"; /* * Crypto algorithms for big_key data encryption */ static struct crypto_rng *big_key_rng; static struct crypto_skcipher *big_key_skcipher; /* * Generate random key to encrypt big_key data */ static inline int big_key_gen_enckey(u8 *key) { return crypto_rng_get_bytes(big_key_rng, key, ENC_KEY_SIZE); } /* * Encrypt/decrypt big_key data */ static int big_key_crypt(enum big_key_op op, u8 *data, size_t datalen, u8 *key) { int ret = -EINVAL; struct scatterlist sgio; SKCIPHER_REQUEST_ON_STACK(req, big_key_skcipher); if (crypto_skcipher_setkey(big_key_skcipher, key, ENC_KEY_SIZE)) { ret = -EAGAIN; goto error; } skcipher_request_set_tfm(req, big_key_skcipher); skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL); sg_init_one(&sgio, data, datalen); skcipher_request_set_crypt(req, &sgio, &sgio, datalen, NULL); if (op == BIG_KEY_ENC) ret = crypto_skcipher_encrypt(req); else ret = crypto_skcipher_decrypt(req); skcipher_request_zero(req); error: return ret; } /* * Preparse a big key */ int big_key_preparse(struct key_preparsed_payload *prep) { struct path *path = (struct path *)&prep->payload.data[big_key_path]; struct file *file; u8 *enckey; u8 *data = NULL; ssize_t written; size_t datalen = prep->datalen; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 1024 * 1024 || !prep->data) goto error; /* Set an arbitrary quota */ prep->quotalen = 16; prep->payload.data[big_key_len] = (void *)(unsigned long)datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { /* Create a shmem file to store the data in. This will permit the data * to be swapped out if needed. * * File content is stored encrypted with randomly generated key. */ size_t enclen = ALIGN(datalen, crypto_skcipher_blocksize(big_key_skcipher)); /* prepare aligned data to encrypt */ data = kmalloc(enclen, GFP_KERNEL); if (!data) return -ENOMEM; memcpy(data, prep->data, datalen); memset(data + datalen, 0x00, enclen - datalen); /* generate random key */ enckey = kmalloc(ENC_KEY_SIZE, GFP_KERNEL); if (!enckey) { ret = -ENOMEM; goto error; } ret = big_key_gen_enckey(enckey); if (ret) goto err_enckey; /* encrypt aligned data */ ret = big_key_crypt(BIG_KEY_ENC, data, enclen, enckey); if (ret) goto err_enckey; /* save aligned data to file */ file = shmem_kernel_file_setup("", enclen, 0); if (IS_ERR(file)) { ret = PTR_ERR(file); goto err_enckey; } written = kernel_write(file, data, enclen, 0); if (written != enclen) { ret = written; if (written >= 0) ret = -ENOMEM; goto err_fput; } /* Pin the mount and dentry to the key so that we can open it again * later */ prep->payload.data[big_key_data] = enckey; *path = file->f_path; path_get(path); fput(file); kfree(data); } else { /* Just store the data in a buffer */ void *data = kmalloc(datalen, GFP_KERNEL); if (!data) return -ENOMEM; prep->payload.data[big_key_data] = data; memcpy(data, prep->data, prep->datalen); } return 0; err_fput: fput(file); err_enckey: kfree(enckey); error: kfree(data); return ret; } /* * Clear preparsement. */ void big_key_free_preparse(struct key_preparsed_payload *prep) { if (prep->datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&prep->payload.data[big_key_path]; path_put(path); } kfree(prep->payload.data[big_key_data]); } /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_instantiated(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } /* * dispose of the data dangling from the corpse of a big_key key */ void big_key_destroy(struct key *key) { size_t datalen = (size_t)key->payload.data[big_key_len]; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data[big_key_path]; path_put(path); path->mnt = NULL; path->dentry = NULL; } kfree(key->payload.data[big_key_data]); key->payload.data[big_key_data] = NULL; } /* * describe the big_key key */ void big_key_describe(const struct key *key, struct seq_file *m) { size_t datalen = (size_t)key->payload.data[big_key_len]; seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %zu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } /* * read the key data * - the key's semaphore is read-locked */ long big_key_read(const struct key *key, char __user *buffer, size_t buflen) { size_t datalen = (size_t)key->payload.data[big_key_len]; long ret; if (!buffer || buflen < datalen) return datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data[big_key_path]; struct file *file; u8 *data; u8 *enckey = (u8 *)key->payload.data[big_key_data]; size_t enclen = ALIGN(datalen, crypto_skcipher_blocksize(big_key_skcipher)); data = kmalloc(enclen, GFP_KERNEL); if (!data) return -ENOMEM; file = dentry_open(path, O_RDONLY, current_cred()); if (IS_ERR(file)) { ret = PTR_ERR(file); goto error; } /* read file to kernel and decrypt */ ret = kernel_read(file, 0, data, enclen); if (ret >= 0 && ret != enclen) { ret = -EIO; goto err_fput; } ret = big_key_crypt(BIG_KEY_DEC, data, enclen, enckey); if (ret) goto err_fput; ret = datalen; /* copy decrypted data to user */ if (copy_to_user(buffer, data, datalen) != 0) ret = -EFAULT; err_fput: fput(file); error: kfree(data); } else { ret = datalen; if (copy_to_user(buffer, key->payload.data[big_key_data], datalen) != 0) ret = -EFAULT; } return ret; } /* * Register key type */ static int __init big_key_init(void) { struct crypto_skcipher *cipher; struct crypto_rng *rng; int ret; rng = crypto_alloc_rng(big_key_rng_name, 0, 0); if (IS_ERR(rng)) { pr_err("Can't alloc rng: %ld\n", PTR_ERR(rng)); return PTR_ERR(rng); } big_key_rng = rng; /* seed RNG */ ret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng)); if (ret) { pr_err("Can't reset rng: %d\n", ret); goto error_rng; } /* init block cipher */ cipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(cipher)) { ret = PTR_ERR(cipher); pr_err("Can't alloc crypto: %d\n", ret); goto error_rng; } big_key_skcipher = cipher; ret = register_key_type(&key_type_big_key); if (ret < 0) { pr_err("Can't register type: %d\n", ret); goto error_cipher; } return 0; error_cipher: crypto_free_skcipher(big_key_skcipher); error_rng: crypto_free_rng(big_key_rng); return ret; } late_initcall(big_key_init);
./CrossVul/dataset_final_sorted/CWE-476/c/good_5410_0
crossvul-cpp_data_good_5129_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD CCCC M M % % D D C MM MM % % D D C M M M % % D D C M M % % DDDD CCCC M M % % % % % % Read DICOM Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 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 "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/resource_.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/module.h" /* Dicom medical image declarations. */ typedef struct _DicomInfo { const unsigned short group, element; const char *vr, *description; } DicomInfo; static const DicomInfo dicom_info[] = { { 0x0000, 0x0000, "UL", "Group Length" }, { 0x0000, 0x0001, "UL", "Command Length to End" }, { 0x0000, 0x0002, "UI", "Affected SOP Class UID" }, { 0x0000, 0x0003, "UI", "Requested SOP Class UID" }, { 0x0000, 0x0010, "LO", "Command Recognition Code" }, { 0x0000, 0x0100, "US", "Command Field" }, { 0x0000, 0x0110, "US", "Message ID" }, { 0x0000, 0x0120, "US", "Message ID Being Responded To" }, { 0x0000, 0x0200, "AE", "Initiator" }, { 0x0000, 0x0300, "AE", "Receiver" }, { 0x0000, 0x0400, "AE", "Find Location" }, { 0x0000, 0x0600, "AE", "Move Destination" }, { 0x0000, 0x0700, "US", "Priority" }, { 0x0000, 0x0800, "US", "Data Set Type" }, { 0x0000, 0x0850, "US", "Number of Matches" }, { 0x0000, 0x0860, "US", "Response Sequence Number" }, { 0x0000, 0x0900, "US", "Status" }, { 0x0000, 0x0901, "AT", "Offending Element" }, { 0x0000, 0x0902, "LO", "Exception Comment" }, { 0x0000, 0x0903, "US", "Exception ID" }, { 0x0000, 0x1000, "UI", "Affected SOP Instance UID" }, { 0x0000, 0x1001, "UI", "Requested SOP Instance UID" }, { 0x0000, 0x1002, "US", "Event Type ID" }, { 0x0000, 0x1005, "AT", "Attribute Identifier List" }, { 0x0000, 0x1008, "US", "Action Type ID" }, { 0x0000, 0x1020, "US", "Number of Remaining Suboperations" }, { 0x0000, 0x1021, "US", "Number of Completed Suboperations" }, { 0x0000, 0x1022, "US", "Number of Failed Suboperations" }, { 0x0000, 0x1023, "US", "Number of Warning Suboperations" }, { 0x0000, 0x1030, "AE", "Move Originator Application Entity Title" }, { 0x0000, 0x1031, "US", "Move Originator Message ID" }, { 0x0000, 0x4000, "LO", "Dialog Receiver" }, { 0x0000, 0x4010, "LO", "Terminal Type" }, { 0x0000, 0x5010, "SH", "Message Set ID" }, { 0x0000, 0x5020, "SH", "End Message Set" }, { 0x0000, 0x5110, "LO", "Display Format" }, { 0x0000, 0x5120, "LO", "Page Position ID" }, { 0x0000, 0x5130, "LO", "Text Format ID" }, { 0x0000, 0x5140, "LO", "Normal Reverse" }, { 0x0000, 0x5150, "LO", "Add Gray Scale" }, { 0x0000, 0x5160, "LO", "Borders" }, { 0x0000, 0x5170, "IS", "Copies" }, { 0x0000, 0x5180, "LO", "OldMagnificationType" }, { 0x0000, 0x5190, "LO", "Erase" }, { 0x0000, 0x51a0, "LO", "Print" }, { 0x0000, 0x51b0, "US", "Overlays" }, { 0x0002, 0x0000, "UL", "Meta Element Group Length" }, { 0x0002, 0x0001, "OB", "File Meta Information Version" }, { 0x0002, 0x0002, "UI", "Media Storage SOP Class UID" }, { 0x0002, 0x0003, "UI", "Media Storage SOP Instance UID" }, { 0x0002, 0x0010, "UI", "Transfer Syntax UID" }, { 0x0002, 0x0012, "UI", "Implementation Class UID" }, { 0x0002, 0x0013, "SH", "Implementation Version Name" }, { 0x0002, 0x0016, "AE", "Source Application Entity Title" }, { 0x0002, 0x0100, "UI", "Private Information Creator UID" }, { 0x0002, 0x0102, "OB", "Private Information" }, { 0x0003, 0x0000, "US", "?" }, { 0x0003, 0x0008, "US", "ISI Command Field" }, { 0x0003, 0x0011, "US", "Attach ID Application Code" }, { 0x0003, 0x0012, "UL", "Attach ID Message Count" }, { 0x0003, 0x0013, "DA", "Attach ID Date" }, { 0x0003, 0x0014, "TM", "Attach ID Time" }, { 0x0003, 0x0020, "US", "Message Type" }, { 0x0003, 0x0030, "DA", "Max Waiting Date" }, { 0x0003, 0x0031, "TM", "Max Waiting Time" }, { 0x0004, 0x0000, "UL", "File Set Group Length" }, { 0x0004, 0x1130, "CS", "File Set ID" }, { 0x0004, 0x1141, "CS", "File Set Descriptor File ID" }, { 0x0004, 0x1142, "CS", "File Set Descriptor File Specific Character Set" }, { 0x0004, 0x1200, "UL", "Root Directory Entity First Directory Record Offset" }, { 0x0004, 0x1202, "UL", "Root Directory Entity Last Directory Record Offset" }, { 0x0004, 0x1212, "US", "File Set Consistency Flag" }, { 0x0004, 0x1220, "SQ", "Directory Record Sequence" }, { 0x0004, 0x1400, "UL", "Next Directory Record Offset" }, { 0x0004, 0x1410, "US", "Record In Use Flag" }, { 0x0004, 0x1420, "UL", "Referenced Lower Level Directory Entity Offset" }, { 0x0004, 0x1430, "CS", "Directory Record Type" }, { 0x0004, 0x1432, "UI", "Private Record UID" }, { 0x0004, 0x1500, "CS", "Referenced File ID" }, { 0x0004, 0x1504, "UL", "MRDR Directory Record Offset" }, { 0x0004, 0x1510, "UI", "Referenced SOP Class UID In File" }, { 0x0004, 0x1511, "UI", "Referenced SOP Instance UID In File" }, { 0x0004, 0x1512, "UI", "Referenced Transfer Syntax UID In File" }, { 0x0004, 0x1600, "UL", "Number of References" }, { 0x0005, 0x0000, "US", "?" }, { 0x0006, 0x0000, "US", "?" }, { 0x0008, 0x0000, "UL", "Identifying Group Length" }, { 0x0008, 0x0001, "UL", "Length to End" }, { 0x0008, 0x0005, "CS", "Specific Character Set" }, { 0x0008, 0x0008, "CS", "Image Type" }, { 0x0008, 0x0010, "LO", "Recognition Code" }, { 0x0008, 0x0012, "DA", "Instance Creation Date" }, { 0x0008, 0x0013, "TM", "Instance Creation Time" }, { 0x0008, 0x0014, "UI", "Instance Creator UID" }, { 0x0008, 0x0016, "UI", "SOP Class UID" }, { 0x0008, 0x0018, "UI", "SOP Instance UID" }, { 0x0008, 0x0020, "DA", "Study Date" }, { 0x0008, 0x0021, "DA", "Series Date" }, { 0x0008, 0x0022, "DA", "Acquisition Date" }, { 0x0008, 0x0023, "DA", "Image Date" }, { 0x0008, 0x0024, "DA", "Overlay Date" }, { 0x0008, 0x0025, "DA", "Curve Date" }, { 0x0008, 0x0030, "TM", "Study Time" }, { 0x0008, 0x0031, "TM", "Series Time" }, { 0x0008, 0x0032, "TM", "Acquisition Time" }, { 0x0008, 0x0033, "TM", "Image Time" }, { 0x0008, 0x0034, "TM", "Overlay Time" }, { 0x0008, 0x0035, "TM", "Curve Time" }, { 0x0008, 0x0040, "xs", "Old Data Set Type" }, { 0x0008, 0x0041, "xs", "Old Data Set Subtype" }, { 0x0008, 0x0042, "CS", "Nuclear Medicine Series Type" }, { 0x0008, 0x0050, "SH", "Accession Number" }, { 0x0008, 0x0052, "CS", "Query/Retrieve Level" }, { 0x0008, 0x0054, "AE", "Retrieve AE Title" }, { 0x0008, 0x0058, "UI", "Failed SOP Instance UID List" }, { 0x0008, 0x0060, "CS", "Modality" }, { 0x0008, 0x0062, "SQ", "Modality Subtype" }, { 0x0008, 0x0064, "CS", "Conversion Type" }, { 0x0008, 0x0068, "CS", "Presentation Intent Type" }, { 0x0008, 0x0070, "LO", "Manufacturer" }, { 0x0008, 0x0080, "LO", "Institution Name" }, { 0x0008, 0x0081, "ST", "Institution Address" }, { 0x0008, 0x0082, "SQ", "Institution Code Sequence" }, { 0x0008, 0x0090, "PN", "Referring Physician's Name" }, { 0x0008, 0x0092, "ST", "Referring Physician's Address" }, { 0x0008, 0x0094, "SH", "Referring Physician's Telephone Numbers" }, { 0x0008, 0x0100, "SH", "Code Value" }, { 0x0008, 0x0102, "SH", "Coding Scheme Designator" }, { 0x0008, 0x0103, "SH", "Coding Scheme Version" }, { 0x0008, 0x0104, "LO", "Code Meaning" }, { 0x0008, 0x0105, "CS", "Mapping Resource" }, { 0x0008, 0x0106, "DT", "Context Group Version" }, { 0x0008, 0x010b, "CS", "Code Set Extension Flag" }, { 0x0008, 0x010c, "UI", "Private Coding Scheme Creator UID" }, { 0x0008, 0x010d, "UI", "Code Set Extension Creator UID" }, { 0x0008, 0x010f, "CS", "Context Identifier" }, { 0x0008, 0x1000, "LT", "Network ID" }, { 0x0008, 0x1010, "SH", "Station Name" }, { 0x0008, 0x1030, "LO", "Study Description" }, { 0x0008, 0x1032, "SQ", "Procedure Code Sequence" }, { 0x0008, 0x103e, "LO", "Series Description" }, { 0x0008, 0x1040, "LO", "Institutional Department Name" }, { 0x0008, 0x1048, "PN", "Physician of Record" }, { 0x0008, 0x1050, "PN", "Performing Physician's Name" }, { 0x0008, 0x1060, "PN", "Name of Physician(s) Reading Study" }, { 0x0008, 0x1070, "PN", "Operator's Name" }, { 0x0008, 0x1080, "LO", "Admitting Diagnosis Description" }, { 0x0008, 0x1084, "SQ", "Admitting Diagnosis Code Sequence" }, { 0x0008, 0x1090, "LO", "Manufacturer's Model Name" }, { 0x0008, 0x1100, "SQ", "Referenced Results Sequence" }, { 0x0008, 0x1110, "SQ", "Referenced Study Sequence" }, { 0x0008, 0x1111, "SQ", "Referenced Study Component Sequence" }, { 0x0008, 0x1115, "SQ", "Referenced Series Sequence" }, { 0x0008, 0x1120, "SQ", "Referenced Patient Sequence" }, { 0x0008, 0x1125, "SQ", "Referenced Visit Sequence" }, { 0x0008, 0x1130, "SQ", "Referenced Overlay Sequence" }, { 0x0008, 0x1140, "SQ", "Referenced Image Sequence" }, { 0x0008, 0x1145, "SQ", "Referenced Curve Sequence" }, { 0x0008, 0x1148, "SQ", "Referenced Previous Waveform" }, { 0x0008, 0x114a, "SQ", "Referenced Simultaneous Waveforms" }, { 0x0008, 0x114c, "SQ", "Referenced Subsequent Waveform" }, { 0x0008, 0x1150, "UI", "Referenced SOP Class UID" }, { 0x0008, 0x1155, "UI", "Referenced SOP Instance UID" }, { 0x0008, 0x1160, "IS", "Referenced Frame Number" }, { 0x0008, 0x1195, "UI", "Transaction UID" }, { 0x0008, 0x1197, "US", "Failure Reason" }, { 0x0008, 0x1198, "SQ", "Failed SOP Sequence" }, { 0x0008, 0x1199, "SQ", "Referenced SOP Sequence" }, { 0x0008, 0x2110, "CS", "Old Lossy Image Compression" }, { 0x0008, 0x2111, "ST", "Derivation Description" }, { 0x0008, 0x2112, "SQ", "Source Image Sequence" }, { 0x0008, 0x2120, "SH", "Stage Name" }, { 0x0008, 0x2122, "IS", "Stage Number" }, { 0x0008, 0x2124, "IS", "Number of Stages" }, { 0x0008, 0x2128, "IS", "View Number" }, { 0x0008, 0x2129, "IS", "Number of Event Timers" }, { 0x0008, 0x212a, "IS", "Number of Views in Stage" }, { 0x0008, 0x2130, "DS", "Event Elapsed Time(s)" }, { 0x0008, 0x2132, "LO", "Event Timer Name(s)" }, { 0x0008, 0x2142, "IS", "Start Trim" }, { 0x0008, 0x2143, "IS", "Stop Trim" }, { 0x0008, 0x2144, "IS", "Recommended Display Frame Rate" }, { 0x0008, 0x2200, "CS", "Transducer Position" }, { 0x0008, 0x2204, "CS", "Transducer Orientation" }, { 0x0008, 0x2208, "CS", "Anatomic Structure" }, { 0x0008, 0x2218, "SQ", "Anatomic Region Sequence" }, { 0x0008, 0x2220, "SQ", "Anatomic Region Modifier Sequence" }, { 0x0008, 0x2228, "SQ", "Primary Anatomic Structure Sequence" }, { 0x0008, 0x2230, "SQ", "Primary Anatomic Structure Modifier Sequence" }, { 0x0008, 0x2240, "SQ", "Transducer Position Sequence" }, { 0x0008, 0x2242, "SQ", "Transducer Position Modifier Sequence" }, { 0x0008, 0x2244, "SQ", "Transducer Orientation Sequence" }, { 0x0008, 0x2246, "SQ", "Transducer Orientation Modifier Sequence" }, { 0x0008, 0x2251, "SQ", "Anatomic Structure Space Or Region Code Sequence" }, { 0x0008, 0x2253, "SQ", "Anatomic Portal Of Entrance Code Sequence" }, { 0x0008, 0x2255, "SQ", "Anatomic Approach Direction Code Sequence" }, { 0x0008, 0x2256, "ST", "Anatomic Perspective Description" }, { 0x0008, 0x2257, "SQ", "Anatomic Perspective Code Sequence" }, { 0x0008, 0x2258, "ST", "Anatomic Location Of Examining Instrument Description" }, { 0x0008, 0x2259, "SQ", "Anatomic Location Of Examining Instrument Code Sequence" }, { 0x0008, 0x225a, "SQ", "Anatomic Structure Space Or Region Modifier Code Sequence" }, { 0x0008, 0x225c, "SQ", "OnAxis Background Anatomic Structure Code Sequence" }, { 0x0008, 0x4000, "LT", "Identifying Comments" }, { 0x0009, 0x0000, "xs", "?" }, { 0x0009, 0x0001, "xs", "?" }, { 0x0009, 0x0002, "xs", "?" }, { 0x0009, 0x0003, "xs", "?" }, { 0x0009, 0x0004, "xs", "?" }, { 0x0009, 0x0005, "UN", "?" }, { 0x0009, 0x0006, "UN", "?" }, { 0x0009, 0x0007, "UN", "?" }, { 0x0009, 0x0008, "xs", "?" }, { 0x0009, 0x0009, "LT", "?" }, { 0x0009, 0x000a, "IS", "?" }, { 0x0009, 0x000b, "IS", "?" }, { 0x0009, 0x000c, "IS", "?" }, { 0x0009, 0x000d, "IS", "?" }, { 0x0009, 0x000e, "IS", "?" }, { 0x0009, 0x000f, "UN", "?" }, { 0x0009, 0x0010, "xs", "?" }, { 0x0009, 0x0011, "xs", "?" }, { 0x0009, 0x0012, "xs", "?" }, { 0x0009, 0x0013, "xs", "?" }, { 0x0009, 0x0014, "xs", "?" }, { 0x0009, 0x0015, "xs", "?" }, { 0x0009, 0x0016, "xs", "?" }, { 0x0009, 0x0017, "LT", "?" }, { 0x0009, 0x0018, "LT", "Data Set Identifier" }, { 0x0009, 0x001a, "US", "?" }, { 0x0009, 0x001e, "UI", "?" }, { 0x0009, 0x0020, "xs", "?" }, { 0x0009, 0x0021, "xs", "?" }, { 0x0009, 0x0022, "SH", "User Orientation" }, { 0x0009, 0x0023, "SL", "Initiation Type" }, { 0x0009, 0x0024, "xs", "?" }, { 0x0009, 0x0025, "xs", "?" }, { 0x0009, 0x0026, "xs", "?" }, { 0x0009, 0x0027, "xs", "?" }, { 0x0009, 0x0029, "xs", "?" }, { 0x0009, 0x002a, "SL", "?" }, { 0x0009, 0x002c, "LO", "Series Comments" }, { 0x0009, 0x002d, "SL", "Track Beat Average" }, { 0x0009, 0x002e, "FD", "Distance Prescribed" }, { 0x0009, 0x002f, "LT", "?" }, { 0x0009, 0x0030, "xs", "?" }, { 0x0009, 0x0031, "xs", "?" }, { 0x0009, 0x0032, "LT", "?" }, { 0x0009, 0x0034, "xs", "?" }, { 0x0009, 0x0035, "SL", "Gantry Locus Type" }, { 0x0009, 0x0037, "SL", "Starting Heart Rate" }, { 0x0009, 0x0038, "xs", "?" }, { 0x0009, 0x0039, "SL", "RR Window Offset" }, { 0x0009, 0x003a, "SL", "Percent Cycle Imaged" }, { 0x0009, 0x003e, "US", "?" }, { 0x0009, 0x003f, "US", "?" }, { 0x0009, 0x0040, "xs", "?" }, { 0x0009, 0x0041, "xs", "?" }, { 0x0009, 0x0042, "xs", "?" }, { 0x0009, 0x0043, "xs", "?" }, { 0x0009, 0x0050, "LT", "?" }, { 0x0009, 0x0051, "xs", "?" }, { 0x0009, 0x0060, "LT", "?" }, { 0x0009, 0x0061, "LT", "Series Unique Identifier" }, { 0x0009, 0x0070, "LT", "?" }, { 0x0009, 0x0080, "LT", "?" }, { 0x0009, 0x0091, "LT", "?" }, { 0x0009, 0x00e2, "LT", "?" }, { 0x0009, 0x00e3, "UI", "Equipment UID" }, { 0x0009, 0x00e6, "SH", "Genesis Version Now" }, { 0x0009, 0x00e7, "UL", "Exam Record Checksum" }, { 0x0009, 0x00e8, "UL", "?" }, { 0x0009, 0x00e9, "SL", "Actual Series Data Time Stamp" }, { 0x0009, 0x00f2, "UN", "?" }, { 0x0009, 0x00f3, "UN", "?" }, { 0x0009, 0x00f4, "LT", "?" }, { 0x0009, 0x00f5, "xs", "?" }, { 0x0009, 0x00f6, "LT", "PDM Data Object Type Extension" }, { 0x0009, 0x00f8, "US", "?" }, { 0x0009, 0x00fb, "IS", "?" }, { 0x0009, 0x1002, "OB", "?" }, { 0x0009, 0x1003, "OB", "?" }, { 0x0009, 0x1010, "UN", "?" }, { 0x0010, 0x0000, "UL", "Patient Group Length" }, { 0x0010, 0x0010, "PN", "Patient's Name" }, { 0x0010, 0x0020, "LO", "Patient's ID" }, { 0x0010, 0x0021, "LO", "Issuer of Patient's ID" }, { 0x0010, 0x0030, "DA", "Patient's Birth Date" }, { 0x0010, 0x0032, "TM", "Patient's Birth Time" }, { 0x0010, 0x0040, "CS", "Patient's Sex" }, { 0x0010, 0x0050, "SQ", "Patient's Insurance Plan Code Sequence" }, { 0x0010, 0x1000, "LO", "Other Patient's ID's" }, { 0x0010, 0x1001, "PN", "Other Patient's Names" }, { 0x0010, 0x1005, "PN", "Patient's Birth Name" }, { 0x0010, 0x1010, "AS", "Patient's Age" }, { 0x0010, 0x1020, "DS", "Patient's Size" }, { 0x0010, 0x1030, "DS", "Patient's Weight" }, { 0x0010, 0x1040, "LO", "Patient's Address" }, { 0x0010, 0x1050, "LT", "Insurance Plan Identification" }, { 0x0010, 0x1060, "PN", "Patient's Mother's Birth Name" }, { 0x0010, 0x1080, "LO", "Military Rank" }, { 0x0010, 0x1081, "LO", "Branch of Service" }, { 0x0010, 0x1090, "LO", "Medical Record Locator" }, { 0x0010, 0x2000, "LO", "Medical Alerts" }, { 0x0010, 0x2110, "LO", "Contrast Allergies" }, { 0x0010, 0x2150, "LO", "Country of Residence" }, { 0x0010, 0x2152, "LO", "Region of Residence" }, { 0x0010, 0x2154, "SH", "Patients Telephone Numbers" }, { 0x0010, 0x2160, "SH", "Ethnic Group" }, { 0x0010, 0x2180, "SH", "Occupation" }, { 0x0010, 0x21a0, "CS", "Smoking Status" }, { 0x0010, 0x21b0, "LT", "Additional Patient History" }, { 0x0010, 0x21c0, "US", "Pregnancy Status" }, { 0x0010, 0x21d0, "DA", "Last Menstrual Date" }, { 0x0010, 0x21f0, "LO", "Patients Religious Preference" }, { 0x0010, 0x4000, "LT", "Patient Comments" }, { 0x0011, 0x0001, "xs", "?" }, { 0x0011, 0x0002, "US", "?" }, { 0x0011, 0x0003, "LT", "Patient UID" }, { 0x0011, 0x0004, "LT", "Patient ID" }, { 0x0011, 0x000a, "xs", "?" }, { 0x0011, 0x000b, "SL", "Effective Series Duration" }, { 0x0011, 0x000c, "SL", "Num Beats" }, { 0x0011, 0x000d, "LO", "Radio Nuclide Name" }, { 0x0011, 0x0010, "xs", "?" }, { 0x0011, 0x0011, "xs", "?" }, { 0x0011, 0x0012, "LO", "Dataset Name" }, { 0x0011, 0x0013, "LO", "Dataset Type" }, { 0x0011, 0x0015, "xs", "?" }, { 0x0011, 0x0016, "SL", "Energy Number" }, { 0x0011, 0x0017, "SL", "RR Interval Window Number" }, { 0x0011, 0x0018, "SL", "MG Bin Number" }, { 0x0011, 0x0019, "FD", "Radius Of Rotation" }, { 0x0011, 0x001a, "SL", "Detector Count Zone" }, { 0x0011, 0x001b, "SL", "Num Energy Windows" }, { 0x0011, 0x001c, "SL", "Energy Offset" }, { 0x0011, 0x001d, "SL", "Energy Range" }, { 0x0011, 0x001f, "SL", "Image Orientation" }, { 0x0011, 0x0020, "xs", "?" }, { 0x0011, 0x0021, "xs", "?" }, { 0x0011, 0x0022, "xs", "?" }, { 0x0011, 0x0023, "xs", "?" }, { 0x0011, 0x0024, "SL", "FOV Mask Y Cutoff Angle" }, { 0x0011, 0x0025, "xs", "?" }, { 0x0011, 0x0026, "SL", "Table Orientation" }, { 0x0011, 0x0027, "SL", "ROI Top Left" }, { 0x0011, 0x0028, "SL", "ROI Bottom Right" }, { 0x0011, 0x0030, "xs", "?" }, { 0x0011, 0x0031, "xs", "?" }, { 0x0011, 0x0032, "UN", "?" }, { 0x0011, 0x0033, "LO", "Energy Correct Name" }, { 0x0011, 0x0034, "LO", "Spatial Correct Name" }, { 0x0011, 0x0035, "xs", "?" }, { 0x0011, 0x0036, "LO", "Uniformity Correct Name" }, { 0x0011, 0x0037, "LO", "Acquisition Specific Correct Name" }, { 0x0011, 0x0038, "SL", "Byte Order" }, { 0x0011, 0x003a, "SL", "Picture Format" }, { 0x0011, 0x003b, "FD", "Pixel Scale" }, { 0x0011, 0x003c, "FD", "Pixel Offset" }, { 0x0011, 0x003e, "SL", "FOV Shape" }, { 0x0011, 0x003f, "SL", "Dataset Flags" }, { 0x0011, 0x0040, "xs", "?" }, { 0x0011, 0x0041, "LT", "Medical Alerts" }, { 0x0011, 0x0042, "LT", "Contrast Allergies" }, { 0x0011, 0x0044, "FD", "Threshold Center" }, { 0x0011, 0x0045, "FD", "Threshold Width" }, { 0x0011, 0x0046, "SL", "Interpolation Type" }, { 0x0011, 0x0055, "FD", "Period" }, { 0x0011, 0x0056, "FD", "ElapsedTime" }, { 0x0011, 0x00a1, "DA", "Patient Registration Date" }, { 0x0011, 0x00a2, "TM", "Patient Registration Time" }, { 0x0011, 0x00b0, "LT", "Patient Last Name" }, { 0x0011, 0x00b2, "LT", "Patient First Name" }, { 0x0011, 0x00b4, "LT", "Patient Hospital Status" }, { 0x0011, 0x00bc, "TM", "Current Location Time" }, { 0x0011, 0x00c0, "LT", "Patient Insurance Status" }, { 0x0011, 0x00d0, "LT", "Patient Billing Type" }, { 0x0011, 0x00d2, "LT", "Patient Billing Address" }, { 0x0013, 0x0000, "LT", "Modifying Physician" }, { 0x0013, 0x0010, "xs", "?" }, { 0x0013, 0x0011, "SL", "?" }, { 0x0013, 0x0012, "xs", "?" }, { 0x0013, 0x0016, "SL", "AutoTrack Peak" }, { 0x0013, 0x0017, "SL", "AutoTrack Width" }, { 0x0013, 0x0018, "FD", "Transmission Scan Time" }, { 0x0013, 0x0019, "FD", "Transmission Mask Width" }, { 0x0013, 0x001a, "FD", "Copper Attenuator Thickness" }, { 0x0013, 0x001c, "FD", "?" }, { 0x0013, 0x001d, "FD", "?" }, { 0x0013, 0x001e, "FD", "Tomo View Offset" }, { 0x0013, 0x0020, "LT", "Patient Name" }, { 0x0013, 0x0022, "LT", "Patient Id" }, { 0x0013, 0x0026, "LT", "Study Comments" }, { 0x0013, 0x0030, "DA", "Patient Birthdate" }, { 0x0013, 0x0031, "DS", "Patient Weight" }, { 0x0013, 0x0032, "LT", "Patients Maiden Name" }, { 0x0013, 0x0033, "LT", "Referring Physician" }, { 0x0013, 0x0034, "LT", "Admitting Diagnosis" }, { 0x0013, 0x0035, "LT", "Patient Sex" }, { 0x0013, 0x0040, "LT", "Procedure Description" }, { 0x0013, 0x0042, "LT", "Patient Rest Direction" }, { 0x0013, 0x0044, "LT", "Patient Position" }, { 0x0013, 0x0046, "LT", "View Direction" }, { 0x0015, 0x0001, "DS", "Stenosis Calibration Ratio" }, { 0x0015, 0x0002, "DS", "Stenosis Magnification" }, { 0x0015, 0x0003, "DS", "Cardiac Calibration Ratio" }, { 0x0018, 0x0000, "UL", "Acquisition Group Length" }, { 0x0018, 0x0010, "LO", "Contrast/Bolus Agent" }, { 0x0018, 0x0012, "SQ", "Contrast/Bolus Agent Sequence" }, { 0x0018, 0x0014, "SQ", "Contrast/Bolus Administration Route Sequence" }, { 0x0018, 0x0015, "CS", "Body Part Examined" }, { 0x0018, 0x0020, "CS", "Scanning Sequence" }, { 0x0018, 0x0021, "CS", "Sequence Variant" }, { 0x0018, 0x0022, "CS", "Scan Options" }, { 0x0018, 0x0023, "CS", "MR Acquisition Type" }, { 0x0018, 0x0024, "SH", "Sequence Name" }, { 0x0018, 0x0025, "CS", "Angio Flag" }, { 0x0018, 0x0026, "SQ", "Intervention Drug Information Sequence" }, { 0x0018, 0x0027, "TM", "Intervention Drug Stop Time" }, { 0x0018, 0x0028, "DS", "Intervention Drug Dose" }, { 0x0018, 0x0029, "SQ", "Intervention Drug Code Sequence" }, { 0x0018, 0x002a, "SQ", "Additional Drug Sequence" }, { 0x0018, 0x0030, "LO", "Radionuclide" }, { 0x0018, 0x0031, "LO", "Radiopharmaceutical" }, { 0x0018, 0x0032, "DS", "Energy Window Centerline" }, { 0x0018, 0x0033, "DS", "Energy Window Total Width" }, { 0x0018, 0x0034, "LO", "Intervention Drug Name" }, { 0x0018, 0x0035, "TM", "Intervention Drug Start Time" }, { 0x0018, 0x0036, "SQ", "Intervention Therapy Sequence" }, { 0x0018, 0x0037, "CS", "Therapy Type" }, { 0x0018, 0x0038, "CS", "Intervention Status" }, { 0x0018, 0x0039, "CS", "Therapy Description" }, { 0x0018, 0x0040, "IS", "Cine Rate" }, { 0x0018, 0x0050, "DS", "Slice Thickness" }, { 0x0018, 0x0060, "DS", "KVP" }, { 0x0018, 0x0070, "IS", "Counts Accumulated" }, { 0x0018, 0x0071, "CS", "Acquisition Termination Condition" }, { 0x0018, 0x0072, "DS", "Effective Series Duration" }, { 0x0018, 0x0073, "CS", "Acquisition Start Condition" }, { 0x0018, 0x0074, "IS", "Acquisition Start Condition Data" }, { 0x0018, 0x0075, "IS", "Acquisition Termination Condition Data" }, { 0x0018, 0x0080, "DS", "Repetition Time" }, { 0x0018, 0x0081, "DS", "Echo Time" }, { 0x0018, 0x0082, "DS", "Inversion Time" }, { 0x0018, 0x0083, "DS", "Number of Averages" }, { 0x0018, 0x0084, "DS", "Imaging Frequency" }, { 0x0018, 0x0085, "SH", "Imaged Nucleus" }, { 0x0018, 0x0086, "IS", "Echo Number(s)" }, { 0x0018, 0x0087, "DS", "Magnetic Field Strength" }, { 0x0018, 0x0088, "DS", "Spacing Between Slices" }, { 0x0018, 0x0089, "IS", "Number of Phase Encoding Steps" }, { 0x0018, 0x0090, "DS", "Data Collection Diameter" }, { 0x0018, 0x0091, "IS", "Echo Train Length" }, { 0x0018, 0x0093, "DS", "Percent Sampling" }, { 0x0018, 0x0094, "DS", "Percent Phase Field of View" }, { 0x0018, 0x0095, "DS", "Pixel Bandwidth" }, { 0x0018, 0x1000, "LO", "Device Serial Number" }, { 0x0018, 0x1004, "LO", "Plate ID" }, { 0x0018, 0x1010, "LO", "Secondary Capture Device ID" }, { 0x0018, 0x1012, "DA", "Date of Secondary Capture" }, { 0x0018, 0x1014, "TM", "Time of Secondary Capture" }, { 0x0018, 0x1016, "LO", "Secondary Capture Device Manufacturer" }, { 0x0018, 0x1018, "LO", "Secondary Capture Device Manufacturer Model Name" }, { 0x0018, 0x1019, "LO", "Secondary Capture Device Software Version(s)" }, { 0x0018, 0x1020, "LO", "Software Version(s)" }, { 0x0018, 0x1022, "SH", "Video Image Format Acquired" }, { 0x0018, 0x1023, "LO", "Digital Image Format Acquired" }, { 0x0018, 0x1030, "LO", "Protocol Name" }, { 0x0018, 0x1040, "LO", "Contrast/Bolus Route" }, { 0x0018, 0x1041, "DS", "Contrast/Bolus Volume" }, { 0x0018, 0x1042, "TM", "Contrast/Bolus Start Time" }, { 0x0018, 0x1043, "TM", "Contrast/Bolus Stop Time" }, { 0x0018, 0x1044, "DS", "Contrast/Bolus Total Dose" }, { 0x0018, 0x1045, "IS", "Syringe Counts" }, { 0x0018, 0x1046, "DS", "Contrast Flow Rate" }, { 0x0018, 0x1047, "DS", "Contrast Flow Duration" }, { 0x0018, 0x1048, "CS", "Contrast/Bolus Ingredient" }, { 0x0018, 0x1049, "DS", "Contrast/Bolus Ingredient Concentration" }, { 0x0018, 0x1050, "DS", "Spatial Resolution" }, { 0x0018, 0x1060, "DS", "Trigger Time" }, { 0x0018, 0x1061, "LO", "Trigger Source or Type" }, { 0x0018, 0x1062, "IS", "Nominal Interval" }, { 0x0018, 0x1063, "DS", "Frame Time" }, { 0x0018, 0x1064, "LO", "Framing Type" }, { 0x0018, 0x1065, "DS", "Frame Time Vector" }, { 0x0018, 0x1066, "DS", "Frame Delay" }, { 0x0018, 0x1067, "DS", "Image Trigger Delay" }, { 0x0018, 0x1068, "DS", "Group Time Offset" }, { 0x0018, 0x1069, "DS", "Trigger Time Offset" }, { 0x0018, 0x106a, "CS", "Synchronization Trigger" }, { 0x0018, 0x106b, "UI", "Synchronization Frame of Reference" }, { 0x0018, 0x106e, "UL", "Trigger Sample Position" }, { 0x0018, 0x1070, "LO", "Radiopharmaceutical Route" }, { 0x0018, 0x1071, "DS", "Radiopharmaceutical Volume" }, { 0x0018, 0x1072, "TM", "Radiopharmaceutical Start Time" }, { 0x0018, 0x1073, "TM", "Radiopharmaceutical Stop Time" }, { 0x0018, 0x1074, "DS", "Radionuclide Total Dose" }, { 0x0018, 0x1075, "DS", "Radionuclide Half Life" }, { 0x0018, 0x1076, "DS", "Radionuclide Positron Fraction" }, { 0x0018, 0x1077, "DS", "Radiopharmaceutical Specific Activity" }, { 0x0018, 0x1080, "CS", "Beat Rejection Flag" }, { 0x0018, 0x1081, "IS", "Low R-R Value" }, { 0x0018, 0x1082, "IS", "High R-R Value" }, { 0x0018, 0x1083, "IS", "Intervals Acquired" }, { 0x0018, 0x1084, "IS", "Intervals Rejected" }, { 0x0018, 0x1085, "LO", "PVC Rejection" }, { 0x0018, 0x1086, "IS", "Skip Beats" }, { 0x0018, 0x1088, "IS", "Heart Rate" }, { 0x0018, 0x1090, "IS", "Cardiac Number of Images" }, { 0x0018, 0x1094, "IS", "Trigger Window" }, { 0x0018, 0x1100, "DS", "Reconstruction Diameter" }, { 0x0018, 0x1110, "DS", "Distance Source to Detector" }, { 0x0018, 0x1111, "DS", "Distance Source to Patient" }, { 0x0018, 0x1114, "DS", "Estimated Radiographic Magnification Factor" }, { 0x0018, 0x1120, "DS", "Gantry/Detector Tilt" }, { 0x0018, 0x1121, "DS", "Gantry/Detector Slew" }, { 0x0018, 0x1130, "DS", "Table Height" }, { 0x0018, 0x1131, "DS", "Table Traverse" }, { 0x0018, 0x1134, "CS", "Table Motion" }, { 0x0018, 0x1135, "DS", "Table Vertical Increment" }, { 0x0018, 0x1136, "DS", "Table Lateral Increment" }, { 0x0018, 0x1137, "DS", "Table Longitudinal Increment" }, { 0x0018, 0x1138, "DS", "Table Angle" }, { 0x0018, 0x113a, "CS", "Table Type" }, { 0x0018, 0x1140, "CS", "Rotation Direction" }, { 0x0018, 0x1141, "DS", "Angular Position" }, { 0x0018, 0x1142, "DS", "Radial Position" }, { 0x0018, 0x1143, "DS", "Scan Arc" }, { 0x0018, 0x1144, "DS", "Angular Step" }, { 0x0018, 0x1145, "DS", "Center of Rotation Offset" }, { 0x0018, 0x1146, "DS", "Rotation Offset" }, { 0x0018, 0x1147, "CS", "Field of View Shape" }, { 0x0018, 0x1149, "IS", "Field of View Dimension(s)" }, { 0x0018, 0x1150, "IS", "Exposure Time" }, { 0x0018, 0x1151, "IS", "X-ray Tube Current" }, { 0x0018, 0x1152, "IS", "Exposure" }, { 0x0018, 0x1153, "IS", "Exposure in uAs" }, { 0x0018, 0x1154, "DS", "AveragePulseWidth" }, { 0x0018, 0x1155, "CS", "RadiationSetting" }, { 0x0018, 0x1156, "CS", "Rectification Type" }, { 0x0018, 0x115a, "CS", "RadiationMode" }, { 0x0018, 0x115e, "DS", "ImageAreaDoseProduct" }, { 0x0018, 0x1160, "SH", "Filter Type" }, { 0x0018, 0x1161, "LO", "TypeOfFilters" }, { 0x0018, 0x1162, "DS", "IntensifierSize" }, { 0x0018, 0x1164, "DS", "ImagerPixelSpacing" }, { 0x0018, 0x1166, "CS", "Grid" }, { 0x0018, 0x1170, "IS", "Generator Power" }, { 0x0018, 0x1180, "SH", "Collimator/Grid Name" }, { 0x0018, 0x1181, "CS", "Collimator Type" }, { 0x0018, 0x1182, "IS", "Focal Distance" }, { 0x0018, 0x1183, "DS", "X Focus Center" }, { 0x0018, 0x1184, "DS", "Y Focus Center" }, { 0x0018, 0x1190, "DS", "Focal Spot(s)" }, { 0x0018, 0x1191, "CS", "Anode Target Material" }, { 0x0018, 0x11a0, "DS", "Body Part Thickness" }, { 0x0018, 0x11a2, "DS", "Compression Force" }, { 0x0018, 0x1200, "DA", "Date of Last Calibration" }, { 0x0018, 0x1201, "TM", "Time of Last Calibration" }, { 0x0018, 0x1210, "SH", "Convolution Kernel" }, { 0x0018, 0x1240, "IS", "Upper/Lower Pixel Values" }, { 0x0018, 0x1242, "IS", "Actual Frame Duration" }, { 0x0018, 0x1243, "IS", "Count Rate" }, { 0x0018, 0x1244, "US", "Preferred Playback Sequencing" }, { 0x0018, 0x1250, "SH", "Receiving Coil" }, { 0x0018, 0x1251, "SH", "Transmitting Coil" }, { 0x0018, 0x1260, "SH", "Plate Type" }, { 0x0018, 0x1261, "LO", "Phosphor Type" }, { 0x0018, 0x1300, "DS", "Scan Velocity" }, { 0x0018, 0x1301, "CS", "Whole Body Technique" }, { 0x0018, 0x1302, "IS", "Scan Length" }, { 0x0018, 0x1310, "US", "Acquisition Matrix" }, { 0x0018, 0x1312, "CS", "Phase Encoding Direction" }, { 0x0018, 0x1314, "DS", "Flip Angle" }, { 0x0018, 0x1315, "CS", "Variable Flip Angle Flag" }, { 0x0018, 0x1316, "DS", "SAR" }, { 0x0018, 0x1318, "DS", "dB/dt" }, { 0x0018, 0x1400, "LO", "Acquisition Device Processing Description" }, { 0x0018, 0x1401, "LO", "Acquisition Device Processing Code" }, { 0x0018, 0x1402, "CS", "Cassette Orientation" }, { 0x0018, 0x1403, "CS", "Cassette Size" }, { 0x0018, 0x1404, "US", "Exposures on Plate" }, { 0x0018, 0x1405, "IS", "Relative X-ray Exposure" }, { 0x0018, 0x1450, "DS", "Column Angulation" }, { 0x0018, 0x1460, "DS", "Tomo Layer Height" }, { 0x0018, 0x1470, "DS", "Tomo Angle" }, { 0x0018, 0x1480, "DS", "Tomo Time" }, { 0x0018, 0x1490, "CS", "Tomo Type" }, { 0x0018, 0x1491, "CS", "Tomo Class" }, { 0x0018, 0x1495, "IS", "Number of Tomosynthesis Source Images" }, { 0x0018, 0x1500, "CS", "PositionerMotion" }, { 0x0018, 0x1508, "CS", "Positioner Type" }, { 0x0018, 0x1510, "DS", "PositionerPrimaryAngle" }, { 0x0018, 0x1511, "DS", "PositionerSecondaryAngle" }, { 0x0018, 0x1520, "DS", "PositionerPrimaryAngleIncrement" }, { 0x0018, 0x1521, "DS", "PositionerSecondaryAngleIncrement" }, { 0x0018, 0x1530, "DS", "DetectorPrimaryAngle" }, { 0x0018, 0x1531, "DS", "DetectorSecondaryAngle" }, { 0x0018, 0x1600, "CS", "Shutter Shape" }, { 0x0018, 0x1602, "IS", "Shutter Left Vertical Edge" }, { 0x0018, 0x1604, "IS", "Shutter Right Vertical Edge" }, { 0x0018, 0x1606, "IS", "Shutter Upper Horizontal Edge" }, { 0x0018, 0x1608, "IS", "Shutter Lower Horizonta lEdge" }, { 0x0018, 0x1610, "IS", "Center of Circular Shutter" }, { 0x0018, 0x1612, "IS", "Radius of Circular Shutter" }, { 0x0018, 0x1620, "IS", "Vertices of Polygonal Shutter" }, { 0x0018, 0x1622, "US", "Shutter Presentation Value" }, { 0x0018, 0x1623, "US", "Shutter Overlay Group" }, { 0x0018, 0x1700, "CS", "Collimator Shape" }, { 0x0018, 0x1702, "IS", "Collimator Left Vertical Edge" }, { 0x0018, 0x1704, "IS", "Collimator Right Vertical Edge" }, { 0x0018, 0x1706, "IS", "Collimator Upper Horizontal Edge" }, { 0x0018, 0x1708, "IS", "Collimator Lower Horizontal Edge" }, { 0x0018, 0x1710, "IS", "Center of Circular Collimator" }, { 0x0018, 0x1712, "IS", "Radius of Circular Collimator" }, { 0x0018, 0x1720, "IS", "Vertices of Polygonal Collimator" }, { 0x0018, 0x1800, "CS", "Acquisition Time Synchronized" }, { 0x0018, 0x1801, "SH", "Time Source" }, { 0x0018, 0x1802, "CS", "Time Distribution Protocol" }, { 0x0018, 0x4000, "LT", "Acquisition Comments" }, { 0x0018, 0x5000, "SH", "Output Power" }, { 0x0018, 0x5010, "LO", "Transducer Data" }, { 0x0018, 0x5012, "DS", "Focus Depth" }, { 0x0018, 0x5020, "LO", "Processing Function" }, { 0x0018, 0x5021, "LO", "Postprocessing Function" }, { 0x0018, 0x5022, "DS", "Mechanical Index" }, { 0x0018, 0x5024, "DS", "Thermal Index" }, { 0x0018, 0x5026, "DS", "Cranial Thermal Index" }, { 0x0018, 0x5027, "DS", "Soft Tissue Thermal Index" }, { 0x0018, 0x5028, "DS", "Soft Tissue-Focus Thermal Index" }, { 0x0018, 0x5029, "DS", "Soft Tissue-Surface Thermal Index" }, { 0x0018, 0x5030, "DS", "Dynamic Range" }, { 0x0018, 0x5040, "DS", "Total Gain" }, { 0x0018, 0x5050, "IS", "Depth of Scan Field" }, { 0x0018, 0x5100, "CS", "Patient Position" }, { 0x0018, 0x5101, "CS", "View Position" }, { 0x0018, 0x5104, "SQ", "Projection Eponymous Name Code Sequence" }, { 0x0018, 0x5210, "DS", "Image Transformation Matrix" }, { 0x0018, 0x5212, "DS", "Image Translation Vector" }, { 0x0018, 0x6000, "DS", "Sensitivity" }, { 0x0018, 0x6011, "IS", "Sequence of Ultrasound Regions" }, { 0x0018, 0x6012, "US", "Region Spatial Format" }, { 0x0018, 0x6014, "US", "Region Data Type" }, { 0x0018, 0x6016, "UL", "Region Flags" }, { 0x0018, 0x6018, "UL", "Region Location Min X0" }, { 0x0018, 0x601a, "UL", "Region Location Min Y0" }, { 0x0018, 0x601c, "UL", "Region Location Max X1" }, { 0x0018, 0x601e, "UL", "Region Location Max Y1" }, { 0x0018, 0x6020, "SL", "Reference Pixel X0" }, { 0x0018, 0x6022, "SL", "Reference Pixel Y0" }, { 0x0018, 0x6024, "US", "Physical Units X Direction" }, { 0x0018, 0x6026, "US", "Physical Units Y Direction" }, { 0x0018, 0x6028, "FD", "Reference Pixel Physical Value X" }, { 0x0018, 0x602a, "US", "Reference Pixel Physical Value Y" }, { 0x0018, 0x602c, "US", "Physical Delta X" }, { 0x0018, 0x602e, "US", "Physical Delta Y" }, { 0x0018, 0x6030, "UL", "Transducer Frequency" }, { 0x0018, 0x6031, "CS", "Transducer Type" }, { 0x0018, 0x6032, "UL", "Pulse Repetition Frequency" }, { 0x0018, 0x6034, "FD", "Doppler Correction Angle" }, { 0x0018, 0x6036, "FD", "Steering Angle" }, { 0x0018, 0x6038, "UL", "Doppler Sample Volume X Position" }, { 0x0018, 0x603a, "UL", "Doppler Sample Volume Y Position" }, { 0x0018, 0x603c, "UL", "TM-Line Position X0" }, { 0x0018, 0x603e, "UL", "TM-Line Position Y0" }, { 0x0018, 0x6040, "UL", "TM-Line Position X1" }, { 0x0018, 0x6042, "UL", "TM-Line Position Y1" }, { 0x0018, 0x6044, "US", "Pixel Component Organization" }, { 0x0018, 0x6046, "UL", "Pixel Component Mask" }, { 0x0018, 0x6048, "UL", "Pixel Component Range Start" }, { 0x0018, 0x604a, "UL", "Pixel Component Range Stop" }, { 0x0018, 0x604c, "US", "Pixel Component Physical Units" }, { 0x0018, 0x604e, "US", "Pixel Component Data Type" }, { 0x0018, 0x6050, "UL", "Number of Table Break Points" }, { 0x0018, 0x6052, "UL", "Table of X Break Points" }, { 0x0018, 0x6054, "FD", "Table of Y Break Points" }, { 0x0018, 0x6056, "UL", "Number of Table Entries" }, { 0x0018, 0x6058, "UL", "Table of Pixel Values" }, { 0x0018, 0x605a, "FL", "Table of Parameter Values" }, { 0x0018, 0x7000, "CS", "Detector Conditions Nominal Flag" }, { 0x0018, 0x7001, "DS", "Detector Temperature" }, { 0x0018, 0x7004, "CS", "Detector Type" }, { 0x0018, 0x7005, "CS", "Detector Configuration" }, { 0x0018, 0x7006, "LT", "Detector Description" }, { 0x0018, 0x7008, "LT", "Detector Mode" }, { 0x0018, 0x700a, "SH", "Detector ID" }, { 0x0018, 0x700c, "DA", "Date of Last Detector Calibration " }, { 0x0018, 0x700e, "TM", "Time of Last Detector Calibration" }, { 0x0018, 0x7010, "IS", "Exposures on Detector Since Last Calibration" }, { 0x0018, 0x7011, "IS", "Exposures on Detector Since Manufactured" }, { 0x0018, 0x7012, "DS", "Detector Time Since Last Exposure" }, { 0x0018, 0x7014, "DS", "Detector Active Time" }, { 0x0018, 0x7016, "DS", "Detector Activation Offset From Exposure" }, { 0x0018, 0x701a, "DS", "Detector Binning" }, { 0x0018, 0x7020, "DS", "Detector Element Physical Size" }, { 0x0018, 0x7022, "DS", "Detector Element Spacing" }, { 0x0018, 0x7024, "CS", "Detector Active Shape" }, { 0x0018, 0x7026, "DS", "Detector Active Dimensions" }, { 0x0018, 0x7028, "DS", "Detector Active Origin" }, { 0x0018, 0x7030, "DS", "Field of View Origin" }, { 0x0018, 0x7032, "DS", "Field of View Rotation" }, { 0x0018, 0x7034, "CS", "Field of View Horizontal Flip" }, { 0x0018, 0x7040, "LT", "Grid Absorbing Material" }, { 0x0018, 0x7041, "LT", "Grid Spacing Material" }, { 0x0018, 0x7042, "DS", "Grid Thickness" }, { 0x0018, 0x7044, "DS", "Grid Pitch" }, { 0x0018, 0x7046, "IS", "Grid Aspect Ratio" }, { 0x0018, 0x7048, "DS", "Grid Period" }, { 0x0018, 0x704c, "DS", "Grid Focal Distance" }, { 0x0018, 0x7050, "LT", "Filter Material" }, { 0x0018, 0x7052, "DS", "Filter Thickness Minimum" }, { 0x0018, 0x7054, "DS", "Filter Thickness Maximum" }, { 0x0018, 0x7060, "CS", "Exposure Control Mode" }, { 0x0018, 0x7062, "LT", "Exposure Control Mode Description" }, { 0x0018, 0x7064, "CS", "Exposure Status" }, { 0x0018, 0x7065, "DS", "Phototimer Setting" }, { 0x0019, 0x0000, "xs", "?" }, { 0x0019, 0x0001, "xs", "?" }, { 0x0019, 0x0002, "xs", "?" }, { 0x0019, 0x0003, "xs", "?" }, { 0x0019, 0x0004, "xs", "?" }, { 0x0019, 0x0005, "xs", "?" }, { 0x0019, 0x0006, "xs", "?" }, { 0x0019, 0x0007, "xs", "?" }, { 0x0019, 0x0008, "xs", "?" }, { 0x0019, 0x0009, "xs", "?" }, { 0x0019, 0x000a, "xs", "?" }, { 0x0019, 0x000b, "DS", "?" }, { 0x0019, 0x000c, "US", "?" }, { 0x0019, 0x000d, "TM", "Time" }, { 0x0019, 0x000e, "xs", "?" }, { 0x0019, 0x000f, "DS", "Horizontal Frame Of Reference" }, { 0x0019, 0x0010, "xs", "?" }, { 0x0019, 0x0011, "xs", "?" }, { 0x0019, 0x0012, "xs", "?" }, { 0x0019, 0x0013, "xs", "?" }, { 0x0019, 0x0014, "xs", "?" }, { 0x0019, 0x0015, "xs", "?" }, { 0x0019, 0x0016, "xs", "?" }, { 0x0019, 0x0017, "xs", "?" }, { 0x0019, 0x0018, "xs", "?" }, { 0x0019, 0x0019, "xs", "?" }, { 0x0019, 0x001a, "xs", "?" }, { 0x0019, 0x001b, "xs", "?" }, { 0x0019, 0x001c, "CS", "Dose" }, { 0x0019, 0x001d, "IS", "Side Mark" }, { 0x0019, 0x001e, "xs", "?" }, { 0x0019, 0x001f, "DS", "Exposure Duration" }, { 0x0019, 0x0020, "xs", "?" }, { 0x0019, 0x0021, "xs", "?" }, { 0x0019, 0x0022, "xs", "?" }, { 0x0019, 0x0023, "xs", "?" }, { 0x0019, 0x0024, "xs", "?" }, { 0x0019, 0x0025, "xs", "?" }, { 0x0019, 0x0026, "xs", "?" }, { 0x0019, 0x0027, "xs", "?" }, { 0x0019, 0x0028, "xs", "?" }, { 0x0019, 0x0029, "IS", "?" }, { 0x0019, 0x002a, "xs", "?" }, { 0x0019, 0x002b, "DS", "Xray Off Position" }, { 0x0019, 0x002c, "xs", "?" }, { 0x0019, 0x002d, "US", "?" }, { 0x0019, 0x002e, "xs", "?" }, { 0x0019, 0x002f, "DS", "Trigger Frequency" }, { 0x0019, 0x0030, "xs", "?" }, { 0x0019, 0x0031, "xs", "?" }, { 0x0019, 0x0032, "xs", "?" }, { 0x0019, 0x0033, "UN", "ECG 2 Offset 2" }, { 0x0019, 0x0034, "US", "?" }, { 0x0019, 0x0036, "US", "?" }, { 0x0019, 0x0038, "US", "?" }, { 0x0019, 0x0039, "xs", "?" }, { 0x0019, 0x003a, "xs", "?" }, { 0x0019, 0x003b, "LT", "?" }, { 0x0019, 0x003c, "xs", "?" }, { 0x0019, 0x003e, "xs", "?" }, { 0x0019, 0x003f, "UN", "?" }, { 0x0019, 0x0040, "xs", "?" }, { 0x0019, 0x0041, "xs", "?" }, { 0x0019, 0x0042, "xs", "?" }, { 0x0019, 0x0043, "xs", "?" }, { 0x0019, 0x0044, "xs", "?" }, { 0x0019, 0x0045, "xs", "?" }, { 0x0019, 0x0046, "xs", "?" }, { 0x0019, 0x0047, "xs", "?" }, { 0x0019, 0x0048, "xs", "?" }, { 0x0019, 0x0049, "US", "?" }, { 0x0019, 0x004a, "xs", "?" }, { 0x0019, 0x004b, "SL", "Data Size For Scan Data" }, { 0x0019, 0x004c, "US", "?" }, { 0x0019, 0x004e, "US", "?" }, { 0x0019, 0x0050, "xs", "?" }, { 0x0019, 0x0051, "xs", "?" }, { 0x0019, 0x0052, "xs", "?" }, { 0x0019, 0x0053, "LT", "Barcode" }, { 0x0019, 0x0054, "xs", "?" }, { 0x0019, 0x0055, "DS", "Receiver Reference Gain" }, { 0x0019, 0x0056, "xs", "?" }, { 0x0019, 0x0057, "SS", "CT Water Number" }, { 0x0019, 0x0058, "xs", "?" }, { 0x0019, 0x005a, "xs", "?" }, { 0x0019, 0x005c, "xs", "?" }, { 0x0019, 0x005d, "US", "?" }, { 0x0019, 0x005e, "xs", "?" }, { 0x0019, 0x005f, "SL", "Increment Between Channels" }, { 0x0019, 0x0060, "xs", "?" }, { 0x0019, 0x0061, "xs", "?" }, { 0x0019, 0x0062, "xs", "?" }, { 0x0019, 0x0063, "xs", "?" }, { 0x0019, 0x0064, "xs", "?" }, { 0x0019, 0x0065, "xs", "?" }, { 0x0019, 0x0066, "xs", "?" }, { 0x0019, 0x0067, "xs", "?" }, { 0x0019, 0x0068, "xs", "?" }, { 0x0019, 0x0069, "UL", "Convolution Mode" }, { 0x0019, 0x006a, "xs", "?" }, { 0x0019, 0x006b, "SS", "Field Of View In Detector Cells" }, { 0x0019, 0x006c, "US", "?" }, { 0x0019, 0x006e, "US", "?" }, { 0x0019, 0x0070, "xs", "?" }, { 0x0019, 0x0071, "xs", "?" }, { 0x0019, 0x0072, "xs", "?" }, { 0x0019, 0x0073, "xs", "?" }, { 0x0019, 0x0074, "xs", "?" }, { 0x0019, 0x0075, "xs", "?" }, { 0x0019, 0x0076, "xs", "?" }, { 0x0019, 0x0077, "US", "?" }, { 0x0019, 0x0078, "US", "?" }, { 0x0019, 0x007a, "US", "?" }, { 0x0019, 0x007c, "US", "?" }, { 0x0019, 0x007d, "DS", "Second Echo" }, { 0x0019, 0x007e, "xs", "?" }, { 0x0019, 0x007f, "DS", "Table Delta" }, { 0x0019, 0x0080, "xs", "?" }, { 0x0019, 0x0081, "xs", "?" }, { 0x0019, 0x0082, "xs", "?" }, { 0x0019, 0x0083, "xs", "?" }, { 0x0019, 0x0084, "xs", "?" }, { 0x0019, 0x0085, "xs", "?" }, { 0x0019, 0x0086, "xs", "?" }, { 0x0019, 0x0087, "xs", "?" }, { 0x0019, 0x0088, "xs", "?" }, { 0x0019, 0x008a, "xs", "?" }, { 0x0019, 0x008b, "SS", "Actual Receive Gain Digital" }, { 0x0019, 0x008c, "US", "?" }, { 0x0019, 0x008d, "DS", "Delay After Trigger" }, { 0x0019, 0x008e, "US", "?" }, { 0x0019, 0x008f, "SS", "Swap Phase Frequency" }, { 0x0019, 0x0090, "xs", "?" }, { 0x0019, 0x0091, "xs", "?" }, { 0x0019, 0x0092, "xs", "?" }, { 0x0019, 0x0093, "xs", "?" }, { 0x0019, 0x0094, "xs", "?" }, { 0x0019, 0x0095, "SS", "Analog Receiver Gain" }, { 0x0019, 0x0096, "xs", "?" }, { 0x0019, 0x0097, "xs", "?" }, { 0x0019, 0x0098, "xs", "?" }, { 0x0019, 0x0099, "US", "?" }, { 0x0019, 0x009a, "US", "?" }, { 0x0019, 0x009b, "SS", "Pulse Sequence Mode" }, { 0x0019, 0x009c, "xs", "?" }, { 0x0019, 0x009d, "DT", "Pulse Sequence Date" }, { 0x0019, 0x009e, "xs", "?" }, { 0x0019, 0x009f, "xs", "?" }, { 0x0019, 0x00a0, "xs", "?" }, { 0x0019, 0x00a1, "xs", "?" }, { 0x0019, 0x00a2, "xs", "?" }, { 0x0019, 0x00a3, "xs", "?" }, { 0x0019, 0x00a4, "xs", "?" }, { 0x0019, 0x00a5, "xs", "?" }, { 0x0019, 0x00a6, "xs", "?" }, { 0x0019, 0x00a7, "xs", "?" }, { 0x0019, 0x00a8, "xs", "?" }, { 0x0019, 0x00a9, "xs", "?" }, { 0x0019, 0x00aa, "xs", "?" }, { 0x0019, 0x00ab, "xs", "?" }, { 0x0019, 0x00ac, "xs", "?" }, { 0x0019, 0x00ad, "xs", "?" }, { 0x0019, 0x00ae, "xs", "?" }, { 0x0019, 0x00af, "xs", "?" }, { 0x0019, 0x00b0, "xs", "?" }, { 0x0019, 0x00b1, "xs", "?" }, { 0x0019, 0x00b2, "xs", "?" }, { 0x0019, 0x00b3, "xs", "?" }, { 0x0019, 0x00b4, "xs", "?" }, { 0x0019, 0x00b5, "xs", "?" }, { 0x0019, 0x00b6, "DS", "User Data" }, { 0x0019, 0x00b7, "DS", "User Data" }, { 0x0019, 0x00b8, "DS", "User Data" }, { 0x0019, 0x00b9, "DS", "User Data" }, { 0x0019, 0x00ba, "DS", "User Data" }, { 0x0019, 0x00bb, "DS", "User Data" }, { 0x0019, 0x00bc, "DS", "User Data" }, { 0x0019, 0x00bd, "DS", "User Data" }, { 0x0019, 0x00be, "DS", "Projection Angle" }, { 0x0019, 0x00c0, "xs", "?" }, { 0x0019, 0x00c1, "xs", "?" }, { 0x0019, 0x00c2, "xs", "?" }, { 0x0019, 0x00c3, "xs", "?" }, { 0x0019, 0x00c4, "xs", "?" }, { 0x0019, 0x00c5, "xs", "?" }, { 0x0019, 0x00c6, "SS", "SAT Location H" }, { 0x0019, 0x00c7, "SS", "SAT Location F" }, { 0x0019, 0x00c8, "SS", "SAT Thickness R L" }, { 0x0019, 0x00c9, "SS", "SAT Thickness A P" }, { 0x0019, 0x00ca, "SS", "SAT Thickness H F" }, { 0x0019, 0x00cb, "xs", "?" }, { 0x0019, 0x00cc, "xs", "?" }, { 0x0019, 0x00cd, "SS", "Thickness Disclaimer" }, { 0x0019, 0x00ce, "SS", "Prescan Type" }, { 0x0019, 0x00cf, "SS", "Prescan Status" }, { 0x0019, 0x00d0, "SH", "Raw Data Type" }, { 0x0019, 0x00d1, "DS", "Flow Sensitivity" }, { 0x0019, 0x00d2, "xs", "?" }, { 0x0019, 0x00d3, "xs", "?" }, { 0x0019, 0x00d4, "xs", "?" }, { 0x0019, 0x00d5, "xs", "?" }, { 0x0019, 0x00d6, "xs", "?" }, { 0x0019, 0x00d7, "xs", "?" }, { 0x0019, 0x00d8, "xs", "?" }, { 0x0019, 0x00d9, "xs", "?" }, { 0x0019, 0x00da, "xs", "?" }, { 0x0019, 0x00db, "DS", "Back Projector Coefficient" }, { 0x0019, 0x00dc, "SS", "Primary Speed Correction Used" }, { 0x0019, 0x00dd, "SS", "Overrange Correction Used" }, { 0x0019, 0x00de, "DS", "Dynamic Z Alpha Value" }, { 0x0019, 0x00df, "DS", "User Data" }, { 0x0019, 0x00e0, "DS", "User Data" }, { 0x0019, 0x00e1, "xs", "?" }, { 0x0019, 0x00e2, "xs", "?" }, { 0x0019, 0x00e3, "xs", "?" }, { 0x0019, 0x00e4, "LT", "?" }, { 0x0019, 0x00e5, "IS", "?" }, { 0x0019, 0x00e6, "US", "?" }, { 0x0019, 0x00e8, "DS", "?" }, { 0x0019, 0x00e9, "DS", "?" }, { 0x0019, 0x00eb, "DS", "?" }, { 0x0019, 0x00ec, "US", "?" }, { 0x0019, 0x00f0, "xs", "?" }, { 0x0019, 0x00f1, "xs", "?" }, { 0x0019, 0x00f2, "xs", "?" }, { 0x0019, 0x00f3, "xs", "?" }, { 0x0019, 0x00f4, "LT", "?" }, { 0x0019, 0x00f9, "DS", "Transmission Gain" }, { 0x0019, 0x1015, "UN", "?" }, { 0x0020, 0x0000, "UL", "Relationship Group Length" }, { 0x0020, 0x000d, "UI", "Study Instance UID" }, { 0x0020, 0x000e, "UI", "Series Instance UID" }, { 0x0020, 0x0010, "SH", "Study ID" }, { 0x0020, 0x0011, "IS", "Series Number" }, { 0x0020, 0x0012, "IS", "Acquisition Number" }, { 0x0020, 0x0013, "IS", "Instance (formerly Image) Number" }, { 0x0020, 0x0014, "IS", "Isotope Number" }, { 0x0020, 0x0015, "IS", "Phase Number" }, { 0x0020, 0x0016, "IS", "Interval Number" }, { 0x0020, 0x0017, "IS", "Time Slot Number" }, { 0x0020, 0x0018, "IS", "Angle Number" }, { 0x0020, 0x0020, "CS", "Patient Orientation" }, { 0x0020, 0x0022, "IS", "Overlay Number" }, { 0x0020, 0x0024, "IS", "Curve Number" }, { 0x0020, 0x0026, "IS", "LUT Number" }, { 0x0020, 0x0030, "DS", "Image Position" }, { 0x0020, 0x0032, "DS", "Image Position (Patient)" }, { 0x0020, 0x0035, "DS", "Image Orientation" }, { 0x0020, 0x0037, "DS", "Image Orientation (Patient)" }, { 0x0020, 0x0050, "DS", "Location" }, { 0x0020, 0x0052, "UI", "Frame of Reference UID" }, { 0x0020, 0x0060, "CS", "Laterality" }, { 0x0020, 0x0062, "CS", "Image Laterality" }, { 0x0020, 0x0070, "LT", "Image Geometry Type" }, { 0x0020, 0x0080, "LO", "Masking Image" }, { 0x0020, 0x0100, "IS", "Temporal Position Identifier" }, { 0x0020, 0x0105, "IS", "Number of Temporal Positions" }, { 0x0020, 0x0110, "DS", "Temporal Resolution" }, { 0x0020, 0x1000, "IS", "Series in Study" }, { 0x0020, 0x1001, "DS", "Acquisitions in Series" }, { 0x0020, 0x1002, "IS", "Images in Acquisition" }, { 0x0020, 0x1003, "IS", "Images in Series" }, { 0x0020, 0x1004, "IS", "Acquisitions in Study" }, { 0x0020, 0x1005, "IS", "Images in Study" }, { 0x0020, 0x1020, "LO", "Reference" }, { 0x0020, 0x1040, "LO", "Position Reference Indicator" }, { 0x0020, 0x1041, "DS", "Slice Location" }, { 0x0020, 0x1070, "IS", "Other Study Numbers" }, { 0x0020, 0x1200, "IS", "Number of Patient Related Studies" }, { 0x0020, 0x1202, "IS", "Number of Patient Related Series" }, { 0x0020, 0x1204, "IS", "Number of Patient Related Images" }, { 0x0020, 0x1206, "IS", "Number of Study Related Series" }, { 0x0020, 0x1208, "IS", "Number of Study Related Series" }, { 0x0020, 0x3100, "LO", "Source Image IDs" }, { 0x0020, 0x3401, "LO", "Modifying Device ID" }, { 0x0020, 0x3402, "LO", "Modified Image ID" }, { 0x0020, 0x3403, "xs", "Modified Image Date" }, { 0x0020, 0x3404, "LO", "Modifying Device Manufacturer" }, { 0x0020, 0x3405, "xs", "Modified Image Time" }, { 0x0020, 0x3406, "xs", "Modified Image Description" }, { 0x0020, 0x4000, "LT", "Image Comments" }, { 0x0020, 0x5000, "AT", "Original Image Identification" }, { 0x0020, 0x5002, "LO", "Original Image Identification Nomenclature" }, { 0x0021, 0x0000, "xs", "?" }, { 0x0021, 0x0001, "xs", "?" }, { 0x0021, 0x0002, "xs", "?" }, { 0x0021, 0x0003, "xs", "?" }, { 0x0021, 0x0004, "DS", "VOI Position" }, { 0x0021, 0x0005, "xs", "?" }, { 0x0021, 0x0006, "IS", "CSI Matrix Size Original" }, { 0x0021, 0x0007, "xs", "?" }, { 0x0021, 0x0008, "DS", "Spatial Grid Shift" }, { 0x0021, 0x0009, "DS", "Signal Limits Minimum" }, { 0x0021, 0x0010, "xs", "?" }, { 0x0021, 0x0011, "xs", "?" }, { 0x0021, 0x0012, "xs", "?" }, { 0x0021, 0x0013, "xs", "?" }, { 0x0021, 0x0014, "xs", "?" }, { 0x0021, 0x0015, "xs", "?" }, { 0x0021, 0x0016, "xs", "?" }, { 0x0021, 0x0017, "DS", "EPI Operation Mode Flag" }, { 0x0021, 0x0018, "xs", "?" }, { 0x0021, 0x0019, "xs", "?" }, { 0x0021, 0x0020, "xs", "?" }, { 0x0021, 0x0021, "xs", "?" }, { 0x0021, 0x0022, "xs", "?" }, { 0x0021, 0x0024, "xs", "?" }, { 0x0021, 0x0025, "US", "?" }, { 0x0021, 0x0026, "IS", "Image Pixel Offset" }, { 0x0021, 0x0030, "xs", "?" }, { 0x0021, 0x0031, "xs", "?" }, { 0x0021, 0x0032, "xs", "?" }, { 0x0021, 0x0034, "xs", "?" }, { 0x0021, 0x0035, "SS", "Series From Which Prescribed" }, { 0x0021, 0x0036, "xs", "?" }, { 0x0021, 0x0037, "SS", "Screen Format" }, { 0x0021, 0x0039, "DS", "Slab Thickness" }, { 0x0021, 0x0040, "xs", "?" }, { 0x0021, 0x0041, "xs", "?" }, { 0x0021, 0x0042, "xs", "?" }, { 0x0021, 0x0043, "xs", "?" }, { 0x0021, 0x0044, "xs", "?" }, { 0x0021, 0x0045, "xs", "?" }, { 0x0021, 0x0046, "xs", "?" }, { 0x0021, 0x0047, "xs", "?" }, { 0x0021, 0x0048, "xs", "?" }, { 0x0021, 0x0049, "xs", "?" }, { 0x0021, 0x004a, "xs", "?" }, { 0x0021, 0x004e, "US", "?" }, { 0x0021, 0x004f, "xs", "?" }, { 0x0021, 0x0050, "xs", "?" }, { 0x0021, 0x0051, "xs", "?" }, { 0x0021, 0x0052, "xs", "?" }, { 0x0021, 0x0053, "xs", "?" }, { 0x0021, 0x0054, "xs", "?" }, { 0x0021, 0x0055, "xs", "?" }, { 0x0021, 0x0056, "xs", "?" }, { 0x0021, 0x0057, "xs", "?" }, { 0x0021, 0x0058, "xs", "?" }, { 0x0021, 0x0059, "xs", "?" }, { 0x0021, 0x005a, "SL", "Integer Slop" }, { 0x0021, 0x005b, "DS", "Float Slop" }, { 0x0021, 0x005c, "DS", "Float Slop" }, { 0x0021, 0x005d, "DS", "Float Slop" }, { 0x0021, 0x005e, "DS", "Float Slop" }, { 0x0021, 0x005f, "DS", "Float Slop" }, { 0x0021, 0x0060, "xs", "?" }, { 0x0021, 0x0061, "DS", "Image Normal" }, { 0x0021, 0x0062, "IS", "Reference Type Code" }, { 0x0021, 0x0063, "DS", "Image Distance" }, { 0x0021, 0x0065, "US", "Image Positioning History Mask" }, { 0x0021, 0x006a, "DS", "Image Row" }, { 0x0021, 0x006b, "DS", "Image Column" }, { 0x0021, 0x0070, "xs", "?" }, { 0x0021, 0x0071, "xs", "?" }, { 0x0021, 0x0072, "xs", "?" }, { 0x0021, 0x0073, "DS", "Second Repetition Time" }, { 0x0021, 0x0075, "DS", "Light Brightness" }, { 0x0021, 0x0076, "DS", "Light Contrast" }, { 0x0021, 0x007a, "IS", "Overlay Threshold" }, { 0x0021, 0x007b, "IS", "Surface Threshold" }, { 0x0021, 0x007c, "IS", "Grey Scale Threshold" }, { 0x0021, 0x0080, "xs", "?" }, { 0x0021, 0x0081, "DS", "Auto Window Level Alpha" }, { 0x0021, 0x0082, "xs", "?" }, { 0x0021, 0x0083, "DS", "Auto Window Level Window" }, { 0x0021, 0x0084, "DS", "Auto Window Level Level" }, { 0x0021, 0x0090, "xs", "?" }, { 0x0021, 0x0091, "xs", "?" }, { 0x0021, 0x0092, "xs", "?" }, { 0x0021, 0x0093, "xs", "?" }, { 0x0021, 0x0094, "DS", "EPI Change Value of X Component" }, { 0x0021, 0x0095, "DS", "EPI Change Value of Y Component" }, { 0x0021, 0x0096, "DS", "EPI Change Value of Z Component" }, { 0x0021, 0x00a0, "xs", "?" }, { 0x0021, 0x00a1, "DS", "?" }, { 0x0021, 0x00a2, "xs", "?" }, { 0x0021, 0x00a3, "LT", "?" }, { 0x0021, 0x00a4, "LT", "?" }, { 0x0021, 0x00a7, "LT", "?" }, { 0x0021, 0x00b0, "IS", "?" }, { 0x0021, 0x00c0, "IS", "?" }, { 0x0023, 0x0000, "xs", "?" }, { 0x0023, 0x0001, "SL", "Number Of Series In Study" }, { 0x0023, 0x0002, "SL", "Number Of Unarchived Series" }, { 0x0023, 0x0010, "xs", "?" }, { 0x0023, 0x0020, "xs", "?" }, { 0x0023, 0x0030, "xs", "?" }, { 0x0023, 0x0040, "xs", "?" }, { 0x0023, 0x0050, "xs", "?" }, { 0x0023, 0x0060, "xs", "?" }, { 0x0023, 0x0070, "xs", "?" }, { 0x0023, 0x0074, "SL", "Number Of Updates To Info" }, { 0x0023, 0x007d, "SS", "Indicates If Study Has Complete Info" }, { 0x0023, 0x0080, "xs", "?" }, { 0x0023, 0x0090, "xs", "?" }, { 0x0023, 0x00ff, "US", "?" }, { 0x0025, 0x0000, "UL", "Group Length" }, { 0x0025, 0x0006, "SS", "Last Pulse Sequence Used" }, { 0x0025, 0x0007, "SL", "Images In Series" }, { 0x0025, 0x0010, "SS", "Landmark Counter" }, { 0x0025, 0x0011, "SS", "Number Of Acquisitions" }, { 0x0025, 0x0014, "SL", "Indicates Number Of Updates To Info" }, { 0x0025, 0x0017, "SL", "Series Complete Flag" }, { 0x0025, 0x0018, "SL", "Number Of Images Archived" }, { 0x0025, 0x0019, "SL", "Last Image Number Used" }, { 0x0025, 0x001a, "SH", "Primary Receiver Suite And Host" }, { 0x0027, 0x0000, "US", "?" }, { 0x0027, 0x0006, "SL", "Image Archive Flag" }, { 0x0027, 0x0010, "SS", "Scout Type" }, { 0x0027, 0x0011, "UN", "?" }, { 0x0027, 0x0012, "IS", "?" }, { 0x0027, 0x0013, "IS", "?" }, { 0x0027, 0x0014, "IS", "?" }, { 0x0027, 0x0015, "IS", "?" }, { 0x0027, 0x0016, "LT", "?" }, { 0x0027, 0x001c, "SL", "Vma Mamp" }, { 0x0027, 0x001d, "SS", "Vma Phase" }, { 0x0027, 0x001e, "SL", "Vma Mod" }, { 0x0027, 0x001f, "SL", "Vma Clip" }, { 0x0027, 0x0020, "SS", "Smart Scan On Off Flag" }, { 0x0027, 0x0030, "SH", "Foreign Image Revision" }, { 0x0027, 0x0031, "SS", "Imaging Mode" }, { 0x0027, 0x0032, "SS", "Pulse Sequence" }, { 0x0027, 0x0033, "SL", "Imaging Options" }, { 0x0027, 0x0035, "SS", "Plane Type" }, { 0x0027, 0x0036, "SL", "Oblique Plane" }, { 0x0027, 0x0040, "SH", "RAS Letter Of Image Location" }, { 0x0027, 0x0041, "FL", "Image Location" }, { 0x0027, 0x0042, "FL", "Center R Coord Of Plane Image" }, { 0x0027, 0x0043, "FL", "Center A Coord Of Plane Image" }, { 0x0027, 0x0044, "FL", "Center S Coord Of Plane Image" }, { 0x0027, 0x0045, "FL", "Normal R Coord" }, { 0x0027, 0x0046, "FL", "Normal A Coord" }, { 0x0027, 0x0047, "FL", "Normal S Coord" }, { 0x0027, 0x0048, "FL", "R Coord Of Top Right Corner" }, { 0x0027, 0x0049, "FL", "A Coord Of Top Right Corner" }, { 0x0027, 0x004a, "FL", "S Coord Of Top Right Corner" }, { 0x0027, 0x004b, "FL", "R Coord Of Bottom Right Corner" }, { 0x0027, 0x004c, "FL", "A Coord Of Bottom Right Corner" }, { 0x0027, 0x004d, "FL", "S Coord Of Bottom Right Corner" }, { 0x0027, 0x0050, "FL", "Table Start Location" }, { 0x0027, 0x0051, "FL", "Table End Location" }, { 0x0027, 0x0052, "SH", "RAS Letter For Side Of Image" }, { 0x0027, 0x0053, "SH", "RAS Letter For Anterior Posterior" }, { 0x0027, 0x0054, "SH", "RAS Letter For Scout Start Loc" }, { 0x0027, 0x0055, "SH", "RAS Letter For Scout End Loc" }, { 0x0027, 0x0060, "FL", "Image Dimension X" }, { 0x0027, 0x0061, "FL", "Image Dimension Y" }, { 0x0027, 0x0062, "FL", "Number Of Excitations" }, { 0x0028, 0x0000, "UL", "Image Presentation Group Length" }, { 0x0028, 0x0002, "US", "Samples per Pixel" }, { 0x0028, 0x0004, "CS", "Photometric Interpretation" }, { 0x0028, 0x0005, "US", "Image Dimensions" }, { 0x0028, 0x0006, "US", "Planar Configuration" }, { 0x0028, 0x0008, "IS", "Number of Frames" }, { 0x0028, 0x0009, "AT", "Frame Increment Pointer" }, { 0x0028, 0x0010, "US", "Rows" }, { 0x0028, 0x0011, "US", "Columns" }, { 0x0028, 0x0012, "US", "Planes" }, { 0x0028, 0x0014, "US", "Ultrasound Color Data Present" }, { 0x0028, 0x0030, "DS", "Pixel Spacing" }, { 0x0028, 0x0031, "DS", "Zoom Factor" }, { 0x0028, 0x0032, "DS", "Zoom Center" }, { 0x0028, 0x0034, "IS", "Pixel Aspect Ratio" }, { 0x0028, 0x0040, "LO", "Image Format" }, { 0x0028, 0x0050, "LT", "Manipulated Image" }, { 0x0028, 0x0051, "CS", "Corrected Image" }, { 0x0028, 0x005f, "LO", "Compression Recognition Code" }, { 0x0028, 0x0060, "LO", "Compression Code" }, { 0x0028, 0x0061, "SH", "Compression Originator" }, { 0x0028, 0x0062, "SH", "Compression Label" }, { 0x0028, 0x0063, "SH", "Compression Description" }, { 0x0028, 0x0065, "LO", "Compression Sequence" }, { 0x0028, 0x0066, "AT", "Compression Step Pointers" }, { 0x0028, 0x0068, "US", "Repeat Interval" }, { 0x0028, 0x0069, "US", "Bits Grouped" }, { 0x0028, 0x0070, "US", "Perimeter Table" }, { 0x0028, 0x0071, "xs", "Perimeter Value" }, { 0x0028, 0x0080, "US", "Predictor Rows" }, { 0x0028, 0x0081, "US", "Predictor Columns" }, { 0x0028, 0x0082, "US", "Predictor Constants" }, { 0x0028, 0x0090, "LO", "Blocked Pixels" }, { 0x0028, 0x0091, "US", "Block Rows" }, { 0x0028, 0x0092, "US", "Block Columns" }, { 0x0028, 0x0093, "US", "Row Overlap" }, { 0x0028, 0x0094, "US", "Column Overlap" }, { 0x0028, 0x0100, "US", "Bits Allocated" }, { 0x0028, 0x0101, "US", "Bits Stored" }, { 0x0028, 0x0102, "US", "High Bit" }, { 0x0028, 0x0103, "US", "Pixel Representation" }, { 0x0028, 0x0104, "xs", "Smallest Valid Pixel Value" }, { 0x0028, 0x0105, "xs", "Largest Valid Pixel Value" }, { 0x0028, 0x0106, "xs", "Smallest Image Pixel Value" }, { 0x0028, 0x0107, "xs", "Largest Image Pixel Value" }, { 0x0028, 0x0108, "xs", "Smallest Pixel Value in Series" }, { 0x0028, 0x0109, "xs", "Largest Pixel Value in Series" }, { 0x0028, 0x0110, "xs", "Smallest Pixel Value in Plane" }, { 0x0028, 0x0111, "xs", "Largest Pixel Value in Plane" }, { 0x0028, 0x0120, "xs", "Pixel Padding Value" }, { 0x0028, 0x0200, "xs", "Image Location" }, { 0x0028, 0x0300, "CS", "Quality Control Image" }, { 0x0028, 0x0301, "CS", "Burned In Annotation" }, { 0x0028, 0x0400, "xs", "?" }, { 0x0028, 0x0401, "xs", "?" }, { 0x0028, 0x0402, "xs", "?" }, { 0x0028, 0x0403, "xs", "?" }, { 0x0028, 0x0404, "AT", "Details of Coefficients" }, { 0x0028, 0x0700, "LO", "DCT Label" }, { 0x0028, 0x0701, "LO", "Data Block Description" }, { 0x0028, 0x0702, "AT", "Data Block" }, { 0x0028, 0x0710, "US", "Normalization Factor Format" }, { 0x0028, 0x0720, "US", "Zonal Map Number Format" }, { 0x0028, 0x0721, "AT", "Zonal Map Location" }, { 0x0028, 0x0722, "US", "Zonal Map Format" }, { 0x0028, 0x0730, "US", "Adaptive Map Format" }, { 0x0028, 0x0740, "US", "Code Number Format" }, { 0x0028, 0x0800, "LO", "Code Label" }, { 0x0028, 0x0802, "US", "Number of Tables" }, { 0x0028, 0x0803, "AT", "Code Table Location" }, { 0x0028, 0x0804, "US", "Bits For Code Word" }, { 0x0028, 0x0808, "AT", "Image Data Location" }, { 0x0028, 0x1040, "CS", "Pixel Intensity Relationship" }, { 0x0028, 0x1041, "SS", "Pixel Intensity Relationship Sign" }, { 0x0028, 0x1050, "DS", "Window Center" }, { 0x0028, 0x1051, "DS", "Window Width" }, { 0x0028, 0x1052, "DS", "Rescale Intercept" }, { 0x0028, 0x1053, "DS", "Rescale Slope" }, { 0x0028, 0x1054, "LO", "Rescale Type" }, { 0x0028, 0x1055, "LO", "Window Center & Width Explanation" }, { 0x0028, 0x1080, "LO", "Gray Scale" }, { 0x0028, 0x1090, "CS", "Recommended Viewing Mode" }, { 0x0028, 0x1100, "xs", "Gray Lookup Table Descriptor" }, { 0x0028, 0x1101, "xs", "Red Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1102, "xs", "Green Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1103, "xs", "Blue Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1111, "OW", "Large Red Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1112, "OW", "Large Green Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1113, "OW", "Large Blue Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1199, "UI", "Palette Color Lookup Table UID" }, { 0x0028, 0x1200, "xs", "Gray Lookup Table Data" }, { 0x0028, 0x1201, "OW", "Red Palette Color Lookup Table Data" }, { 0x0028, 0x1202, "OW", "Green Palette Color Lookup Table Data" }, { 0x0028, 0x1203, "OW", "Blue Palette Color Lookup Table Data" }, { 0x0028, 0x1211, "OW", "Large Red Palette Color Lookup Table Data" }, { 0x0028, 0x1212, "OW", "Large Green Palette Color Lookup Table Data" }, { 0x0028, 0x1213, "OW", "Large Blue Palette Color Lookup Table Data" }, { 0x0028, 0x1214, "UI", "Large Palette Color Lookup Table UID" }, { 0x0028, 0x1221, "OW", "Segmented Red Palette Color Lookup Table Data" }, { 0x0028, 0x1222, "OW", "Segmented Green Palette Color Lookup Table Data" }, { 0x0028, 0x1223, "OW", "Segmented Blue Palette Color Lookup Table Data" }, { 0x0028, 0x1300, "CS", "Implant Present" }, { 0x0028, 0x2110, "CS", "Lossy Image Compression" }, { 0x0028, 0x2112, "DS", "Lossy Image Compression Ratio" }, { 0x0028, 0x3000, "SQ", "Modality LUT Sequence" }, { 0x0028, 0x3002, "US", "LUT Descriptor" }, { 0x0028, 0x3003, "LO", "LUT Explanation" }, { 0x0028, 0x3004, "LO", "Modality LUT Type" }, { 0x0028, 0x3006, "US", "LUT Data" }, { 0x0028, 0x3010, "xs", "VOI LUT Sequence" }, { 0x0028, 0x4000, "LT", "Image Presentation Comments" }, { 0x0028, 0x5000, "SQ", "Biplane Acquisition Sequence" }, { 0x0028, 0x6010, "US", "Representative Frame Number" }, { 0x0028, 0x6020, "US", "Frame Numbers of Interest" }, { 0x0028, 0x6022, "LO", "Frame of Interest Description" }, { 0x0028, 0x6030, "US", "Mask Pointer" }, { 0x0028, 0x6040, "US", "R Wave Pointer" }, { 0x0028, 0x6100, "SQ", "Mask Subtraction Sequence" }, { 0x0028, 0x6101, "CS", "Mask Operation" }, { 0x0028, 0x6102, "US", "Applicable Frame Range" }, { 0x0028, 0x6110, "US", "Mask Frame Numbers" }, { 0x0028, 0x6112, "US", "Contrast Frame Averaging" }, { 0x0028, 0x6114, "FL", "Mask Sub-Pixel Shift" }, { 0x0028, 0x6120, "SS", "TID Offset" }, { 0x0028, 0x6190, "ST", "Mask Operation Explanation" }, { 0x0029, 0x0000, "xs", "?" }, { 0x0029, 0x0001, "xs", "?" }, { 0x0029, 0x0002, "xs", "?" }, { 0x0029, 0x0003, "xs", "?" }, { 0x0029, 0x0004, "xs", "?" }, { 0x0029, 0x0005, "xs", "?" }, { 0x0029, 0x0006, "xs", "?" }, { 0x0029, 0x0007, "SL", "Lower Range Of Pixels" }, { 0x0029, 0x0008, "SH", "Lower Range Of Pixels" }, { 0x0029, 0x0009, "SH", "Lower Range Of Pixels" }, { 0x0029, 0x000a, "SS", "Lower Range Of Pixels" }, { 0x0029, 0x000c, "xs", "?" }, { 0x0029, 0x000e, "CS", "Zoom Enable Status" }, { 0x0029, 0x000f, "CS", "Zoom Select Status" }, { 0x0029, 0x0010, "xs", "?" }, { 0x0029, 0x0011, "xs", "?" }, { 0x0029, 0x0013, "LT", "?" }, { 0x0029, 0x0015, "xs", "?" }, { 0x0029, 0x0016, "SL", "Lower Range Of Pixels" }, { 0x0029, 0x0017, "SL", "Lower Range Of Pixels" }, { 0x0029, 0x0018, "SL", "Upper Range Of Pixels" }, { 0x0029, 0x001a, "SL", "Length Of Total Info In Bytes" }, { 0x0029, 0x001e, "xs", "?" }, { 0x0029, 0x001f, "xs", "?" }, { 0x0029, 0x0020, "xs", "?" }, { 0x0029, 0x0022, "IS", "Pixel Quality Value" }, { 0x0029, 0x0025, "LT", "Processed Pixel Data Quality" }, { 0x0029, 0x0026, "SS", "Version Of Info Structure" }, { 0x0029, 0x0030, "xs", "?" }, { 0x0029, 0x0031, "xs", "?" }, { 0x0029, 0x0032, "xs", "?" }, { 0x0029, 0x0033, "xs", "?" }, { 0x0029, 0x0034, "xs", "?" }, { 0x0029, 0x0035, "SL", "Advantage Comp Underflow" }, { 0x0029, 0x0038, "US", "?" }, { 0x0029, 0x0040, "xs", "?" }, { 0x0029, 0x0041, "DS", "Magnifying Glass Rectangle" }, { 0x0029, 0x0043, "DS", "Magnifying Glass Factor" }, { 0x0029, 0x0044, "US", "Magnifying Glass Function" }, { 0x0029, 0x004e, "CS", "Magnifying Glass Enable Status" }, { 0x0029, 0x004f, "CS", "Magnifying Glass Select Status" }, { 0x0029, 0x0050, "xs", "?" }, { 0x0029, 0x0051, "LT", "Exposure Code" }, { 0x0029, 0x0052, "LT", "Sort Code" }, { 0x0029, 0x0053, "LT", "?" }, { 0x0029, 0x0060, "xs", "?" }, { 0x0029, 0x0061, "xs", "?" }, { 0x0029, 0x0067, "LT", "?" }, { 0x0029, 0x0070, "xs", "?" }, { 0x0029, 0x0071, "xs", "?" }, { 0x0029, 0x0072, "xs", "?" }, { 0x0029, 0x0077, "CS", "Window Select Status" }, { 0x0029, 0x0078, "LT", "ECG Display Printing ID" }, { 0x0029, 0x0079, "CS", "ECG Display Printing" }, { 0x0029, 0x007e, "CS", "ECG Display Printing Enable Status" }, { 0x0029, 0x007f, "CS", "ECG Display Printing Select Status" }, { 0x0029, 0x0080, "xs", "?" }, { 0x0029, 0x0081, "xs", "?" }, { 0x0029, 0x0082, "IS", "View Zoom" }, { 0x0029, 0x0083, "IS", "View Transform" }, { 0x0029, 0x008e, "CS", "Physiological Display Enable Status" }, { 0x0029, 0x008f, "CS", "Physiological Display Select Status" }, { 0x0029, 0x0090, "IS", "?" }, { 0x0029, 0x0099, "LT", "Shutter Type" }, { 0x0029, 0x00a0, "US", "Rows of Rectangular Shutter" }, { 0x0029, 0x00a1, "US", "Columns of Rectangular Shutter" }, { 0x0029, 0x00a2, "US", "Origin of Rectangular Shutter" }, { 0x0029, 0x00b0, "US", "Radius of Circular Shutter" }, { 0x0029, 0x00b2, "US", "Origin of Circular Shutter" }, { 0x0029, 0x00c0, "LT", "Functional Shutter ID" }, { 0x0029, 0x00c1, "xs", "?" }, { 0x0029, 0x00c3, "IS", "Scan Resolution" }, { 0x0029, 0x00c4, "IS", "Field of View" }, { 0x0029, 0x00c5, "LT", "Field Of Shutter Rectangle" }, { 0x0029, 0x00ce, "CS", "Shutter Enable Status" }, { 0x0029, 0x00cf, "CS", "Shutter Select Status" }, { 0x0029, 0x00d0, "IS", "?" }, { 0x0029, 0x00d1, "IS", "?" }, { 0x0029, 0x00d5, "LT", "Slice Thickness" }, { 0x0031, 0x0010, "LT", "Request UID" }, { 0x0031, 0x0012, "LT", "Examination Reason" }, { 0x0031, 0x0030, "DA", "Requested Date" }, { 0x0031, 0x0032, "TM", "Worklist Request Start Time" }, { 0x0031, 0x0033, "TM", "Worklist Request End Time" }, { 0x0031, 0x0045, "LT", "Requesting Physician" }, { 0x0031, 0x004a, "TM", "Requested Time" }, { 0x0031, 0x0050, "LT", "Requested Physician" }, { 0x0031, 0x0080, "LT", "Requested Location" }, { 0x0032, 0x0000, "UL", "Study Group Length" }, { 0x0032, 0x000a, "CS", "Study Status ID" }, { 0x0032, 0x000c, "CS", "Study Priority ID" }, { 0x0032, 0x0012, "LO", "Study ID Issuer" }, { 0x0032, 0x0032, "DA", "Study Verified Date" }, { 0x0032, 0x0033, "TM", "Study Verified Time" }, { 0x0032, 0x0034, "DA", "Study Read Date" }, { 0x0032, 0x0035, "TM", "Study Read Time" }, { 0x0032, 0x1000, "DA", "Scheduled Study Start Date" }, { 0x0032, 0x1001, "TM", "Scheduled Study Start Time" }, { 0x0032, 0x1010, "DA", "Scheduled Study Stop Date" }, { 0x0032, 0x1011, "TM", "Scheduled Study Stop Time" }, { 0x0032, 0x1020, "LO", "Scheduled Study Location" }, { 0x0032, 0x1021, "AE", "Scheduled Study Location AE Title(s)" }, { 0x0032, 0x1030, "LO", "Reason for Study" }, { 0x0032, 0x1032, "PN", "Requesting Physician" }, { 0x0032, 0x1033, "LO", "Requesting Service" }, { 0x0032, 0x1040, "DA", "Study Arrival Date" }, { 0x0032, 0x1041, "TM", "Study Arrival Time" }, { 0x0032, 0x1050, "DA", "Study Completion Date" }, { 0x0032, 0x1051, "TM", "Study Completion Time" }, { 0x0032, 0x1055, "CS", "Study Component Status ID" }, { 0x0032, 0x1060, "LO", "Requested Procedure Description" }, { 0x0032, 0x1064, "SQ", "Requested Procedure Code Sequence" }, { 0x0032, 0x1070, "LO", "Requested Contrast Agent" }, { 0x0032, 0x4000, "LT", "Study Comments" }, { 0x0033, 0x0001, "UN", "?" }, { 0x0033, 0x0002, "UN", "?" }, { 0x0033, 0x0005, "UN", "?" }, { 0x0033, 0x0006, "UN", "?" }, { 0x0033, 0x0010, "LT", "Patient Study UID" }, { 0x0037, 0x0010, "LO", "ReferringDepartment" }, { 0x0037, 0x0020, "US", "ScreenNumber" }, { 0x0037, 0x0040, "SH", "LeftOrientation" }, { 0x0037, 0x0042, "SH", "RightOrientation" }, { 0x0037, 0x0050, "CS", "Inversion" }, { 0x0037, 0x0060, "US", "DSA" }, { 0x0038, 0x0000, "UL", "Visit Group Length" }, { 0x0038, 0x0004, "SQ", "Referenced Patient Alias Sequence" }, { 0x0038, 0x0008, "CS", "Visit Status ID" }, { 0x0038, 0x0010, "LO", "Admission ID" }, { 0x0038, 0x0011, "LO", "Issuer of Admission ID" }, { 0x0038, 0x0016, "LO", "Route of Admissions" }, { 0x0038, 0x001a, "DA", "Scheduled Admission Date" }, { 0x0038, 0x001b, "TM", "Scheduled Admission Time" }, { 0x0038, 0x001c, "DA", "Scheduled Discharge Date" }, { 0x0038, 0x001d, "TM", "Scheduled Discharge Time" }, { 0x0038, 0x001e, "LO", "Scheduled Patient Institution Residence" }, { 0x0038, 0x0020, "DA", "Admitting Date" }, { 0x0038, 0x0021, "TM", "Admitting Time" }, { 0x0038, 0x0030, "DA", "Discharge Date" }, { 0x0038, 0x0032, "TM", "Discharge Time" }, { 0x0038, 0x0040, "LO", "Discharge Diagnosis Description" }, { 0x0038, 0x0044, "SQ", "Discharge Diagnosis Code Sequence" }, { 0x0038, 0x0050, "LO", "Special Needs" }, { 0x0038, 0x0300, "LO", "Current Patient Location" }, { 0x0038, 0x0400, "LO", "Patient's Institution Residence" }, { 0x0038, 0x0500, "LO", "Patient State" }, { 0x0038, 0x4000, "LT", "Visit Comments" }, { 0x0039, 0x0080, "IS", "Private Entity Number" }, { 0x0039, 0x0085, "DA", "Private Entity Date" }, { 0x0039, 0x0090, "TM", "Private Entity Time" }, { 0x0039, 0x0095, "LO", "Private Entity Launch Command" }, { 0x0039, 0x00aa, "CS", "Private Entity Type" }, { 0x003a, 0x0002, "SQ", "Waveform Sequence" }, { 0x003a, 0x0005, "US", "Waveform Number of Channels" }, { 0x003a, 0x0010, "UL", "Waveform Number of Samples" }, { 0x003a, 0x001a, "DS", "Sampling Frequency" }, { 0x003a, 0x0020, "SH", "Group Label" }, { 0x003a, 0x0103, "CS", "Waveform Sample Value Representation" }, { 0x003a, 0x0122, "OB", "Waveform Padding Value" }, { 0x003a, 0x0200, "SQ", "Channel Definition" }, { 0x003a, 0x0202, "IS", "Waveform Channel Number" }, { 0x003a, 0x0203, "SH", "Channel Label" }, { 0x003a, 0x0205, "CS", "Channel Status" }, { 0x003a, 0x0208, "SQ", "Channel Source" }, { 0x003a, 0x0209, "SQ", "Channel Source Modifiers" }, { 0x003a, 0x020a, "SQ", "Differential Channel Source" }, { 0x003a, 0x020b, "SQ", "Differential Channel Source Modifiers" }, { 0x003a, 0x0210, "DS", "Channel Sensitivity" }, { 0x003a, 0x0211, "SQ", "Channel Sensitivity Units" }, { 0x003a, 0x0212, "DS", "Channel Sensitivity Correction Factor" }, { 0x003a, 0x0213, "DS", "Channel Baseline" }, { 0x003a, 0x0214, "DS", "Channel Time Skew" }, { 0x003a, 0x0215, "DS", "Channel Sample Skew" }, { 0x003a, 0x0216, "OB", "Channel Minimum Value" }, { 0x003a, 0x0217, "OB", "Channel Maximum Value" }, { 0x003a, 0x0218, "DS", "Channel Offset" }, { 0x003a, 0x021a, "US", "Bits Per Sample" }, { 0x003a, 0x0220, "DS", "Filter Low Frequency" }, { 0x003a, 0x0221, "DS", "Filter High Frequency" }, { 0x003a, 0x0222, "DS", "Notch Filter Frequency" }, { 0x003a, 0x0223, "DS", "Notch Filter Bandwidth" }, { 0x003a, 0x1000, "OB", "Waveform Data" }, { 0x0040, 0x0001, "AE", "Scheduled Station AE Title" }, { 0x0040, 0x0002, "DA", "Scheduled Procedure Step Start Date" }, { 0x0040, 0x0003, "TM", "Scheduled Procedure Step Start Time" }, { 0x0040, 0x0004, "DA", "Scheduled Procedure Step End Date" }, { 0x0040, 0x0005, "TM", "Scheduled Procedure Step End Time" }, { 0x0040, 0x0006, "PN", "Scheduled Performing Physician Name" }, { 0x0040, 0x0007, "LO", "Scheduled Procedure Step Description" }, { 0x0040, 0x0008, "SQ", "Scheduled Action Item Code Sequence" }, { 0x0040, 0x0009, "SH", "Scheduled Procedure Step ID" }, { 0x0040, 0x0010, "SH", "Scheduled Station Name" }, { 0x0040, 0x0011, "SH", "Scheduled Procedure Step Location" }, { 0x0040, 0x0012, "LO", "Pre-Medication" }, { 0x0040, 0x0020, "CS", "Scheduled Procedure Step Status" }, { 0x0040, 0x0100, "SQ", "Scheduled Procedure Step Sequence" }, { 0x0040, 0x0302, "US", "Entrance Dose" }, { 0x0040, 0x0303, "US", "Exposed Area" }, { 0x0040, 0x0306, "DS", "Distance Source to Entrance" }, { 0x0040, 0x0307, "DS", "Distance Source to Support" }, { 0x0040, 0x0310, "ST", "Comments On Radiation Dose" }, { 0x0040, 0x0312, "DS", "X-Ray Output" }, { 0x0040, 0x0314, "DS", "Half Value Layer" }, { 0x0040, 0x0316, "DS", "Organ Dose" }, { 0x0040, 0x0318, "CS", "Organ Exposed" }, { 0x0040, 0x0400, "LT", "Comments On Scheduled Procedure Step" }, { 0x0040, 0x050a, "LO", "Specimen Accession Number" }, { 0x0040, 0x0550, "SQ", "Specimen Sequence" }, { 0x0040, 0x0551, "LO", "Specimen Identifier" }, { 0x0040, 0x0552, "SQ", "Specimen Description Sequence" }, { 0x0040, 0x0553, "ST", "Specimen Description" }, { 0x0040, 0x0555, "SQ", "Acquisition Context Sequence" }, { 0x0040, 0x0556, "ST", "Acquisition Context Description" }, { 0x0040, 0x059a, "SQ", "Specimen Type Code Sequence" }, { 0x0040, 0x06fa, "LO", "Slide Identifier" }, { 0x0040, 0x071a, "SQ", "Image Center Point Coordinates Sequence" }, { 0x0040, 0x072a, "DS", "X Offset In Slide Coordinate System" }, { 0x0040, 0x073a, "DS", "Y Offset In Slide Coordinate System" }, { 0x0040, 0x074a, "DS", "Z Offset In Slide Coordinate System" }, { 0x0040, 0x08d8, "SQ", "Pixel Spacing Sequence" }, { 0x0040, 0x08da, "SQ", "Coordinate System Axis Code Sequence" }, { 0x0040, 0x08ea, "SQ", "Measurement Units Code Sequence" }, { 0x0040, 0x09f8, "SQ", "Vital Stain Code Sequence" }, { 0x0040, 0x1001, "SH", "Requested Procedure ID" }, { 0x0040, 0x1002, "LO", "Reason For Requested Procedure" }, { 0x0040, 0x1003, "SH", "Requested Procedure Priority" }, { 0x0040, 0x1004, "LO", "Patient Transport Arrangements" }, { 0x0040, 0x1005, "LO", "Requested Procedure Location" }, { 0x0040, 0x1006, "SH", "Placer Order Number of Procedure" }, { 0x0040, 0x1007, "SH", "Filler Order Number of Procedure" }, { 0x0040, 0x1008, "LO", "Confidentiality Code" }, { 0x0040, 0x1009, "SH", "Reporting Priority" }, { 0x0040, 0x1010, "PN", "Names of Intended Recipients of Results" }, { 0x0040, 0x1400, "LT", "Requested Procedure Comments" }, { 0x0040, 0x2001, "LO", "Reason For Imaging Service Request" }, { 0x0040, 0x2004, "DA", "Issue Date of Imaging Service Request" }, { 0x0040, 0x2005, "TM", "Issue Time of Imaging Service Request" }, { 0x0040, 0x2006, "SH", "Placer Order Number of Imaging Service Request" }, { 0x0040, 0x2007, "SH", "Filler Order Number of Imaging Service Request" }, { 0x0040, 0x2008, "PN", "Order Entered By" }, { 0x0040, 0x2009, "SH", "Order Enterer Location" }, { 0x0040, 0x2010, "SH", "Order Callback Phone Number" }, { 0x0040, 0x2400, "LT", "Imaging Service Request Comments" }, { 0x0040, 0x3001, "LO", "Confidentiality Constraint On Patient Data" }, { 0x0040, 0xa007, "CS", "Findings Flag" }, { 0x0040, 0xa020, "SQ", "Findings Sequence" }, { 0x0040, 0xa021, "UI", "Findings Group UID" }, { 0x0040, 0xa022, "UI", "Referenced Findings Group UID" }, { 0x0040, 0xa023, "DA", "Findings Group Recording Date" }, { 0x0040, 0xa024, "TM", "Findings Group Recording Time" }, { 0x0040, 0xa026, "SQ", "Findings Source Category Code Sequence" }, { 0x0040, 0xa027, "LO", "Documenting Organization" }, { 0x0040, 0xa028, "SQ", "Documenting Organization Identifier Code Sequence" }, { 0x0040, 0xa032, "LO", "History Reliability Qualifier Description" }, { 0x0040, 0xa043, "SQ", "Concept Name Code Sequence" }, { 0x0040, 0xa047, "LO", "Measurement Precision Description" }, { 0x0040, 0xa057, "CS", "Urgency or Priority Alerts" }, { 0x0040, 0xa060, "LO", "Sequencing Indicator" }, { 0x0040, 0xa066, "SQ", "Document Identifier Code Sequence" }, { 0x0040, 0xa067, "PN", "Document Author" }, { 0x0040, 0xa068, "SQ", "Document Author Identifier Code Sequence" }, { 0x0040, 0xa070, "SQ", "Identifier Code Sequence" }, { 0x0040, 0xa073, "LO", "Object String Identifier" }, { 0x0040, 0xa074, "OB", "Object Binary Identifier" }, { 0x0040, 0xa075, "PN", "Documenting Observer" }, { 0x0040, 0xa076, "SQ", "Documenting Observer Identifier Code Sequence" }, { 0x0040, 0xa078, "SQ", "Observation Subject Identifier Code Sequence" }, { 0x0040, 0xa080, "SQ", "Person Identifier Code Sequence" }, { 0x0040, 0xa085, "SQ", "Procedure Identifier Code Sequence" }, { 0x0040, 0xa088, "LO", "Object Directory String Identifier" }, { 0x0040, 0xa089, "OB", "Object Directory Binary Identifier" }, { 0x0040, 0xa090, "CS", "History Reliability Qualifier" }, { 0x0040, 0xa0a0, "CS", "Referenced Type of Data" }, { 0x0040, 0xa0b0, "US", "Referenced Waveform Channels" }, { 0x0040, 0xa110, "DA", "Date of Document or Verbal Transaction" }, { 0x0040, 0xa112, "TM", "Time of Document Creation or Verbal Transaction" }, { 0x0040, 0xa121, "DA", "Date" }, { 0x0040, 0xa122, "TM", "Time" }, { 0x0040, 0xa123, "PN", "Person Name" }, { 0x0040, 0xa124, "SQ", "Referenced Person Sequence" }, { 0x0040, 0xa125, "CS", "Report Status ID" }, { 0x0040, 0xa130, "CS", "Temporal Range Type" }, { 0x0040, 0xa132, "UL", "Referenced Sample Offsets" }, { 0x0040, 0xa136, "US", "Referenced Frame Numbers" }, { 0x0040, 0xa138, "DS", "Referenced Time Offsets" }, { 0x0040, 0xa13a, "DT", "Referenced Datetime" }, { 0x0040, 0xa160, "UT", "Text Value" }, { 0x0040, 0xa167, "SQ", "Observation Category Code Sequence" }, { 0x0040, 0xa168, "SQ", "Concept Code Sequence" }, { 0x0040, 0xa16a, "ST", "Bibliographic Citation" }, { 0x0040, 0xa170, "CS", "Observation Class" }, { 0x0040, 0xa171, "UI", "Observation UID" }, { 0x0040, 0xa172, "UI", "Referenced Observation UID" }, { 0x0040, 0xa173, "CS", "Referenced Observation Class" }, { 0x0040, 0xa174, "CS", "Referenced Object Observation Class" }, { 0x0040, 0xa180, "US", "Annotation Group Number" }, { 0x0040, 0xa192, "DA", "Observation Date" }, { 0x0040, 0xa193, "TM", "Observation Time" }, { 0x0040, 0xa194, "CS", "Measurement Automation" }, { 0x0040, 0xa195, "SQ", "Concept Name Code Sequence Modifier" }, { 0x0040, 0xa224, "ST", "Identification Description" }, { 0x0040, 0xa290, "CS", "Coordinates Set Geometric Type" }, { 0x0040, 0xa296, "SQ", "Algorithm Code Sequence" }, { 0x0040, 0xa297, "ST", "Algorithm Description" }, { 0x0040, 0xa29a, "SL", "Pixel Coordinates Set" }, { 0x0040, 0xa300, "SQ", "Measured Value Sequence" }, { 0x0040, 0xa307, "PN", "Current Observer" }, { 0x0040, 0xa30a, "DS", "Numeric Value" }, { 0x0040, 0xa313, "SQ", "Referenced Accession Sequence" }, { 0x0040, 0xa33a, "ST", "Report Status Comment" }, { 0x0040, 0xa340, "SQ", "Procedure Context Sequence" }, { 0x0040, 0xa352, "PN", "Verbal Source" }, { 0x0040, 0xa353, "ST", "Address" }, { 0x0040, 0xa354, "LO", "Telephone Number" }, { 0x0040, 0xa358, "SQ", "Verbal Source Identifier Code Sequence" }, { 0x0040, 0xa380, "SQ", "Report Detail Sequence" }, { 0x0040, 0xa402, "UI", "Observation Subject UID" }, { 0x0040, 0xa403, "CS", "Observation Subject Class" }, { 0x0040, 0xa404, "SQ", "Observation Subject Type Code Sequence" }, { 0x0040, 0xa600, "CS", "Observation Subject Context Flag" }, { 0x0040, 0xa601, "CS", "Observer Context Flag" }, { 0x0040, 0xa603, "CS", "Procedure Context Flag" }, { 0x0040, 0xa730, "SQ", "Observations Sequence" }, { 0x0040, 0xa731, "SQ", "Relationship Sequence" }, { 0x0040, 0xa732, "SQ", "Relationship Type Code Sequence" }, { 0x0040, 0xa744, "SQ", "Language Code Sequence" }, { 0x0040, 0xa992, "ST", "Uniform Resource Locator" }, { 0x0040, 0xb020, "SQ", "Annotation Sequence" }, { 0x0040, 0xdb73, "SQ", "Relationship Type Code Sequence Modifier" }, { 0x0041, 0x0000, "LT", "Papyrus Comments" }, { 0x0041, 0x0010, "xs", "?" }, { 0x0041, 0x0011, "xs", "?" }, { 0x0041, 0x0012, "UL", "Pixel Offset" }, { 0x0041, 0x0013, "SQ", "Image Identifier Sequence" }, { 0x0041, 0x0014, "SQ", "External File Reference Sequence" }, { 0x0041, 0x0015, "US", "Number of Images" }, { 0x0041, 0x0020, "xs", "?" }, { 0x0041, 0x0021, "UI", "Referenced SOP Class UID" }, { 0x0041, 0x0022, "UI", "Referenced SOP Instance UID" }, { 0x0041, 0x0030, "xs", "?" }, { 0x0041, 0x0031, "xs", "?" }, { 0x0041, 0x0032, "xs", "?" }, { 0x0041, 0x0034, "DA", "Modified Date" }, { 0x0041, 0x0036, "TM", "Modified Time" }, { 0x0041, 0x0040, "LT", "Owner Name" }, { 0x0041, 0x0041, "UI", "Referenced Image SOP Class UID" }, { 0x0041, 0x0042, "UI", "Referenced Image SOP Instance UID" }, { 0x0041, 0x0050, "xs", "?" }, { 0x0041, 0x0060, "UL", "Number of Images" }, { 0x0041, 0x0062, "UL", "Number of Other" }, { 0x0041, 0x00a0, "LT", "External Folder Element DSID" }, { 0x0041, 0x00a1, "US", "External Folder Element Data Set Type" }, { 0x0041, 0x00a2, "LT", "External Folder Element File Location" }, { 0x0041, 0x00a3, "UL", "External Folder Element Length" }, { 0x0041, 0x00b0, "LT", "Internal Folder Element DSID" }, { 0x0041, 0x00b1, "US", "Internal Folder Element Data Set Type" }, { 0x0041, 0x00b2, "UL", "Internal Offset To Data Set" }, { 0x0041, 0x00b3, "UL", "Internal Offset To Image" }, { 0x0043, 0x0001, "SS", "Bitmap Of Prescan Options" }, { 0x0043, 0x0002, "SS", "Gradient Offset In X" }, { 0x0043, 0x0003, "SS", "Gradient Offset In Y" }, { 0x0043, 0x0004, "SS", "Gradient Offset In Z" }, { 0x0043, 0x0005, "SS", "Image Is Original Or Unoriginal" }, { 0x0043, 0x0006, "SS", "Number Of EPI Shots" }, { 0x0043, 0x0007, "SS", "Views Per Segment" }, { 0x0043, 0x0008, "SS", "Respiratory Rate In BPM" }, { 0x0043, 0x0009, "SS", "Respiratory Trigger Point" }, { 0x0043, 0x000a, "SS", "Type Of Receiver Used" }, { 0x0043, 0x000b, "DS", "Peak Rate Of Change Of Gradient Field" }, { 0x0043, 0x000c, "DS", "Limits In Units Of Percent" }, { 0x0043, 0x000d, "DS", "PSD Estimated Limit" }, { 0x0043, 0x000e, "DS", "PSD Estimated Limit In Tesla Per Second" }, { 0x0043, 0x000f, "DS", "SAR Avg Head" }, { 0x0043, 0x0010, "US", "Window Value" }, { 0x0043, 0x0011, "US", "Total Input Views" }, { 0x0043, 0x0012, "SS", "Xray Chain" }, { 0x0043, 0x0013, "SS", "Recon Kernel Parameters" }, { 0x0043, 0x0014, "SS", "Calibration Parameters" }, { 0x0043, 0x0015, "SS", "Total Output Views" }, { 0x0043, 0x0016, "SS", "Number Of Overranges" }, { 0x0043, 0x0017, "DS", "IBH Image Scale Factors" }, { 0x0043, 0x0018, "DS", "BBH Coefficients" }, { 0x0043, 0x0019, "SS", "Number Of BBH Chains To Blend" }, { 0x0043, 0x001a, "SL", "Starting Channel Number" }, { 0x0043, 0x001b, "SS", "PPScan Parameters" }, { 0x0043, 0x001c, "SS", "GE Image Integrity" }, { 0x0043, 0x001d, "SS", "Level Value" }, { 0x0043, 0x001e, "xs", "?" }, { 0x0043, 0x001f, "SL", "Max Overranges In A View" }, { 0x0043, 0x0020, "DS", "Avg Overranges All Views" }, { 0x0043, 0x0021, "SS", "Corrected Afterglow Terms" }, { 0x0043, 0x0025, "SS", "Reference Channels" }, { 0x0043, 0x0026, "US", "No Views Ref Channels Blocked" }, { 0x0043, 0x0027, "xs", "?" }, { 0x0043, 0x0028, "OB", "Unique Image Identifier" }, { 0x0043, 0x0029, "OB", "Histogram Tables" }, { 0x0043, 0x002a, "OB", "User Defined Data" }, { 0x0043, 0x002b, "SS", "Private Scan Options" }, { 0x0043, 0x002c, "SS", "Effective Echo Spacing" }, { 0x0043, 0x002d, "SH", "String Slop Field 1" }, { 0x0043, 0x002e, "SH", "String Slop Field 2" }, { 0x0043, 0x002f, "SS", "Raw Data Type" }, { 0x0043, 0x0030, "SS", "Raw Data Type" }, { 0x0043, 0x0031, "DS", "RA Coord Of Target Recon Centre" }, { 0x0043, 0x0032, "SS", "Raw Data Type" }, { 0x0043, 0x0033, "FL", "Neg Scan Spacing" }, { 0x0043, 0x0034, "IS", "Offset Frequency" }, { 0x0043, 0x0035, "UL", "User Usage Tag" }, { 0x0043, 0x0036, "UL", "User Fill Map MSW" }, { 0x0043, 0x0037, "UL", "User Fill Map LSW" }, { 0x0043, 0x0038, "FL", "User 25 To User 48" }, { 0x0043, 0x0039, "IS", "Slop Integer 6 To Slop Integer 9" }, { 0x0043, 0x0040, "FL", "Trigger On Position" }, { 0x0043, 0x0041, "FL", "Degree Of Rotation" }, { 0x0043, 0x0042, "SL", "DAS Trigger Source" }, { 0x0043, 0x0043, "SL", "DAS Fpa Gain" }, { 0x0043, 0x0044, "SL", "DAS Output Source" }, { 0x0043, 0x0045, "SL", "DAS Ad Input" }, { 0x0043, 0x0046, "SL", "DAS Cal Mode" }, { 0x0043, 0x0047, "SL", "DAS Cal Frequency" }, { 0x0043, 0x0048, "SL", "DAS Reg Xm" }, { 0x0043, 0x0049, "SL", "DAS Auto Zero" }, { 0x0043, 0x004a, "SS", "Starting Channel Of View" }, { 0x0043, 0x004b, "SL", "DAS Xm Pattern" }, { 0x0043, 0x004c, "SS", "TGGC Trigger Mode" }, { 0x0043, 0x004d, "FL", "Start Scan To Xray On Delay" }, { 0x0043, 0x004e, "FL", "Duration Of Xray On" }, { 0x0044, 0x0000, "UI", "?" }, { 0x0045, 0x0004, "CS", "AES" }, { 0x0045, 0x0006, "DS", "Angulation" }, { 0x0045, 0x0009, "DS", "Real Magnification Factor" }, { 0x0045, 0x000b, "CS", "Senograph Type" }, { 0x0045, 0x000c, "DS", "Integration Time" }, { 0x0045, 0x000d, "DS", "ROI Origin X and Y" }, { 0x0045, 0x0011, "DS", "Receptor Size cm X and Y" }, { 0x0045, 0x0012, "IS", "Receptor Size Pixels X and Y" }, { 0x0045, 0x0013, "ST", "Screen" }, { 0x0045, 0x0014, "DS", "Pixel Pitch Microns" }, { 0x0045, 0x0015, "IS", "Pixel Depth Bits" }, { 0x0045, 0x0016, "IS", "Binning Factor X and Y" }, { 0x0045, 0x001b, "CS", "Clinical View" }, { 0x0045, 0x001d, "DS", "Mean Of Raw Gray Levels" }, { 0x0045, 0x001e, "DS", "Mean Of Offset Gray Levels" }, { 0x0045, 0x001f, "DS", "Mean Of Corrected Gray Levels" }, { 0x0045, 0x0020, "DS", "Mean Of Region Gray Levels" }, { 0x0045, 0x0021, "DS", "Mean Of Log Region Gray Levels" }, { 0x0045, 0x0022, "DS", "Standard Deviation Of Raw Gray Levels" }, { 0x0045, 0x0023, "DS", "Standard Deviation Of Corrected Gray Levels" }, { 0x0045, 0x0024, "DS", "Standard Deviation Of Region Gray Levels" }, { 0x0045, 0x0025, "DS", "Standard Deviation Of Log Region Gray Levels" }, { 0x0045, 0x0026, "OB", "MAO Buffer" }, { 0x0045, 0x0027, "IS", "Set Number" }, { 0x0045, 0x0028, "CS", "WindowingType (LINEAR or GAMMA)" }, { 0x0045, 0x0029, "DS", "WindowingParameters" }, { 0x0045, 0x002a, "IS", "Crosshair Cursor X Coordinates" }, { 0x0045, 0x002b, "IS", "Crosshair Cursor Y Coordinates" }, { 0x0045, 0x0039, "US", "Vignette Rows" }, { 0x0045, 0x003a, "US", "Vignette Columns" }, { 0x0045, 0x003b, "US", "Vignette Bits Allocated" }, { 0x0045, 0x003c, "US", "Vignette Bits Stored" }, { 0x0045, 0x003d, "US", "Vignette High Bit" }, { 0x0045, 0x003e, "US", "Vignette Pixel Representation" }, { 0x0045, 0x003f, "OB", "Vignette Pixel Data" }, { 0x0047, 0x0001, "SQ", "Reconstruction Parameters Sequence" }, { 0x0047, 0x0050, "UL", "Volume Voxel Count" }, { 0x0047, 0x0051, "UL", "Volume Segment Count" }, { 0x0047, 0x0053, "US", "Volume Slice Size" }, { 0x0047, 0x0054, "US", "Volume Slice Count" }, { 0x0047, 0x0055, "SL", "Volume Threshold Value" }, { 0x0047, 0x0057, "DS", "Volume Voxel Ratio" }, { 0x0047, 0x0058, "DS", "Volume Voxel Size" }, { 0x0047, 0x0059, "US", "Volume Z Position Size" }, { 0x0047, 0x0060, "DS", "Volume Base Line" }, { 0x0047, 0x0061, "DS", "Volume Center Point" }, { 0x0047, 0x0063, "SL", "Volume Skew Base" }, { 0x0047, 0x0064, "DS", "Volume Registration Transform Rotation Matrix" }, { 0x0047, 0x0065, "DS", "Volume Registration Transform Translation Vector" }, { 0x0047, 0x0070, "DS", "KVP List" }, { 0x0047, 0x0071, "IS", "XRay Tube Current List" }, { 0x0047, 0x0072, "IS", "Exposure List" }, { 0x0047, 0x0080, "LO", "Acquisition DLX Identifier" }, { 0x0047, 0x0085, "SQ", "Acquisition DLX 2D Series Sequence" }, { 0x0047, 0x0089, "DS", "Contrast Agent Volume List" }, { 0x0047, 0x008a, "US", "Number Of Injections" }, { 0x0047, 0x008b, "US", "Frame Count" }, { 0x0047, 0x0096, "IS", "Used Frames" }, { 0x0047, 0x0091, "LO", "XA 3D Reconstruction Algorithm Name" }, { 0x0047, 0x0092, "CS", "XA 3D Reconstruction Algorithm Version" }, { 0x0047, 0x0093, "DA", "DLX Calibration Date" }, { 0x0047, 0x0094, "TM", "DLX Calibration Time" }, { 0x0047, 0x0095, "CS", "DLX Calibration Status" }, { 0x0047, 0x0098, "US", "Transform Count" }, { 0x0047, 0x0099, "SQ", "Transform Sequence" }, { 0x0047, 0x009a, "DS", "Transform Rotation Matrix" }, { 0x0047, 0x009b, "DS", "Transform Translation Vector" }, { 0x0047, 0x009c, "LO", "Transform Label" }, { 0x0047, 0x00b1, "US", "Wireframe Count" }, { 0x0047, 0x00b2, "US", "Location System" }, { 0x0047, 0x00b0, "SQ", "Wireframe List" }, { 0x0047, 0x00b5, "LO", "Wireframe Name" }, { 0x0047, 0x00b6, "LO", "Wireframe Group Name" }, { 0x0047, 0x00b7, "LO", "Wireframe Color" }, { 0x0047, 0x00b8, "SL", "Wireframe Attributes" }, { 0x0047, 0x00b9, "SL", "Wireframe Point Count" }, { 0x0047, 0x00ba, "SL", "Wireframe Timestamp" }, { 0x0047, 0x00bb, "SQ", "Wireframe Point List" }, { 0x0047, 0x00bc, "DS", "Wireframe Points Coordinates" }, { 0x0047, 0x00c0, "DS", "Volume Upper Left High Corner RAS" }, { 0x0047, 0x00c1, "DS", "Volume Slice To RAS Rotation Matrix" }, { 0x0047, 0x00c2, "DS", "Volume Upper Left High Corner TLOC" }, { 0x0047, 0x00d1, "OB", "Volume Segment List" }, { 0x0047, 0x00d2, "OB", "Volume Gradient List" }, { 0x0047, 0x00d3, "OB", "Volume Density List" }, { 0x0047, 0x00d4, "OB", "Volume Z Position List" }, { 0x0047, 0x00d5, "OB", "Volume Original Index List" }, { 0x0050, 0x0000, "UL", "Calibration Group Length" }, { 0x0050, 0x0004, "CS", "Calibration Object" }, { 0x0050, 0x0010, "SQ", "DeviceSequence" }, { 0x0050, 0x0014, "DS", "DeviceLength" }, { 0x0050, 0x0016, "DS", "DeviceDiameter" }, { 0x0050, 0x0017, "CS", "DeviceDiameterUnits" }, { 0x0050, 0x0018, "DS", "DeviceVolume" }, { 0x0050, 0x0019, "DS", "InterMarkerDistance" }, { 0x0050, 0x0020, "LO", "DeviceDescription" }, { 0x0050, 0x0030, "SQ", "CodedInterventionDeviceSequence" }, { 0x0051, 0x0010, "xs", "Image Text" }, { 0x0054, 0x0000, "UL", "Nuclear Acquisition Group Length" }, { 0x0054, 0x0010, "US", "Energy Window Vector" }, { 0x0054, 0x0011, "US", "Number of Energy Windows" }, { 0x0054, 0x0012, "SQ", "Energy Window Information Sequence" }, { 0x0054, 0x0013, "SQ", "Energy Window Range Sequence" }, { 0x0054, 0x0014, "DS", "Energy Window Lower Limit" }, { 0x0054, 0x0015, "DS", "Energy Window Upper Limit" }, { 0x0054, 0x0016, "SQ", "Radiopharmaceutical Information Sequence" }, { 0x0054, 0x0017, "IS", "Residual Syringe Counts" }, { 0x0054, 0x0018, "SH", "Energy Window Name" }, { 0x0054, 0x0020, "US", "Detector Vector" }, { 0x0054, 0x0021, "US", "Number of Detectors" }, { 0x0054, 0x0022, "SQ", "Detector Information Sequence" }, { 0x0054, 0x0030, "US", "Phase Vector" }, { 0x0054, 0x0031, "US", "Number of Phases" }, { 0x0054, 0x0032, "SQ", "Phase Information Sequence" }, { 0x0054, 0x0033, "US", "Number of Frames In Phase" }, { 0x0054, 0x0036, "IS", "Phase Delay" }, { 0x0054, 0x0038, "IS", "Pause Between Frames" }, { 0x0054, 0x0050, "US", "Rotation Vector" }, { 0x0054, 0x0051, "US", "Number of Rotations" }, { 0x0054, 0x0052, "SQ", "Rotation Information Sequence" }, { 0x0054, 0x0053, "US", "Number of Frames In Rotation" }, { 0x0054, 0x0060, "US", "R-R Interval Vector" }, { 0x0054, 0x0061, "US", "Number of R-R Intervals" }, { 0x0054, 0x0062, "SQ", "Gated Information Sequence" }, { 0x0054, 0x0063, "SQ", "Data Information Sequence" }, { 0x0054, 0x0070, "US", "Time Slot Vector" }, { 0x0054, 0x0071, "US", "Number of Time Slots" }, { 0x0054, 0x0072, "SQ", "Time Slot Information Sequence" }, { 0x0054, 0x0073, "DS", "Time Slot Time" }, { 0x0054, 0x0080, "US", "Slice Vector" }, { 0x0054, 0x0081, "US", "Number of Slices" }, { 0x0054, 0x0090, "US", "Angular View Vector" }, { 0x0054, 0x0100, "US", "Time Slice Vector" }, { 0x0054, 0x0101, "US", "Number Of Time Slices" }, { 0x0054, 0x0200, "DS", "Start Angle" }, { 0x0054, 0x0202, "CS", "Type of Detector Motion" }, { 0x0054, 0x0210, "IS", "Trigger Vector" }, { 0x0054, 0x0211, "US", "Number of Triggers in Phase" }, { 0x0054, 0x0220, "SQ", "View Code Sequence" }, { 0x0054, 0x0222, "SQ", "View Modifier Code Sequence" }, { 0x0054, 0x0300, "SQ", "Radionuclide Code Sequence" }, { 0x0054, 0x0302, "SQ", "Radiopharmaceutical Route Code Sequence" }, { 0x0054, 0x0304, "SQ", "Radiopharmaceutical Code Sequence" }, { 0x0054, 0x0306, "SQ", "Calibration Data Sequence" }, { 0x0054, 0x0308, "US", "Energy Window Number" }, { 0x0054, 0x0400, "SH", "Image ID" }, { 0x0054, 0x0410, "SQ", "Patient Orientation Code Sequence" }, { 0x0054, 0x0412, "SQ", "Patient Orientation Modifier Code Sequence" }, { 0x0054, 0x0414, "SQ", "Patient Gantry Relationship Code Sequence" }, { 0x0054, 0x1000, "CS", "Positron Emission Tomography Series Type" }, { 0x0054, 0x1001, "CS", "Positron Emission Tomography Units" }, { 0x0054, 0x1002, "CS", "Counts Source" }, { 0x0054, 0x1004, "CS", "Reprojection Method" }, { 0x0054, 0x1100, "CS", "Randoms Correction Method" }, { 0x0054, 0x1101, "LO", "Attenuation Correction Method" }, { 0x0054, 0x1102, "CS", "Decay Correction" }, { 0x0054, 0x1103, "LO", "Reconstruction Method" }, { 0x0054, 0x1104, "LO", "Detector Lines of Response Used" }, { 0x0054, 0x1105, "LO", "Scatter Correction Method" }, { 0x0054, 0x1200, "DS", "Axial Acceptance" }, { 0x0054, 0x1201, "IS", "Axial Mash" }, { 0x0054, 0x1202, "IS", "Transverse Mash" }, { 0x0054, 0x1203, "DS", "Detector Element Size" }, { 0x0054, 0x1210, "DS", "Coincidence Window Width" }, { 0x0054, 0x1220, "CS", "Secondary Counts Type" }, { 0x0054, 0x1300, "DS", "Frame Reference Time" }, { 0x0054, 0x1310, "IS", "Primary Prompts Counts Accumulated" }, { 0x0054, 0x1311, "IS", "Secondary Counts Accumulated" }, { 0x0054, 0x1320, "DS", "Slice Sensitivity Factor" }, { 0x0054, 0x1321, "DS", "Decay Factor" }, { 0x0054, 0x1322, "DS", "Dose Calibration Factor" }, { 0x0054, 0x1323, "DS", "Scatter Fraction Factor" }, { 0x0054, 0x1324, "DS", "Dead Time Factor" }, { 0x0054, 0x1330, "US", "Image Index" }, { 0x0054, 0x1400, "CS", "Counts Included" }, { 0x0054, 0x1401, "CS", "Dead Time Correction Flag" }, { 0x0055, 0x0046, "LT", "Current Ward" }, { 0x0058, 0x0000, "SQ", "?" }, { 0x0060, 0x3000, "SQ", "Histogram Sequence" }, { 0x0060, 0x3002, "US", "Histogram Number of Bins" }, { 0x0060, 0x3004, "xs", "Histogram First Bin Value" }, { 0x0060, 0x3006, "xs", "Histogram Last Bin Value" }, { 0x0060, 0x3008, "US", "Histogram Bin Width" }, { 0x0060, 0x3010, "LO", "Histogram Explanation" }, { 0x0060, 0x3020, "UL", "Histogram Data" }, { 0x0070, 0x0001, "SQ", "Graphic Annotation Sequence" }, { 0x0070, 0x0002, "CS", "Graphic Layer" }, { 0x0070, 0x0003, "CS", "Bounding Box Annotation Units" }, { 0x0070, 0x0004, "CS", "Anchor Point Annotation Units" }, { 0x0070, 0x0005, "CS", "Graphic Annotation Units" }, { 0x0070, 0x0006, "ST", "Unformatted Text Value" }, { 0x0070, 0x0008, "SQ", "Text Object Sequence" }, { 0x0070, 0x0009, "SQ", "Graphic Object Sequence" }, { 0x0070, 0x0010, "FL", "Bounding Box TLHC" }, { 0x0070, 0x0011, "FL", "Bounding Box BRHC" }, { 0x0070, 0x0014, "FL", "Anchor Point" }, { 0x0070, 0x0015, "CS", "Anchor Point Visibility" }, { 0x0070, 0x0020, "US", "Graphic Dimensions" }, { 0x0070, 0x0021, "US", "Number Of Graphic Points" }, { 0x0070, 0x0022, "FL", "Graphic Data" }, { 0x0070, 0x0023, "CS", "Graphic Type" }, { 0x0070, 0x0024, "CS", "Graphic Filled" }, { 0x0070, 0x0040, "IS", "Image Rotation" }, { 0x0070, 0x0041, "CS", "Image Horizontal Flip" }, { 0x0070, 0x0050, "US", "Displayed Area TLHC" }, { 0x0070, 0x0051, "US", "Displayed Area BRHC" }, { 0x0070, 0x0060, "SQ", "Graphic Layer Sequence" }, { 0x0070, 0x0062, "IS", "Graphic Layer Order" }, { 0x0070, 0x0066, "US", "Graphic Layer Recommended Display Value" }, { 0x0070, 0x0068, "LO", "Graphic Layer Description" }, { 0x0070, 0x0080, "CS", "Presentation Label" }, { 0x0070, 0x0081, "LO", "Presentation Description" }, { 0x0070, 0x0082, "DA", "Presentation Creation Date" }, { 0x0070, 0x0083, "TM", "Presentation Creation Time" }, { 0x0070, 0x0084, "PN", "Presentation Creator's Name" }, { 0x0087, 0x0010, "CS", "Media Type" }, { 0x0087, 0x0020, "CS", "Media Location" }, { 0x0087, 0x0050, "IS", "Estimated Retrieve Time" }, { 0x0088, 0x0000, "UL", "Storage Group Length" }, { 0x0088, 0x0130, "SH", "Storage Media FileSet ID" }, { 0x0088, 0x0140, "UI", "Storage Media FileSet UID" }, { 0x0088, 0x0200, "SQ", "Icon Image Sequence" }, { 0x0088, 0x0904, "LO", "Topic Title" }, { 0x0088, 0x0906, "ST", "Topic Subject" }, { 0x0088, 0x0910, "LO", "Topic Author" }, { 0x0088, 0x0912, "LO", "Topic Key Words" }, { 0x0095, 0x0001, "LT", "Examination Folder ID" }, { 0x0095, 0x0004, "UL", "Folder Reported Status" }, { 0x0095, 0x0005, "LT", "Folder Reporting Radiologist" }, { 0x0095, 0x0007, "LT", "SIENET ISA PLA" }, { 0x0099, 0x0002, "UL", "Data Object Attributes" }, { 0x00e1, 0x0001, "US", "Data Dictionary Version" }, { 0x00e1, 0x0014, "LT", "?" }, { 0x00e1, 0x0022, "DS", "?" }, { 0x00e1, 0x0023, "DS", "?" }, { 0x00e1, 0x0024, "LT", "?" }, { 0x00e1, 0x0025, "LT", "?" }, { 0x00e1, 0x0040, "SH", "Offset From CT MR Images" }, { 0x0193, 0x0002, "DS", "RIS Key" }, { 0x0307, 0x0001, "UN", "RIS Worklist IMGEF" }, { 0x0309, 0x0001, "UN", "RIS Report IMGEF" }, { 0x0601, 0x0000, "SH", "Implementation Version" }, { 0x0601, 0x0020, "DS", "Relative Table Position" }, { 0x0601, 0x0021, "DS", "Relative Table Height" }, { 0x0601, 0x0030, "SH", "Surview Direction" }, { 0x0601, 0x0031, "DS", "Surview Length" }, { 0x0601, 0x0050, "SH", "Image View Type" }, { 0x0601, 0x0070, "DS", "Batch Number" }, { 0x0601, 0x0071, "DS", "Batch Size" }, { 0x0601, 0x0072, "DS", "Batch Slice Number" }, { 0x1000, 0x0000, "xs", "?" }, { 0x1000, 0x0001, "US", "Run Length Triplet" }, { 0x1000, 0x0002, "US", "Huffman Table Size" }, { 0x1000, 0x0003, "US", "Huffman Table Triplet" }, { 0x1000, 0x0004, "US", "Shift Table Size" }, { 0x1000, 0x0005, "US", "Shift Table Triplet" }, { 0x1010, 0x0000, "xs", "?" }, { 0x1369, 0x0000, "US", "?" }, { 0x2000, 0x0000, "UL", "Film Session Group Length" }, { 0x2000, 0x0010, "IS", "Number of Copies" }, { 0x2000, 0x0020, "CS", "Print Priority" }, { 0x2000, 0x0030, "CS", "Medium Type" }, { 0x2000, 0x0040, "CS", "Film Destination" }, { 0x2000, 0x0050, "LO", "Film Session Label" }, { 0x2000, 0x0060, "IS", "Memory Allocation" }, { 0x2000, 0x0500, "SQ", "Referenced Film Box Sequence" }, { 0x2010, 0x0000, "UL", "Film Box Group Length" }, { 0x2010, 0x0010, "ST", "Image Display Format" }, { 0x2010, 0x0030, "CS", "Annotation Display Format ID" }, { 0x2010, 0x0040, "CS", "Film Orientation" }, { 0x2010, 0x0050, "CS", "Film Size ID" }, { 0x2010, 0x0060, "CS", "Magnification Type" }, { 0x2010, 0x0080, "CS", "Smoothing Type" }, { 0x2010, 0x0100, "CS", "Border Density" }, { 0x2010, 0x0110, "CS", "Empty Image Density" }, { 0x2010, 0x0120, "US", "Min Density" }, { 0x2010, 0x0130, "US", "Max Density" }, { 0x2010, 0x0140, "CS", "Trim" }, { 0x2010, 0x0150, "ST", "Configuration Information" }, { 0x2010, 0x0500, "SQ", "Referenced Film Session Sequence" }, { 0x2010, 0x0510, "SQ", "Referenced Image Box Sequence" }, { 0x2010, 0x0520, "SQ", "Referenced Basic Annotation Box Sequence" }, { 0x2020, 0x0000, "UL", "Image Box Group Length" }, { 0x2020, 0x0010, "US", "Image Box Position" }, { 0x2020, 0x0020, "CS", "Polarity" }, { 0x2020, 0x0030, "DS", "Requested Image Size" }, { 0x2020, 0x0110, "SQ", "Preformatted Grayscale Image Sequence" }, { 0x2020, 0x0111, "SQ", "Preformatted Color Image Sequence" }, { 0x2020, 0x0130, "SQ", "Referenced Image Overlay Box Sequence" }, { 0x2020, 0x0140, "SQ", "Referenced VOI LUT Box Sequence" }, { 0x2030, 0x0000, "UL", "Annotation Group Length" }, { 0x2030, 0x0010, "US", "Annotation Position" }, { 0x2030, 0x0020, "LO", "Text String" }, { 0x2040, 0x0000, "UL", "Overlay Box Group Length" }, { 0x2040, 0x0010, "SQ", "Referenced Overlay Plane Sequence" }, { 0x2040, 0x0011, "US", "Referenced Overlay Plane Groups" }, { 0x2040, 0x0060, "CS", "Overlay Magnification Type" }, { 0x2040, 0x0070, "CS", "Overlay Smoothing Type" }, { 0x2040, 0x0080, "CS", "Overlay Foreground Density" }, { 0x2040, 0x0090, "CS", "Overlay Mode" }, { 0x2040, 0x0100, "CS", "Threshold Density" }, { 0x2040, 0x0500, "SQ", "Referenced Overlay Image Box Sequence" }, { 0x2050, 0x0010, "SQ", "Presentation LUT Sequence" }, { 0x2050, 0x0020, "CS", "Presentation LUT Shape" }, { 0x2100, 0x0000, "UL", "Print Job Group Length" }, { 0x2100, 0x0020, "CS", "Execution Status" }, { 0x2100, 0x0030, "CS", "Execution Status Info" }, { 0x2100, 0x0040, "DA", "Creation Date" }, { 0x2100, 0x0050, "TM", "Creation Time" }, { 0x2100, 0x0070, "AE", "Originator" }, { 0x2100, 0x0500, "SQ", "Referenced Print Job Sequence" }, { 0x2110, 0x0000, "UL", "Printer Group Length" }, { 0x2110, 0x0010, "CS", "Printer Status" }, { 0x2110, 0x0020, "CS", "Printer Status Info" }, { 0x2110, 0x0030, "LO", "Printer Name" }, { 0x2110, 0x0099, "SH", "Print Queue ID" }, { 0x3002, 0x0002, "SH", "RT Image Label" }, { 0x3002, 0x0003, "LO", "RT Image Name" }, { 0x3002, 0x0004, "ST", "RT Image Description" }, { 0x3002, 0x000a, "CS", "Reported Values Origin" }, { 0x3002, 0x000c, "CS", "RT Image Plane" }, { 0x3002, 0x000e, "DS", "X-Ray Image Receptor Angle" }, { 0x3002, 0x0010, "DS", "RTImageOrientation" }, { 0x3002, 0x0011, "DS", "Image Plane Pixel Spacing" }, { 0x3002, 0x0012, "DS", "RT Image Position" }, { 0x3002, 0x0020, "SH", "Radiation Machine Name" }, { 0x3002, 0x0022, "DS", "Radiation Machine SAD" }, { 0x3002, 0x0024, "DS", "Radiation Machine SSD" }, { 0x3002, 0x0026, "DS", "RT Image SID" }, { 0x3002, 0x0028, "DS", "Source to Reference Object Distance" }, { 0x3002, 0x0029, "IS", "Fraction Number" }, { 0x3002, 0x0030, "SQ", "Exposure Sequence" }, { 0x3002, 0x0032, "DS", "Meterset Exposure" }, { 0x3004, 0x0001, "CS", "DVH Type" }, { 0x3004, 0x0002, "CS", "Dose Units" }, { 0x3004, 0x0004, "CS", "Dose Type" }, { 0x3004, 0x0006, "LO", "Dose Comment" }, { 0x3004, 0x0008, "DS", "Normalization Point" }, { 0x3004, 0x000a, "CS", "Dose Summation Type" }, { 0x3004, 0x000c, "DS", "GridFrame Offset Vector" }, { 0x3004, 0x000e, "DS", "Dose Grid Scaling" }, { 0x3004, 0x0010, "SQ", "RT Dose ROI Sequence" }, { 0x3004, 0x0012, "DS", "Dose Value" }, { 0x3004, 0x0040, "DS", "DVH Normalization Point" }, { 0x3004, 0x0042, "DS", "DVH Normalization Dose Value" }, { 0x3004, 0x0050, "SQ", "DVH Sequence" }, { 0x3004, 0x0052, "DS", "DVH Dose Scaling" }, { 0x3004, 0x0054, "CS", "DVH Volume Units" }, { 0x3004, 0x0056, "IS", "DVH Number of Bins" }, { 0x3004, 0x0058, "DS", "DVH Data" }, { 0x3004, 0x0060, "SQ", "DVH Referenced ROI Sequence" }, { 0x3004, 0x0062, "CS", "DVH ROI Contribution Type" }, { 0x3004, 0x0070, "DS", "DVH Minimum Dose" }, { 0x3004, 0x0072, "DS", "DVH Maximum Dose" }, { 0x3004, 0x0074, "DS", "DVH Mean Dose" }, { 0x3006, 0x0002, "SH", "Structure Set Label" }, { 0x3006, 0x0004, "LO", "Structure Set Name" }, { 0x3006, 0x0006, "ST", "Structure Set Description" }, { 0x3006, 0x0008, "DA", "Structure Set Date" }, { 0x3006, 0x0009, "TM", "Structure Set Time" }, { 0x3006, 0x0010, "SQ", "Referenced Frame of Reference Sequence" }, { 0x3006, 0x0012, "SQ", "RT Referenced Study Sequence" }, { 0x3006, 0x0014, "SQ", "RT Referenced Series Sequence" }, { 0x3006, 0x0016, "SQ", "Contour Image Sequence" }, { 0x3006, 0x0020, "SQ", "Structure Set ROI Sequence" }, { 0x3006, 0x0022, "IS", "ROI Number" }, { 0x3006, 0x0024, "UI", "Referenced Frame of Reference UID" }, { 0x3006, 0x0026, "LO", "ROI Name" }, { 0x3006, 0x0028, "ST", "ROI Description" }, { 0x3006, 0x002a, "IS", "ROI Display Color" }, { 0x3006, 0x002c, "DS", "ROI Volume" }, { 0x3006, 0x0030, "SQ", "RT Related ROI Sequence" }, { 0x3006, 0x0033, "CS", "RT ROI Relationship" }, { 0x3006, 0x0036, "CS", "ROI Generation Algorithm" }, { 0x3006, 0x0038, "LO", "ROI Generation Description" }, { 0x3006, 0x0039, "SQ", "ROI Contour Sequence" }, { 0x3006, 0x0040, "SQ", "Contour Sequence" }, { 0x3006, 0x0042, "CS", "Contour Geometric Type" }, { 0x3006, 0x0044, "DS", "Contour SlabT hickness" }, { 0x3006, 0x0045, "DS", "Contour Offset Vector" }, { 0x3006, 0x0046, "IS", "Number of Contour Points" }, { 0x3006, 0x0050, "DS", "Contour Data" }, { 0x3006, 0x0080, "SQ", "RT ROI Observations Sequence" }, { 0x3006, 0x0082, "IS", "Observation Number" }, { 0x3006, 0x0084, "IS", "Referenced ROI Number" }, { 0x3006, 0x0085, "SH", "ROI Observation Label" }, { 0x3006, 0x0086, "SQ", "RT ROI Identification Code Sequence" }, { 0x3006, 0x0088, "ST", "ROI Observation Description" }, { 0x3006, 0x00a0, "SQ", "Related RT ROI Observations Sequence" }, { 0x3006, 0x00a4, "CS", "RT ROI Interpreted Type" }, { 0x3006, 0x00a6, "PN", "ROI Interpreter" }, { 0x3006, 0x00b0, "SQ", "ROI Physical Properties Sequence" }, { 0x3006, 0x00b2, "CS", "ROI Physical Property" }, { 0x3006, 0x00b4, "DS", "ROI Physical Property Value" }, { 0x3006, 0x00c0, "SQ", "Frame of Reference Relationship Sequence" }, { 0x3006, 0x00c2, "UI", "Related Frame of Reference UID" }, { 0x3006, 0x00c4, "CS", "Frame of Reference Transformation Type" }, { 0x3006, 0x00c6, "DS", "Frame of Reference Transformation Matrix" }, { 0x3006, 0x00c8, "LO", "Frame of Reference Transformation Comment" }, { 0x300a, 0x0002, "SH", "RT Plan Label" }, { 0x300a, 0x0003, "LO", "RT Plan Name" }, { 0x300a, 0x0004, "ST", "RT Plan Description" }, { 0x300a, 0x0006, "DA", "RT Plan Date" }, { 0x300a, 0x0007, "TM", "RT Plan Time" }, { 0x300a, 0x0009, "LO", "Treatment Protocols" }, { 0x300a, 0x000a, "CS", "Treatment Intent" }, { 0x300a, 0x000b, "LO", "Treatment Sites" }, { 0x300a, 0x000c, "CS", "RT Plan Geometry" }, { 0x300a, 0x000e, "ST", "Prescription Description" }, { 0x300a, 0x0010, "SQ", "Dose ReferenceSequence" }, { 0x300a, 0x0012, "IS", "Dose ReferenceNumber" }, { 0x300a, 0x0014, "CS", "Dose Reference Structure Type" }, { 0x300a, 0x0016, "LO", "Dose ReferenceDescription" }, { 0x300a, 0x0018, "DS", "Dose Reference Point Coordinates" }, { 0x300a, 0x001a, "DS", "Nominal Prior Dose" }, { 0x300a, 0x0020, "CS", "Dose Reference Type" }, { 0x300a, 0x0021, "DS", "Constraint Weight" }, { 0x300a, 0x0022, "DS", "Delivery Warning Dose" }, { 0x300a, 0x0023, "DS", "Delivery Maximum Dose" }, { 0x300a, 0x0025, "DS", "Target Minimum Dose" }, { 0x300a, 0x0026, "DS", "Target Prescription Dose" }, { 0x300a, 0x0027, "DS", "Target Maximum Dose" }, { 0x300a, 0x0028, "DS", "Target Underdose Volume Fraction" }, { 0x300a, 0x002a, "DS", "Organ at Risk Full-volume Dose" }, { 0x300a, 0x002b, "DS", "Organ at Risk Limit Dose" }, { 0x300a, 0x002c, "DS", "Organ at Risk Maximum Dose" }, { 0x300a, 0x002d, "DS", "Organ at Risk Overdose Volume Fraction" }, { 0x300a, 0x0040, "SQ", "Tolerance Table Sequence" }, { 0x300a, 0x0042, "IS", "Tolerance Table Number" }, { 0x300a, 0x0043, "SH", "Tolerance Table Label" }, { 0x300a, 0x0044, "DS", "Gantry Angle Tolerance" }, { 0x300a, 0x0046, "DS", "Beam Limiting Device Angle Tolerance" }, { 0x300a, 0x0048, "SQ", "Beam Limiting Device Tolerance Sequence" }, { 0x300a, 0x004a, "DS", "Beam Limiting Device Position Tolerance" }, { 0x300a, 0x004c, "DS", "Patient Support Angle Tolerance" }, { 0x300a, 0x004e, "DS", "Table Top Eccentric Angle Tolerance" }, { 0x300a, 0x0051, "DS", "Table Top Vertical Position Tolerance" }, { 0x300a, 0x0052, "DS", "Table Top Longitudinal Position Tolerance" }, { 0x300a, 0x0053, "DS", "Table Top Lateral Position Tolerance" }, { 0x300a, 0x0055, "CS", "RT Plan Relationship" }, { 0x300a, 0x0070, "SQ", "Fraction Group Sequence" }, { 0x300a, 0x0071, "IS", "Fraction Group Number" }, { 0x300a, 0x0078, "IS", "Number of Fractions Planned" }, { 0x300a, 0x0079, "IS", "Number of Fractions Per Day" }, { 0x300a, 0x007a, "IS", "Repeat Fraction Cycle Length" }, { 0x300a, 0x007b, "LT", "Fraction Pattern" }, { 0x300a, 0x0080, "IS", "Number of Beams" }, { 0x300a, 0x0082, "DS", "Beam Dose Specification Point" }, { 0x300a, 0x0084, "DS", "Beam Dose" }, { 0x300a, 0x0086, "DS", "Beam Meterset" }, { 0x300a, 0x00a0, "IS", "Number of Brachy Application Setups" }, { 0x300a, 0x00a2, "DS", "Brachy Application Setup Dose Specification Point" }, { 0x300a, 0x00a4, "DS", "Brachy Application Setup Dose" }, { 0x300a, 0x00b0, "SQ", "Beam Sequence" }, { 0x300a, 0x00b2, "SH", "Treatment Machine Name " }, { 0x300a, 0x00b3, "CS", "Primary Dosimeter Unit" }, { 0x300a, 0x00b4, "DS", "Source-Axis Distance" }, { 0x300a, 0x00b6, "SQ", "Beam Limiting Device Sequence" }, { 0x300a, 0x00b8, "CS", "RT Beam Limiting Device Type" }, { 0x300a, 0x00ba, "DS", "Source to Beam Limiting Device Distance" }, { 0x300a, 0x00bc, "IS", "Number of Leaf/Jaw Pairs" }, { 0x300a, 0x00be, "DS", "Leaf Position Boundaries" }, { 0x300a, 0x00c0, "IS", "Beam Number" }, { 0x300a, 0x00c2, "LO", "Beam Name" }, { 0x300a, 0x00c3, "ST", "Beam Description" }, { 0x300a, 0x00c4, "CS", "Beam Type" }, { 0x300a, 0x00c6, "CS", "Radiation Type" }, { 0x300a, 0x00c8, "IS", "Reference Image Number" }, { 0x300a, 0x00ca, "SQ", "Planned Verification Image Sequence" }, { 0x300a, 0x00cc, "LO", "Imaging Device Specific Acquisition Parameters" }, { 0x300a, 0x00ce, "CS", "Treatment Delivery Type" }, { 0x300a, 0x00d0, "IS", "Number of Wedges" }, { 0x300a, 0x00d1, "SQ", "Wedge Sequence" }, { 0x300a, 0x00d2, "IS", "Wedge Number" }, { 0x300a, 0x00d3, "CS", "Wedge Type" }, { 0x300a, 0x00d4, "SH", "Wedge ID" }, { 0x300a, 0x00d5, "IS", "Wedge Angle" }, { 0x300a, 0x00d6, "DS", "Wedge Factor" }, { 0x300a, 0x00d8, "DS", "Wedge Orientation" }, { 0x300a, 0x00da, "DS", "Source to Wedge Tray Distance" }, { 0x300a, 0x00e0, "IS", "Number of Compensators" }, { 0x300a, 0x00e1, "SH", "Material ID" }, { 0x300a, 0x00e2, "DS", "Total Compensator Tray Factor" }, { 0x300a, 0x00e3, "SQ", "Compensator Sequence" }, { 0x300a, 0x00e4, "IS", "Compensator Number" }, { 0x300a, 0x00e5, "SH", "Compensator ID" }, { 0x300a, 0x00e6, "DS", "Source to Compensator Tray Distance" }, { 0x300a, 0x00e7, "IS", "Compensator Rows" }, { 0x300a, 0x00e8, "IS", "Compensator Columns" }, { 0x300a, 0x00e9, "DS", "Compensator Pixel Spacing" }, { 0x300a, 0x00ea, "DS", "Compensator Position" }, { 0x300a, 0x00eb, "DS", "Compensator Transmission Data" }, { 0x300a, 0x00ec, "DS", "Compensator Thickness Data" }, { 0x300a, 0x00ed, "IS", "Number of Boli" }, { 0x300a, 0x00f0, "IS", "Number of Blocks" }, { 0x300a, 0x00f2, "DS", "Total Block Tray Factor" }, { 0x300a, 0x00f4, "SQ", "Block Sequence" }, { 0x300a, 0x00f5, "SH", "Block Tray ID" }, { 0x300a, 0x00f6, "DS", "Source to Block Tray Distance" }, { 0x300a, 0x00f8, "CS", "Block Type" }, { 0x300a, 0x00fa, "CS", "Block Divergence" }, { 0x300a, 0x00fc, "IS", "Block Number" }, { 0x300a, 0x00fe, "LO", "Block Name" }, { 0x300a, 0x0100, "DS", "Block Thickness" }, { 0x300a, 0x0102, "DS", "Block Transmission" }, { 0x300a, 0x0104, "IS", "Block Number of Points" }, { 0x300a, 0x0106, "DS", "Block Data" }, { 0x300a, 0x0107, "SQ", "Applicator Sequence" }, { 0x300a, 0x0108, "SH", "Applicator ID" }, { 0x300a, 0x0109, "CS", "Applicator Type" }, { 0x300a, 0x010a, "LO", "Applicator Description" }, { 0x300a, 0x010c, "DS", "Cumulative Dose Reference Coefficient" }, { 0x300a, 0x010e, "DS", "Final Cumulative Meterset Weight" }, { 0x300a, 0x0110, "IS", "Number of Control Points" }, { 0x300a, 0x0111, "SQ", "Control Point Sequence" }, { 0x300a, 0x0112, "IS", "Control Point Index" }, { 0x300a, 0x0114, "DS", "Nominal Beam Energy" }, { 0x300a, 0x0115, "DS", "Dose Rate Set" }, { 0x300a, 0x0116, "SQ", "Wedge Position Sequence" }, { 0x300a, 0x0118, "CS", "Wedge Position" }, { 0x300a, 0x011a, "SQ", "Beam Limiting Device Position Sequence" }, { 0x300a, 0x011c, "DS", "Leaf Jaw Positions" }, { 0x300a, 0x011e, "DS", "Gantry Angle" }, { 0x300a, 0x011f, "CS", "Gantry Rotation Direction" }, { 0x300a, 0x0120, "DS", "Beam Limiting Device Angle" }, { 0x300a, 0x0121, "CS", "Beam Limiting Device Rotation Direction" }, { 0x300a, 0x0122, "DS", "Patient Support Angle" }, { 0x300a, 0x0123, "CS", "Patient Support Rotation Direction" }, { 0x300a, 0x0124, "DS", "Table Top Eccentric Axis Distance" }, { 0x300a, 0x0125, "DS", "Table Top Eccentric Angle" }, { 0x300a, 0x0126, "CS", "Table Top Eccentric Rotation Direction" }, { 0x300a, 0x0128, "DS", "Table Top Vertical Position" }, { 0x300a, 0x0129, "DS", "Table Top Longitudinal Position" }, { 0x300a, 0x012a, "DS", "Table Top Lateral Position" }, { 0x300a, 0x012c, "DS", "Isocenter Position" }, { 0x300a, 0x012e, "DS", "Surface Entry Point" }, { 0x300a, 0x0130, "DS", "Source to Surface Distance" }, { 0x300a, 0x0134, "DS", "Cumulative Meterset Weight" }, { 0x300a, 0x0180, "SQ", "Patient Setup Sequence" }, { 0x300a, 0x0182, "IS", "Patient Setup Number" }, { 0x300a, 0x0184, "LO", "Patient Additional Position" }, { 0x300a, 0x0190, "SQ", "Fixation Device Sequence" }, { 0x300a, 0x0192, "CS", "Fixation Device Type" }, { 0x300a, 0x0194, "SH", "Fixation Device Label" }, { 0x300a, 0x0196, "ST", "Fixation Device Description" }, { 0x300a, 0x0198, "SH", "Fixation Device Position" }, { 0x300a, 0x01a0, "SQ", "Shielding Device Sequence" }, { 0x300a, 0x01a2, "CS", "Shielding Device Type" }, { 0x300a, 0x01a4, "SH", "Shielding Device Label" }, { 0x300a, 0x01a6, "ST", "Shielding Device Description" }, { 0x300a, 0x01a8, "SH", "Shielding Device Position" }, { 0x300a, 0x01b0, "CS", "Setup Technique" }, { 0x300a, 0x01b2, "ST", "Setup TechniqueDescription" }, { 0x300a, 0x01b4, "SQ", "Setup Device Sequence" }, { 0x300a, 0x01b6, "CS", "Setup Device Type" }, { 0x300a, 0x01b8, "SH", "Setup Device Label" }, { 0x300a, 0x01ba, "ST", "Setup Device Description" }, { 0x300a, 0x01bc, "DS", "Setup Device Parameter" }, { 0x300a, 0x01d0, "ST", "Setup ReferenceDescription" }, { 0x300a, 0x01d2, "DS", "Table Top Vertical Setup Displacement" }, { 0x300a, 0x01d4, "DS", "Table Top Longitudinal Setup Displacement" }, { 0x300a, 0x01d6, "DS", "Table Top Lateral Setup Displacement" }, { 0x300a, 0x0200, "CS", "Brachy Treatment Technique" }, { 0x300a, 0x0202, "CS", "Brachy Treatment Type" }, { 0x300a, 0x0206, "SQ", "Treatment Machine Sequence" }, { 0x300a, 0x0210, "SQ", "Source Sequence" }, { 0x300a, 0x0212, "IS", "Source Number" }, { 0x300a, 0x0214, "CS", "Source Type" }, { 0x300a, 0x0216, "LO", "Source Manufacturer" }, { 0x300a, 0x0218, "DS", "Active Source Diameter" }, { 0x300a, 0x021a, "DS", "Active Source Length" }, { 0x300a, 0x0222, "DS", "Source Encapsulation Nominal Thickness" }, { 0x300a, 0x0224, "DS", "Source Encapsulation Nominal Transmission" }, { 0x300a, 0x0226, "LO", "Source IsotopeName" }, { 0x300a, 0x0228, "DS", "Source Isotope Half Life" }, { 0x300a, 0x022a, "DS", "Reference Air Kerma Rate" }, { 0x300a, 0x022c, "DA", "Air Kerma Rate Reference Date" }, { 0x300a, 0x022e, "TM", "Air Kerma Rate Reference Time" }, { 0x300a, 0x0230, "SQ", "Application Setup Sequence" }, { 0x300a, 0x0232, "CS", "Application Setup Type" }, { 0x300a, 0x0234, "IS", "Application Setup Number" }, { 0x300a, 0x0236, "LO", "Application Setup Name" }, { 0x300a, 0x0238, "LO", "Application Setup Manufacturer" }, { 0x300a, 0x0240, "IS", "Template Number" }, { 0x300a, 0x0242, "SH", "Template Type" }, { 0x300a, 0x0244, "LO", "Template Name" }, { 0x300a, 0x0250, "DS", "Total Reference Air Kerma" }, { 0x300a, 0x0260, "SQ", "Brachy Accessory Device Sequence" }, { 0x300a, 0x0262, "IS", "Brachy Accessory Device Number" }, { 0x300a, 0x0263, "SH", "Brachy Accessory Device ID" }, { 0x300a, 0x0264, "CS", "Brachy Accessory Device Type" }, { 0x300a, 0x0266, "LO", "Brachy Accessory Device Name" }, { 0x300a, 0x026a, "DS", "Brachy Accessory Device Nominal Thickness" }, { 0x300a, 0x026c, "DS", "Brachy Accessory Device Nominal Transmission" }, { 0x300a, 0x0280, "SQ", "Channel Sequence" }, { 0x300a, 0x0282, "IS", "Channel Number" }, { 0x300a, 0x0284, "DS", "Channel Length" }, { 0x300a, 0x0286, "DS", "Channel Total Time" }, { 0x300a, 0x0288, "CS", "Source Movement Type" }, { 0x300a, 0x028a, "IS", "Number of Pulses" }, { 0x300a, 0x028c, "DS", "Pulse Repetition Interval" }, { 0x300a, 0x0290, "IS", "Source Applicator Number" }, { 0x300a, 0x0291, "SH", "Source Applicator ID" }, { 0x300a, 0x0292, "CS", "Source Applicator Type" }, { 0x300a, 0x0294, "LO", "Source Applicator Name" }, { 0x300a, 0x0296, "DS", "Source Applicator Length" }, { 0x300a, 0x0298, "LO", "Source Applicator Manufacturer" }, { 0x300a, 0x029c, "DS", "Source Applicator Wall Nominal Thickness" }, { 0x300a, 0x029e, "DS", "Source Applicator Wall Nominal Transmission" }, { 0x300a, 0x02a0, "DS", "Source Applicator Step Size" }, { 0x300a, 0x02a2, "IS", "Transfer Tube Number" }, { 0x300a, 0x02a4, "DS", "Transfer Tube Length" }, { 0x300a, 0x02b0, "SQ", "Channel Shield Sequence" }, { 0x300a, 0x02b2, "IS", "Channel Shield Number" }, { 0x300a, 0x02b3, "SH", "Channel Shield ID" }, { 0x300a, 0x02b4, "LO", "Channel Shield Name" }, { 0x300a, 0x02b8, "DS", "Channel Shield Nominal Thickness" }, { 0x300a, 0x02ba, "DS", "Channel Shield Nominal Transmission" }, { 0x300a, 0x02c8, "DS", "Final Cumulative Time Weight" }, { 0x300a, 0x02d0, "SQ", "Brachy Control Point Sequence" }, { 0x300a, 0x02d2, "DS", "Control Point Relative Position" }, { 0x300a, 0x02d4, "DS", "Control Point 3D Position" }, { 0x300a, 0x02d6, "DS", "Cumulative Time Weight" }, { 0x300c, 0x0002, "SQ", "Referenced RT Plan Sequence" }, { 0x300c, 0x0004, "SQ", "Referenced Beam Sequence" }, { 0x300c, 0x0006, "IS", "Referenced Beam Number" }, { 0x300c, 0x0007, "IS", "Referenced Reference Image Number" }, { 0x300c, 0x0008, "DS", "Start Cumulative Meterset Weight" }, { 0x300c, 0x0009, "DS", "End Cumulative Meterset Weight" }, { 0x300c, 0x000a, "SQ", "Referenced Brachy Application Setup Sequence" }, { 0x300c, 0x000c, "IS", "Referenced Brachy Application Setup Number" }, { 0x300c, 0x000e, "IS", "Referenced Source Number" }, { 0x300c, 0x0020, "SQ", "Referenced Fraction Group Sequence" }, { 0x300c, 0x0022, "IS", "Referenced Fraction Group Number" }, { 0x300c, 0x0040, "SQ", "Referenced Verification Image Sequence" }, { 0x300c, 0x0042, "SQ", "Referenced Reference Image Sequence" }, { 0x300c, 0x0050, "SQ", "Referenced Dose Reference Sequence" }, { 0x300c, 0x0051, "IS", "Referenced Dose Reference Number" }, { 0x300c, 0x0055, "SQ", "Brachy Referenced Dose Reference Sequence" }, { 0x300c, 0x0060, "SQ", "Referenced Structure Set Sequence" }, { 0x300c, 0x006a, "IS", "Referenced Patient Setup Number" }, { 0x300c, 0x0080, "SQ", "Referenced Dose Sequence" }, { 0x300c, 0x00a0, "IS", "Referenced Tolerance Table Number" }, { 0x300c, 0x00b0, "SQ", "Referenced Bolus Sequence" }, { 0x300c, 0x00c0, "IS", "Referenced Wedge Number" }, { 0x300c, 0x00d0, "IS", "Referenced Compensato rNumber" }, { 0x300c, 0x00e0, "IS", "Referenced Block Number" }, { 0x300c, 0x00f0, "IS", "Referenced Control Point" }, { 0x300e, 0x0002, "CS", "Approval Status" }, { 0x300e, 0x0004, "DA", "Review Date" }, { 0x300e, 0x0005, "TM", "Review Time" }, { 0x300e, 0x0008, "PN", "Reviewer Name" }, { 0x4000, 0x0000, "UL", "Text Group Length" }, { 0x4000, 0x0010, "LT", "Text Arbitrary" }, { 0x4000, 0x4000, "LT", "Text Comments" }, { 0x4008, 0x0000, "UL", "Results Group Length" }, { 0x4008, 0x0040, "SH", "Results ID" }, { 0x4008, 0x0042, "LO", "Results ID Issuer" }, { 0x4008, 0x0050, "SQ", "Referenced Interpretation Sequence" }, { 0x4008, 0x00ff, "CS", "Report Production Status" }, { 0x4008, 0x0100, "DA", "Interpretation Recorded Date" }, { 0x4008, 0x0101, "TM", "Interpretation Recorded Time" }, { 0x4008, 0x0102, "PN", "Interpretation Recorder" }, { 0x4008, 0x0103, "LO", "Reference to Recorded Sound" }, { 0x4008, 0x0108, "DA", "Interpretation Transcription Date" }, { 0x4008, 0x0109, "TM", "Interpretation Transcription Time" }, { 0x4008, 0x010a, "PN", "Interpretation Transcriber" }, { 0x4008, 0x010b, "ST", "Interpretation Text" }, { 0x4008, 0x010c, "PN", "Interpretation Author" }, { 0x4008, 0x0111, "SQ", "Interpretation Approver Sequence" }, { 0x4008, 0x0112, "DA", "Interpretation Approval Date" }, { 0x4008, 0x0113, "TM", "Interpretation Approval Time" }, { 0x4008, 0x0114, "PN", "Physician Approving Interpretation" }, { 0x4008, 0x0115, "LT", "Interpretation Diagnosis Description" }, { 0x4008, 0x0117, "SQ", "InterpretationDiagnosis Code Sequence" }, { 0x4008, 0x0118, "SQ", "Results Distribution List Sequence" }, { 0x4008, 0x0119, "PN", "Distribution Name" }, { 0x4008, 0x011a, "LO", "Distribution Address" }, { 0x4008, 0x0200, "SH", "Interpretation ID" }, { 0x4008, 0x0202, "LO", "Interpretation ID Issuer" }, { 0x4008, 0x0210, "CS", "Interpretation Type ID" }, { 0x4008, 0x0212, "CS", "Interpretation Status ID" }, { 0x4008, 0x0300, "ST", "Impressions" }, { 0x4008, 0x4000, "ST", "Results Comments" }, { 0x4009, 0x0001, "LT", "Report ID" }, { 0x4009, 0x0020, "LT", "Report Status" }, { 0x4009, 0x0030, "DA", "Report Creation Date" }, { 0x4009, 0x0070, "LT", "Report Approving Physician" }, { 0x4009, 0x00e0, "LT", "Report Text" }, { 0x4009, 0x00e1, "LT", "Report Author" }, { 0x4009, 0x00e3, "LT", "Reporting Radiologist" }, { 0x5000, 0x0000, "UL", "Curve Group Length" }, { 0x5000, 0x0005, "US", "Curve Dimensions" }, { 0x5000, 0x0010, "US", "Number of Points" }, { 0x5000, 0x0020, "CS", "Type of Data" }, { 0x5000, 0x0022, "LO", "Curve Description" }, { 0x5000, 0x0030, "SH", "Axis Units" }, { 0x5000, 0x0040, "SH", "Axis Labels" }, { 0x5000, 0x0103, "US", "Data Value Representation" }, { 0x5000, 0x0104, "US", "Minimum Coordinate Value" }, { 0x5000, 0x0105, "US", "Maximum Coordinate Value" }, { 0x5000, 0x0106, "SH", "Curve Range" }, { 0x5000, 0x0110, "US", "Curve Data Descriptor" }, { 0x5000, 0x0112, "US", "Coordinate Start Value" }, { 0x5000, 0x0114, "US", "Coordinate Step Value" }, { 0x5000, 0x1001, "CS", "Curve Activation Layer" }, { 0x5000, 0x2000, "US", "Audio Type" }, { 0x5000, 0x2002, "US", "Audio Sample Format" }, { 0x5000, 0x2004, "US", "Number of Channels" }, { 0x5000, 0x2006, "UL", "Number of Samples" }, { 0x5000, 0x2008, "UL", "Sample Rate" }, { 0x5000, 0x200a, "UL", "Total Time" }, { 0x5000, 0x200c, "xs", "Audio Sample Data" }, { 0x5000, 0x200e, "LT", "Audio Comments" }, { 0x5000, 0x2500, "LO", "Curve Label" }, { 0x5000, 0x2600, "SQ", "CurveReferenced Overlay Sequence" }, { 0x5000, 0x2610, "US", "CurveReferenced Overlay Group" }, { 0x5000, 0x3000, "OW", "Curve Data" }, { 0x6000, 0x0000, "UL", "Overlay Group Length" }, { 0x6000, 0x0001, "US", "Gray Palette Color Lookup Table Descriptor" }, { 0x6000, 0x0002, "US", "Gray Palette Color Lookup Table Data" }, { 0x6000, 0x0010, "US", "Overlay Rows" }, { 0x6000, 0x0011, "US", "Overlay Columns" }, { 0x6000, 0x0012, "US", "Overlay Planes" }, { 0x6000, 0x0015, "IS", "Number of Frames in Overlay" }, { 0x6000, 0x0022, "LO", "Overlay Description" }, { 0x6000, 0x0040, "CS", "Overlay Type" }, { 0x6000, 0x0045, "CS", "Overlay Subtype" }, { 0x6000, 0x0050, "SS", "Overlay Origin" }, { 0x6000, 0x0051, "US", "Image Frame Origin" }, { 0x6000, 0x0052, "US", "Plane Origin" }, { 0x6000, 0x0060, "LO", "Overlay Compression Code" }, { 0x6000, 0x0061, "SH", "Overlay Compression Originator" }, { 0x6000, 0x0062, "SH", "Overlay Compression Label" }, { 0x6000, 0x0063, "SH", "Overlay Compression Description" }, { 0x6000, 0x0066, "AT", "Overlay Compression Step Pointers" }, { 0x6000, 0x0068, "US", "Overlay Repeat Interval" }, { 0x6000, 0x0069, "US", "Overlay Bits Grouped" }, { 0x6000, 0x0100, "US", "Overlay Bits Allocated" }, { 0x6000, 0x0102, "US", "Overlay Bit Position" }, { 0x6000, 0x0110, "LO", "Overlay Format" }, { 0x6000, 0x0200, "xs", "Overlay Location" }, { 0x6000, 0x0800, "LO", "Overlay Code Label" }, { 0x6000, 0x0802, "US", "Overlay Number of Tables" }, { 0x6000, 0x0803, "AT", "Overlay Code Table Location" }, { 0x6000, 0x0804, "US", "Overlay Bits For Code Word" }, { 0x6000, 0x1001, "CS", "Overlay Activation Layer" }, { 0x6000, 0x1100, "US", "Overlay Descriptor - Gray" }, { 0x6000, 0x1101, "US", "Overlay Descriptor - Red" }, { 0x6000, 0x1102, "US", "Overlay Descriptor - Green" }, { 0x6000, 0x1103, "US", "Overlay Descriptor - Blue" }, { 0x6000, 0x1200, "US", "Overlays - Gray" }, { 0x6000, 0x1201, "US", "Overlays - Red" }, { 0x6000, 0x1202, "US", "Overlays - Green" }, { 0x6000, 0x1203, "US", "Overlays - Blue" }, { 0x6000, 0x1301, "IS", "ROI Area" }, { 0x6000, 0x1302, "DS", "ROI Mean" }, { 0x6000, 0x1303, "DS", "ROI Standard Deviation" }, { 0x6000, 0x1500, "LO", "Overlay Label" }, { 0x6000, 0x3000, "OW", "Overlay Data" }, { 0x6000, 0x4000, "LT", "Overlay Comments" }, { 0x6001, 0x0000, "UN", "?" }, { 0x6001, 0x0010, "LO", "?" }, { 0x6001, 0x1010, "xs", "?" }, { 0x6001, 0x1030, "xs", "?" }, { 0x6021, 0x0000, "xs", "?" }, { 0x6021, 0x0010, "xs", "?" }, { 0x7001, 0x0010, "LT", "Dummy" }, { 0x7003, 0x0010, "LT", "Info" }, { 0x7005, 0x0010, "LT", "Dummy" }, { 0x7000, 0x0004, "ST", "TextAnnotation" }, { 0x7000, 0x0005, "IS", "Box" }, { 0x7000, 0x0007, "IS", "ArrowEnd" }, { 0x7fe0, 0x0000, "UL", "Pixel Data Group Length" }, { 0x7fe0, 0x0010, "xs", "Pixel Data" }, { 0x7fe0, 0x0020, "OW", "Coefficients SDVN" }, { 0x7fe0, 0x0030, "OW", "Coefficients SDHN" }, { 0x7fe0, 0x0040, "OW", "Coefficients SDDN" }, { 0x7fe1, 0x0010, "xs", "Pixel Data" }, { 0x7f00, 0x0000, "UL", "Variable Pixel Data Group Length" }, { 0x7f00, 0x0010, "xs", "Variable Pixel Data" }, { 0x7f00, 0x0011, "US", "Variable Next Data Group" }, { 0x7f00, 0x0020, "OW", "Variable Coefficients SDVN" }, { 0x7f00, 0x0030, "OW", "Variable Coefficients SDHN" }, { 0x7f00, 0x0040, "OW", "Variable Coefficients SDDN" }, { 0x7fe1, 0x0000, "OB", "Binary Data" }, { 0x7fe3, 0x0000, "LT", "Image Graphics Format Code" }, { 0x7fe3, 0x0010, "OB", "Image Graphics" }, { 0x7fe3, 0x0020, "OB", "Image Graphics Dummy" }, { 0x7ff1, 0x0001, "US", "?" }, { 0x7ff1, 0x0002, "US", "?" }, { 0x7ff1, 0x0003, "xs", "?" }, { 0x7ff1, 0x0004, "IS", "?" }, { 0x7ff1, 0x0005, "US", "?" }, { 0x7ff1, 0x0007, "US", "?" }, { 0x7ff1, 0x0008, "US", "?" }, { 0x7ff1, 0x0009, "US", "?" }, { 0x7ff1, 0x000a, "LT", "?" }, { 0x7ff1, 0x000b, "US", "?" }, { 0x7ff1, 0x000c, "US", "?" }, { 0x7ff1, 0x000d, "US", "?" }, { 0x7ff1, 0x0010, "US", "?" }, { 0xfffc, 0xfffc, "OB", "Data Set Trailing Padding" }, { 0xfffe, 0xe000, "!!", "Item" }, { 0xfffe, 0xe00d, "!!", "Item Delimitation Item" }, { 0xfffe, 0xe0dd, "!!", "Sequence Delimitation Item" }, { 0xffff, 0xffff, "xs", (char *) NULL } }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D C M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDCM() returns MagickTrue if the image format type, identified by the % magick string, is DCM. % % The format of the ReadDCMImage method is: % % MagickBooleanType IsDCM(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 IsDCM(const unsigned char *magick,const size_t length) { if (length < 132) return(MagickFalse); if (LocaleNCompare((char *) (magick+128),"DICM",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D C M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDCMImage() reads a Digital Imaging and Communications in Medicine % (DICOM) 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 ReadDCMImage method is: % % Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ typedef struct _DCMStreamInfo { size_t remaining, segment_count; ssize_t segments[15]; size_t offset_count; ssize_t *offsets; ssize_t count; int byte; } DCMStreamInfo; static int ReadDCMByte(DCMStreamInfo *stream_info,Image *image) { if (image->compression != RLECompression) return(ReadBlobByte(image)); if (stream_info->count == 0) { int byte; ssize_t count; if (stream_info->remaining <= 2) stream_info->remaining=0; else stream_info->remaining-=2; count=(ssize_t) ReadBlobByte(image); byte=ReadBlobByte(image); if (count == 128) return(0); else if (count < 128) { /* Literal bytes. */ stream_info->count=count; stream_info->byte=(-1); return(byte); } else { /* Repeated bytes. */ stream_info->count=256-count; stream_info->byte=byte; return(byte); } } stream_info->count--; if (stream_info->byte >= 0) return(stream_info->byte); if (stream_info->remaining > 0) stream_info->remaining--; return(ReadBlobByte(image)); } static unsigned short ReadDCMShort(DCMStreamInfo *stream_info,Image *image) { int shift; unsigned short value; if (image->compression != RLECompression) return(ReadBlobLSBShort(image)); shift=image->depth < 16 ? 4 : 8; value=ReadDCMByte(stream_info,image) | (unsigned short) (ReadDCMByte(stream_info,image) << shift); return(value); } static signed short ReadDCMSignedShort(DCMStreamInfo *stream_info,Image *image) { union { unsigned short unsigned_value; signed short signed_value; } quantum; quantum.unsigned_value=ReadDCMShort(stream_info,image); return(quantum.signed_value); } static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, index, *redmap; MagickBooleanType explicit_file, explicit_retry, polarity, sequence, use_explicit; MagickOffsetType offset; Quantum *scale; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bits_allocated, bytes_per_pixel, colors, depth, height, length, mask, max_value, number_scenes, quantum, samples_per_pixel, signed_data, significant_bits, status, width, window_width; ssize_t count, rescale_intercept, rescale_slope, scene, window_center, y; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent); bits_allocated=8; bytes_per_pixel=1; polarity=MagickFalse; data=(unsigned char *) NULL; depth=8; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; max_value=255UL; mask=0xffff; number_scenes=1; rescale_intercept=0; rescale_slope=1; samples_per_pixel=1; scale=(Quantum *) NULL; sequence=MagickFalse; signed_data=(~0UL); significant_bits=0; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; window_center=0; window_width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"UL",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"FL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype); if (count < 1) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ bits_allocated=(size_t) datum; bytes_per_pixel=1; if (datum > 8) bytes_per_pixel=2; depth=bits_allocated; if (depth > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); max_value=(1UL << bits_allocated)-1; break; } case 0x0101: { /* Bits stored. */ significant_bits=(size_t) datum; bytes_per_pixel=1; if (significant_bits > 8) bytes_per_pixel=2; depth=significant_bits; if (depth > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); max_value=(1UL << significant_bits)-1; mask=(size_t) GetQuantumRange(significant_bits); break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) window_center=(ssize_t) StringToLong((char *) data); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) window_width=StringToUnsignedLong((char *) data); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) rescale_intercept=(ssize_t) StringToLong((char *) data); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) rescale_slope=(ssize_t) StringToLong((char *) data); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) colors; i++) if (bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data,exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (signed_data == 0xffff) signed_data=(size_t) (significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MagickPathExtent, "jpeg:%s",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, "j2k:%s",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(depth)+1); scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale)); if (scale == (Quantum *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); range=GetQuantumRange(depth); for (i=0; i <= (ssize_t) GetQuantumRange(depth); i++) scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1)) { size_t one; one=1; if (colors == 0) colors=one << depth; if (AcquireImageColormap(image,one << depth,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); if (stream_info->segment_count > 1) { bytes_per_pixel=1; depth=8; } for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; } if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; int byte; PixelPacket pixel; /* Convert DCM Medical image to pixel packets. */ byte=0; i=0; if ((window_center != 0) && (window_width == 0)) window_width=(size_t) window_center; option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) window_width=0; } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { if (signed_data) pixel_value=ReadDCMSignedShort(stream_info,image); else pixel_value=ReadDCMShort(stream_info,image); if (polarity != MagickFalse) pixel_value=(int)max_value-pixel_value; } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMSignedShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) index,q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { if (pixel.red <= GetQuantumRange(depth)) pixel.red=scale[pixel.red]; if (pixel.green <= GetQuantumRange(depth)) pixel.green=scale[pixel.green]; if (pixel.blue <= GetQuantumRange(depth)) pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) pixel.red,q); SetPixelGreen(image,(Quantum) pixel.green,q); SetPixelBlue(image,(Quantum) pixel.blue,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (stream_info->segment_count > 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { pixel_value=(int) (polarity != MagickFalse ? (max_value-ReadDCMShort(stream_info,image)) : ReadDCMShort(stream_info,image)); if (signed_data == 1) pixel_value=((signed short) pixel_value); } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) (((size_t) GetPixelIndex(image,q)) | (((size_t) index) << 8)),q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { pixel.red=scale[pixel.red]; pixel.green=scale[pixel.green]; pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) | (((size_t) pixel.red) << 8)),q); SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) | (((size_t) pixel.green) << 8)),q); SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) | (((size_t) pixel.blue) << 8)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (scale != (Quantum *) NULL) scale=(Quantum *) RelinquishMagickMemory(scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D C M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDCMImage() adds attributes for the DCM 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 RegisterDCMImage method is: % % size_t RegisterDCMImage(void) % */ ModuleExport size_t RegisterDCMImage(void) { MagickInfo *entry; static const char *DCMNote= { "DICOM is used by the medical community for images like X-rays. The\n" "specification, \"Digital Imaging and Communications in Medicine\n" "(DICOM)\", is available at http://medical.nema.org/. In particular,\n" "see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n" "and supplement 61 which adds JPEG-2000 encoding." }; entry=AcquireMagickInfo("DCM","DCM", "Digital Imaging and Communications in Medicine image"); entry->decoder=(DecodeImageHandler *) ReadDCMImage; entry->magick=(IsImageFormatHandler *) IsDCM; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderSeekableStreamFlag; entry->note=ConstantString(DCMNote); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D C M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDCMImage() removes format registrations made by the % DCM module from the list of supported formats. % % The format of the UnregisterDCMImage method is: % % UnregisterDCMImage(void) % */ ModuleExport void UnregisterDCMImage(void) { (void) UnregisterMagickInfo("DCM"); }
./CrossVul/dataset_final_sorted/CWE-476/c/good_5129_1
crossvul-cpp_data_bad_101_1
/* * fs/cifs/smb2pdu.c * * Copyright (C) International Business Machines Corp., 2009, 2013 * Etersoft, 2012 * Author(s): Steve French (sfrench@us.ibm.com) * Pavel Shilovsky (pshilovsky@samba.org) 2012 * * Contains the routines for constructing the SMB2 PDUs themselves * * 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 */ /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */ /* Note that there are handle based routines which must be */ /* treated slightly differently for reconnection purposes since we never */ /* want to reuse a stale file handle and only the caller knows the file info */ #include <linux/fs.h> #include <linux/kernel.h> #include <linux/vfs.h> #include <linux/task_io_accounting_ops.h> #include <linux/uaccess.h> #include <linux/pagemap.h> #include <linux/xattr.h> #include "smb2pdu.h" #include "cifsglob.h" #include "cifsacl.h" #include "cifsproto.h" #include "smb2proto.h" #include "cifs_unicode.h" #include "cifs_debug.h" #include "ntlmssp.h" #include "smb2status.h" #include "smb2glob.h" #include "cifspdu.h" #include "cifs_spnego.h" /* * The following table defines the expected "StructureSize" of SMB2 requests * in order by SMB2 command. This is similar to "wct" in SMB/CIFS requests. * * Note that commands are defined in smb2pdu.h in le16 but the array below is * indexed by command in host byte order. */ static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = { /* SMB2_NEGOTIATE */ 36, /* SMB2_SESSION_SETUP */ 25, /* SMB2_LOGOFF */ 4, /* SMB2_TREE_CONNECT */ 9, /* SMB2_TREE_DISCONNECT */ 4, /* SMB2_CREATE */ 57, /* SMB2_CLOSE */ 24, /* SMB2_FLUSH */ 24, /* SMB2_READ */ 49, /* SMB2_WRITE */ 49, /* SMB2_LOCK */ 48, /* SMB2_IOCTL */ 57, /* SMB2_CANCEL */ 4, /* SMB2_ECHO */ 4, /* SMB2_QUERY_DIRECTORY */ 33, /* SMB2_CHANGE_NOTIFY */ 32, /* SMB2_QUERY_INFO */ 41, /* SMB2_SET_INFO */ 33, /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */ }; static int encryption_required(const struct cifs_tcon *tcon) { if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) || (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA)) return 1; return 0; } static void smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd, const struct cifs_tcon *tcon) { shdr->ProtocolId = SMB2_PROTO_NUMBER; shdr->StructureSize = cpu_to_le16(64); shdr->Command = smb2_cmd; if (tcon && tcon->ses && tcon->ses->server) { struct TCP_Server_Info *server = tcon->ses->server; spin_lock(&server->req_lock); /* Request up to 2 credits but don't go over the limit. */ if (server->credits >= server->max_credits) shdr->CreditRequest = cpu_to_le16(0); else shdr->CreditRequest = cpu_to_le16( min_t(int, server->max_credits - server->credits, 2)); spin_unlock(&server->req_lock); } else { shdr->CreditRequest = cpu_to_le16(2); } shdr->ProcessId = cpu_to_le32((__u16)current->tgid); if (!tcon) goto out; /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */ /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */ if ((tcon->ses) && (tcon->ses->server) && (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU)) shdr->CreditCharge = cpu_to_le16(1); /* else CreditCharge MBZ */ shdr->TreeId = tcon->tid; /* Uid is not converted */ if (tcon->ses) shdr->SessionId = tcon->ses->Suid; /* * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have * to pass the path on the Open SMB prefixed by \\server\share. * Not sure when we would need to do the augmented path (if ever) and * setting this flag breaks the SMB2 open operation since it is * illegal to send an empty path name (without \\server\share prefix) * when the DFS flag is set in the SMB open header. We could * consider setting the flag on all operations other than open * but it is safer to net set it for now. */ /* if (tcon->share_flags & SHI1005_FLAGS_DFS) shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */ if (tcon->ses && tcon->ses->server && tcon->ses->server->sign && !encryption_required(tcon)) shdr->Flags |= SMB2_FLAGS_SIGNED; out: return; } static int smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon) { int rc = 0; struct nls_table *nls_codepage; struct cifs_ses *ses; struct TCP_Server_Info *server; /* * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so * check for tcp and smb session status done differently * for those three - in the calling routine. */ if (tcon == NULL) return rc; if (smb2_command == SMB2_TREE_CONNECT) return rc; if (tcon->tidStatus == CifsExiting) { /* * only tree disconnect, open, and write, * (and ulogoff which does not have tcon) * are allowed as we start force umount. */ if ((smb2_command != SMB2_WRITE) && (smb2_command != SMB2_CREATE) && (smb2_command != SMB2_TREE_DISCONNECT)) { cifs_dbg(FYI, "can not send cmd %d while umounting\n", smb2_command); return -ENODEV; } } if ((!tcon->ses) || (tcon->ses->status == CifsExiting) || (!tcon->ses->server)) return -EIO; ses = tcon->ses; server = ses->server; /* * Give demultiplex thread up to 10 seconds to reconnect, should be * greater than cifs socket timeout which is 7 seconds */ while (server->tcpStatus == CifsNeedReconnect) { /* * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE * here since they are implicitly done when session drops. */ switch (smb2_command) { /* * BB Should we keep oplock break and add flush to exceptions? */ case SMB2_TREE_DISCONNECT: case SMB2_CANCEL: case SMB2_CLOSE: case SMB2_OPLOCK_BREAK: return -EAGAIN; } wait_event_interruptible_timeout(server->response_q, (server->tcpStatus != CifsNeedReconnect), 10 * HZ); /* are we still trying to reconnect? */ if (server->tcpStatus != CifsNeedReconnect) break; /* * on "soft" mounts we wait once. Hard mounts keep * retrying until process is killed or server comes * back on-line */ if (!tcon->retry) { cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n"); return -EHOSTDOWN; } } if (!tcon->ses->need_reconnect && !tcon->need_reconnect) return rc; nls_codepage = load_nls_default(); /* * need to prevent multiple threads trying to simultaneously reconnect * the same SMB session */ mutex_lock(&tcon->ses->session_mutex); rc = cifs_negotiate_protocol(0, tcon->ses); if (!rc && tcon->ses->need_reconnect) rc = cifs_setup_session(0, tcon->ses, nls_codepage); if (rc || !tcon->need_reconnect) { mutex_unlock(&tcon->ses->session_mutex); goto out; } cifs_mark_open_files_invalid(tcon); if (tcon->use_persistent) tcon->need_reopen_files = true; rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage); mutex_unlock(&tcon->ses->session_mutex); cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc); if (rc) goto out; if (smb2_command != SMB2_INTERNAL_CMD) queue_delayed_work(cifsiod_wq, &server->reconnect, 0); atomic_inc(&tconInfoReconnectCount); out: /* * Check if handle based operation so we know whether we can continue * or not without returning to caller to reset file handle. */ /* * BB Is flush done by server on drop of tcp session? Should we special * case it and skip above? */ switch (smb2_command) { case SMB2_FLUSH: case SMB2_READ: case SMB2_WRITE: case SMB2_LOCK: case SMB2_IOCTL: case SMB2_QUERY_DIRECTORY: case SMB2_CHANGE_NOTIFY: case SMB2_QUERY_INFO: case SMB2_SET_INFO: rc = -EAGAIN; } unload_nls(nls_codepage); return rc; } static void fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf, unsigned int *total_len) { struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf; /* lookup word count ie StructureSize from table */ __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)]; /* * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of * largest operations (Create) */ memset(buf, 0, 256); smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon); spdu->StructureSize2 = cpu_to_le16(parmsize); *total_len = parmsize + sizeof(struct smb2_sync_hdr); } /* init request without RFC1001 length at the beginning */ static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon, void **request_buf, unsigned int *total_len) { int rc; struct smb2_sync_hdr *shdr; rc = smb2_reconnect(smb2_command, tcon); if (rc) return rc; /* BB eventually switch this to SMB2 specific small buf size */ *request_buf = cifs_small_buf_get(); if (*request_buf == NULL) { /* BB should we add a retry in here if not a writepage? */ return -ENOMEM; } shdr = (struct smb2_sync_hdr *)(*request_buf); fill_small_buf(smb2_command, tcon, shdr, total_len); if (tcon != NULL) { #ifdef CONFIG_CIFS_STATS2 uint16_t com_code = le16_to_cpu(smb2_command); cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]); #endif cifs_stats_inc(&tcon->num_smbs_sent); } return rc; } /* * Allocate and return pointer to an SMB request hdr, and set basic * SMB information in the SMB header. If the return code is zero, this * function must have filled in request_buf pointer. The returned buffer * has RFC1001 length at the beginning. */ static int small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon, void **request_buf) { int rc; unsigned int total_len; struct smb2_pdu *pdu; rc = smb2_reconnect(smb2_command, tcon); if (rc) return rc; /* BB eventually switch this to SMB2 specific small buf size */ *request_buf = cifs_small_buf_get(); if (*request_buf == NULL) { /* BB should we add a retry in here if not a writepage? */ return -ENOMEM; } pdu = (struct smb2_pdu *)(*request_buf); fill_small_buf(smb2_command, tcon, get_sync_hdr(pdu), &total_len); /* Note this is only network field converted to big endian */ pdu->hdr.smb2_buf_length = cpu_to_be32(total_len); if (tcon != NULL) { #ifdef CONFIG_CIFS_STATS2 uint16_t com_code = le16_to_cpu(smb2_command); cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]); #endif cifs_stats_inc(&tcon->num_smbs_sent); } return rc; } #ifdef CONFIG_CIFS_SMB311 /* offset is sizeof smb2_negotiate_req - 4 but rounded up to 8 bytes */ #define OFFSET_OF_NEG_CONTEXT 0x68 /* sizeof(struct smb2_negotiate_req) - 4 */ #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES cpu_to_le16(1) #define SMB2_ENCRYPTION_CAPABILITIES cpu_to_le16(2) static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES; pneg_ctxt->DataLength = cpu_to_le16(38); pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1); pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE); get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE); pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512; } static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES; pneg_ctxt->DataLength = cpu_to_le16(6); pneg_ctxt->CipherCount = cpu_to_le16(2); pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM; pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM; } static void assemble_neg_contexts(struct smb2_negotiate_req *req) { /* +4 is to account for the RFC1001 len field */ char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT + 4; build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt); /* Add 2 to size to round to 8 byte boundary */ pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context); build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt); req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT); req->NegotiateContextCount = cpu_to_le16(2); inc_rfc1001_len(req, 4 + sizeof(struct smb2_preauth_neg_context) + 2 + sizeof(struct smb2_encryption_neg_context)); /* calculate hash */ } #else static void assemble_neg_contexts(struct smb2_negotiate_req *req) { return; } #endif /* SMB311 */ /* * * SMB2 Worker functions follow: * * The general structure of the worker functions is: * 1) Call smb2_init (assembles SMB2 header) * 2) Initialize SMB2 command specific fields in fixed length area of SMB * 3) Call smb_sendrcv2 (sends request on socket and waits for response) * 4) Decode SMB2 command specific fields in the fixed length area * 5) Decode variable length data area (if any for this SMB2 command type) * 6) Call free smb buffer * 7) return * */ int SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses) { struct smb2_negotiate_req *req; struct smb2_negotiate_rsp *rsp; struct kvec iov[1]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct TCP_Server_Info *server = ses->server; int blob_offset, blob_length; char *security_blob; int flags = CIFS_NEG_OP; cifs_dbg(FYI, "Negotiate protocol\n"); if (!server) { WARN(1, "%s: server is NULL!\n", __func__); return -EIO; } rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req); if (rc) return rc; req->hdr.sync_hdr.SessionId = 0; req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id); req->DialectCount = cpu_to_le16(1); /* One vers= at a time for now */ inc_rfc1001_len(req, 2); /* only one of SMB2 signing flags may be set in SMB2 request */ if (ses->sign) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else req->SecurityMode = 0; req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities); /* ClientGUID must be zero for SMB2.02 dialect */ if (ses->server->vals->protocol_id == SMB20_PROT_ID) memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE); else { memcpy(req->ClientGUID, server->client_guid, SMB2_CLIENT_GUID_SIZE); if (ses->server->vals->protocol_id == SMB311_PROT_ID) assemble_neg_contexts(req); } iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base; /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ if (rc != 0) goto neg_exit; cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode); /* BB we may eventually want to match the negotiated vs. requested dialect, even though we are only requesting one at a time */ if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) cifs_dbg(FYI, "negotiated smb2.0 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) cifs_dbg(FYI, "negotiated smb2.1 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.0 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.02 dialect\n"); #ifdef CONFIG_CIFS_SMB311 else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n"); #endif /* SMB311 */ else { cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n", le16_to_cpu(rsp->DialectRevision)); rc = -EIO; goto neg_exit; } server->dialect = le16_to_cpu(rsp->DialectRevision); /* SMB2 only has an extended negflavor */ server->negflavor = CIFS_NEGFLAVOR_EXTENDED; /* set it to the maximum buffer size value we can send with 1 credit */ server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize), SMB2_MAX_BUFFER_SIZE); server->max_read = le32_to_cpu(rsp->MaxReadSize); server->max_write = le32_to_cpu(rsp->MaxWriteSize); /* BB Do we need to validate the SecurityMode? */ server->sec_mode = le16_to_cpu(rsp->SecurityMode); server->capabilities = le32_to_cpu(rsp->Capabilities); /* Internal types */ server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES; security_blob = smb2_get_data_area_len(&blob_offset, &blob_length, &rsp->hdr); /* * See MS-SMB2 section 2.2.4: if no blob, client picks default which * for us will be * ses->sectype = RawNTLMSSP; * but for time being this is our only auth choice so doesn't matter. * We just found a server which sets blob length to zero expecting raw. */ if (blob_length == 0) cifs_dbg(FYI, "missing security blob on negprot\n"); rc = cifs_enable_signing(server, ses->sign); if (rc) goto neg_exit; if (blob_length) { rc = decode_negTokenInit(security_blob, blob_length, server); if (rc == 1) rc = 0; else if (rc == 0) rc = -EIO; } neg_exit: free_rsp_buf(resp_buftype, rsp); return rc; } int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon) { int rc = 0; struct validate_negotiate_info_req vneg_inbuf; struct validate_negotiate_info_rsp *pneg_rsp; u32 rsplen; cifs_dbg(FYI, "validate negotiate\n"); /* * validation ioctl must be signed, so no point sending this if we * can not sign it. We could eventually change this to selectively * sign just this, the first and only signed request on a connection. * This is good enough for now since a user who wants better security * would also enable signing on the mount. Having validation of * negotiate info for signed connections helps reduce attack vectors */ if (tcon->ses->server->sign == false) return 0; /* validation requires signing */ vneg_inbuf.Capabilities = cpu_to_le32(tcon->ses->server->vals->req_capabilities); memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid, SMB2_CLIENT_GUID_SIZE); if (tcon->ses->sign) vneg_inbuf.SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) vneg_inbuf.SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else vneg_inbuf.SecurityMode = 0; vneg_inbuf.DialectCount = cpu_to_le16(1); vneg_inbuf.Dialects[0] = cpu_to_le16(tcon->ses->server->vals->protocol_id); rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID, FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */, (char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req), (char **)&pneg_rsp, &rsplen); if (rc != 0) { cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc); return -EIO; } if (rsplen != sizeof(struct validate_negotiate_info_rsp)) { cifs_dbg(VFS, "invalid size of protocol negotiate response\n"); return -EIO; } /* check validate negotiate info response matches what we got earlier */ if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->vals->protocol_id)) goto vneg_out; if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode)) goto vneg_out; /* do not validate server guid because not saved at negprot time yet */ if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND | SMB2_LARGE_FILES) != tcon->ses->server->capabilities) goto vneg_out; /* validate negotiate successful */ cifs_dbg(FYI, "validate negotiate info successful\n"); return 0; vneg_out: cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n"); return -EIO; } struct SMB2_sess_data { unsigned int xid; struct cifs_ses *ses; struct nls_table *nls_cp; void (*func)(struct SMB2_sess_data *); int result; u64 previous_session; /* we will send the SMB in three pieces: * a fixed length beginning part, an optional * SPNEGO blob (which can be zero length), and a * last part which will include the strings * and rest of bcc area. This allows us to avoid * a large buffer 17K allocation */ int buf0_type; struct kvec iov[2]; }; static int SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct TCP_Server_Info *server = ses->server; rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req); if (rc) return rc; /* First session, not a reauthenticate */ req->hdr.sync_hdr.SessionId = 0; /* if reconnect, we need to send previous sess id, otherwise it is 0 */ req->PreviousSessionId = sess_data->previous_session; req->Flags = 0; /* MBZ */ /* to enable echos and oplocks */ req->hdr.sync_hdr.CreditRequest = cpu_to_le16(3); /* only one of SMB2 signing flags may be set in SMB2 request */ if (server->sign) req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED; else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */ req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED; else req->SecurityMode = 0; req->Capabilities = 0; req->Channel = 0; /* MBZ */ sess_data->iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ sess_data->iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* * This variable will be used to clear the buffer * allocated above in case of any error in the calling function. */ sess_data->buf0_type = CIFS_SMALL_BUFFER; return 0; } static void SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data) { free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base); sess_data->buf0_type = CIFS_NO_BUFFER; } static int SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data) { int rc; struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base; struct kvec rsp_iov = { NULL, 0 }; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->SecurityBufferOffset = cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */ - 4 /* rfc1001 len */); req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len); inc_rfc1001_len(req, sess_data->iov[1].iov_len - 1 /* pad */); /* BB add code to build os and lm fields */ rc = SendReceive2(sess_data->xid, sess_data->ses, sess_data->iov, 2, &sess_data->buf0_type, CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov); cifs_small_buf_release(sess_data->iov[0].iov_base); memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec)); return rc; } static int SMB2_sess_establish_session(struct SMB2_sess_data *sess_data) { int rc = 0; struct cifs_ses *ses = sess_data->ses; mutex_lock(&ses->server->srv_mutex); if (ses->server->sign && ses->server->ops->generate_signingkey) { rc = ses->server->ops->generate_signingkey(ses); kfree(ses->auth_key.response); ses->auth_key.response = NULL; if (rc) { cifs_dbg(FYI, "SMB3 session key generation failed\n"); mutex_unlock(&ses->server->srv_mutex); goto keygen_exit; } } if (!ses->server->session_estab) { ses->server->sequence_number = 0x2; ses->server->session_estab = true; } mutex_unlock(&ses->server->srv_mutex); cifs_dbg(FYI, "SMB2/3 session established successfully\n"); spin_lock(&GlobalMid_Lock); ses->status = CifsGood; ses->need_reconnect = false; spin_unlock(&GlobalMid_Lock); keygen_exit: if (!ses->server->sign) { kfree(ses->auth_key.response); ses->auth_key.response = NULL; } return rc; } #ifdef CONFIG_CIFS_UPCALL static void SMB2_auth_kerberos(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct cifs_spnego_msg *msg; struct key *spnego_key = NULL; struct smb2_sess_setup_rsp *rsp = NULL; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; spnego_key = cifs_get_spnego_key(ses); if (IS_ERR(spnego_key)) { rc = PTR_ERR(spnego_key); spnego_key = NULL; goto out; } msg = spnego_key->payload.data[0]; /* * check version field to make sure that cifs.upcall is * sending us a response in an expected form */ if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) { cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d", CIFS_SPNEGO_UPCALL_VERSION, msg->version); rc = -EKEYREJECTED; goto out_put_spnego_key; } ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len, GFP_KERNEL); if (!ses->auth_key.response) { cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory", msg->sesskey_len); rc = -ENOMEM; goto out_put_spnego_key; } ses->auth_key.len = msg->sesskey_len; sess_data->iov[1].iov_base = msg->data + msg->sesskey_len; sess_data->iov[1].iov_len = msg->secblob_len; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out_put_spnego_key; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) cifs_dbg(VFS, "SMB3 encryption not supported yet\n"); rc = SMB2_sess_establish_session(sess_data); out_put_spnego_key: key_invalidate(spnego_key); key_put(spnego_key); out: sess_data->result = rc; sess_data->func = NULL; SMB2_sess_free_buffer(sess_data); } #else static void SMB2_auth_kerberos(struct SMB2_sess_data *sess_data) { cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n"); sess_data->result = -EOPNOTSUPP; sess_data->func = NULL; } #endif static void SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data); static void SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_rsp *rsp = NULL; char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; /* * If memory allocation is successful, caller of this function * frees it. */ ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL); if (!ses->ntlmssp) { rc = -ENOMEM; goto out_err; } ses->ntlmssp->sesskey_per_smbsess = true; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out_err; ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE), GFP_KERNEL); if (ntlmssp_blob == NULL) { rc = -ENOMEM; goto out; } build_ntlmssp_negotiate_blob(ntlmssp_blob, ses); if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } else { blob_length = sizeof(struct _NEGOTIATE_MESSAGE); /* with raw NTLMSSP we don't encapsulate in SPNEGO */ } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; /* If true, rc here is expected and not an error */ if (sess_data->buf0_type != CIFS_NO_BUFFER && rsp->hdr.sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) rc = 0; if (rc) goto out; if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 != le16_to_cpu(rsp->SecurityBufferOffset)) { cifs_dbg(VFS, "Invalid security buffer offset %d\n", le16_to_cpu(rsp->SecurityBufferOffset)); rc = -EIO; goto out; } rc = decode_ntlmssp_challenge(rsp->Buffer, le16_to_cpu(rsp->SecurityBufferLength), ses); if (rc) goto out; cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n"); ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) cifs_dbg(VFS, "SMB3 encryption not supported yet\n"); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); if (!rc) { sess_data->result = 0; sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate; return; } out_err: kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } static void SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct smb2_sess_setup_rsp *rsp = NULL; unsigned char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base; req->hdr.sync_hdr.SessionId = ses->Suid; rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses, sess_data->nls_cp); if (rc) { cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc); goto out; } if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) cifs_dbg(VFS, "SMB3 encryption not supported yet\n"); rc = SMB2_sess_establish_session(sess_data); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } static int SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data) { if (ses->sectype != Kerberos && ses->sectype != RawNTLMSSP) ses->sectype = RawNTLMSSP; switch (ses->sectype) { case Kerberos: sess_data->func = SMB2_auth_kerberos; break; case RawNTLMSSP: sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate; break; default: cifs_dbg(VFS, "secType %d not supported!\n", ses->sectype); return -EOPNOTSUPP; } return 0; } int SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses, const struct nls_table *nls_cp) { int rc = 0; struct TCP_Server_Info *server = ses->server; struct SMB2_sess_data *sess_data; cifs_dbg(FYI, "Session Setup\n"); if (!server) { WARN(1, "%s: server is NULL!\n", __func__); return -EIO; } sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL); if (!sess_data) return -ENOMEM; rc = SMB2_select_sec(ses, sess_data); if (rc) goto out; sess_data->xid = xid; sess_data->ses = ses; sess_data->buf0_type = CIFS_NO_BUFFER; sess_data->nls_cp = (struct nls_table *) nls_cp; while (sess_data->func) sess_data->func(sess_data); rc = sess_data->result; out: kfree(sess_data); return rc; } int SMB2_logoff(const unsigned int xid, struct cifs_ses *ses) { struct smb2_logoff_req *req; /* response is also trivial struct */ int rc = 0; struct TCP_Server_Info *server; int flags = 0; cifs_dbg(FYI, "disconnect session %p\n", ses); if (ses && (ses->server)) server = ses->server; else return -EIO; /* no need to send SMB logoff if uid already closed due to reconnect */ if (ses->need_reconnect) goto smb2_session_already_dead; rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req); if (rc) return rc; /* since no tcon, smb2_init can not do this, so do here */ req->hdr.sync_hdr.SessionId = ses->Suid; if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) flags |= CIFS_TRANSFORM_REQ; else if (server->sign) req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED; rc = SendReceiveNoRsp(xid, ses, (char *) req, flags); cifs_small_buf_release(req); /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ smb2_session_already_dead: return rc; } static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code) { cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]); } #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */) /* These are similar values to what Windows uses */ static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon) { tcon->max_chunks = 256; tcon->max_bytes_chunk = 1048576; tcon->max_bytes_copy = 16777216; } int SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree, struct cifs_tcon *tcon, const struct nls_table *cp) { struct smb2_tree_connect_req *req; struct smb2_tree_connect_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov; int rc = 0; int resp_buftype; int unc_path_len; struct TCP_Server_Info *server; __le16 *unc_path = NULL; int flags = 0; cifs_dbg(FYI, "TCON\n"); if ((ses->server) && tree) server = ses->server; else return -EIO; if (tcon && tcon->bad_network_name) return -ENOENT; if ((tcon && tcon->seal) && ((ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) == 0)) { cifs_dbg(VFS, "encryption requested but no server support"); return -EOPNOTSUPP; } unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL); if (unc_path == NULL) return -ENOMEM; unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1; unc_path_len *= 2; if (unc_path_len < 2) { kfree(unc_path); return -EINVAL; } rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req); if (rc) { kfree(unc_path); return rc; } if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) flags |= CIFS_TRANSFORM_REQ; if (tcon == NULL) { /* since no tcon, smb2_init can not do this, so do here */ req->hdr.sync_hdr.SessionId = ses->Suid; /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED) req->hdr.Flags |= SMB2_FLAGS_SIGNED; */ } iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req) - 1 /* pad */ - 4 /* do not count rfc1001 len field */); req->PathLength = cpu_to_le16(unc_path_len - 2); iov[1].iov_base = unc_path; iov[1].iov_len = unc_path_len; inc_rfc1001_len(req, unc_path_len - 1 /* pad */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base; if (rc != 0) { if (tcon) { cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE); tcon->need_reconnect = true; } goto tcon_error_exit; } if (tcon == NULL) { ses->ipc_tid = rsp->hdr.sync_hdr.TreeId; goto tcon_exit; } if (rsp->ShareType & SMB2_SHARE_TYPE_DISK) cifs_dbg(FYI, "connection to disk share\n"); else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) { tcon->ipc = true; cifs_dbg(FYI, "connection to pipe share\n"); } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) { tcon->print = true; cifs_dbg(FYI, "connection to printer\n"); } else { cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType); rc = -EOPNOTSUPP; goto tcon_error_exit; } tcon->share_flags = le32_to_cpu(rsp->ShareFlags); tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */ tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess); tcon->tidStatus = CifsGood; tcon->need_reconnect = false; tcon->tid = rsp->hdr.sync_hdr.TreeId; strlcpy(tcon->treeName, tree, sizeof(tcon->treeName)); if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) && ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0)) cifs_dbg(VFS, "DFS capability contradicts DFS flag\n"); init_copy_chunk_defaults(tcon); if (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA) cifs_dbg(VFS, "Encrypted shares not supported"); if (tcon->ses->server->ops->validate_negotiate) rc = tcon->ses->server->ops->validate_negotiate(xid, tcon); tcon_exit: free_rsp_buf(resp_buftype, rsp); kfree(unc_path); return rc; tcon_error_exit: if (rsp->hdr.sync_hdr.Status == STATUS_BAD_NETWORK_NAME) { cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree); if (tcon) tcon->bad_network_name = true; } goto tcon_exit; } int SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon) { struct smb2_tree_disconnect_req *req; /* response is trivial */ int rc = 0; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; int flags = 0; cifs_dbg(FYI, "Tree Disconnect\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; if ((tcon->need_reconnect) || (tcon->ses->need_reconnect)) return 0; rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; rc = SendReceiveNoRsp(xid, ses, (char *)req, flags); cifs_small_buf_release(req); if (rc) cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE); return rc; } static struct create_durable * create_durable_buf(void) { struct create_durable *buf; buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable, Data)); buf->ccontext.DataLength = cpu_to_le32(16); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable, Name)); buf->ccontext.NameLength = cpu_to_le16(4); /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = 'n'; buf->Name[3] = 'Q'; return buf; } static struct create_durable * create_reconnect_durable_buf(struct cifs_fid *fid) { struct create_durable *buf; buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable, Data)); buf->ccontext.DataLength = cpu_to_le32(16); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->Data.Fid.PersistentFileId = fid->persistent_fid; buf->Data.Fid.VolatileFileId = fid->volatile_fid; /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = 'n'; buf->Name[3] = 'C'; return buf; } static __u8 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp, unsigned int *epoch) { char *data_offset; struct create_context *cc; unsigned int next; unsigned int remaining; char *name; data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset); remaining = le32_to_cpu(rsp->CreateContextsLength); cc = (struct create_context *)data_offset; while (remaining >= sizeof(struct create_context)) { name = le16_to_cpu(cc->NameOffset) + (char *)cc; if (le16_to_cpu(cc->NameLength) == 4 && strncmp(name, "RqLs", 4) == 0) return server->ops->parse_lease_buf(cc, epoch); next = le32_to_cpu(cc->Next); if (!next) break; remaining -= next; cc = (struct create_context *)((char *)cc + next); } return 0; } static int add_lease_context(struct TCP_Server_Info *server, struct kvec *iov, unsigned int *num_iovec, __u8 *oplock) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = server->vals->create_lease_size; req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE; if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32( sizeof(struct smb2_create_req) - 4 + iov[num - 1].iov_len); le32_add_cpu(&req->CreateContextsLength, server->vals->create_lease_size); inc_rfc1001_len(&req->hdr, server->vals->create_lease_size); *num_iovec = num + 1; return 0; } static struct create_durable_v2 * create_durable_v2_buf(struct cifs_fid *pfid) { struct create_durable_v2 *buf; buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable_v2, dcontext)); buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2)); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable_v2, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->dcontext.Timeout = 0; /* Should this be configurable by workload */ buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT); generate_random_uuid(buf->dcontext.CreateGuid); memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16); /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = '2'; buf->Name[3] = 'Q'; return buf; } static struct create_durable_handle_reconnect_v2 * create_reconnect_durable_v2_buf(struct cifs_fid *fid) { struct create_durable_handle_reconnect_v2 *buf; buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2, dcontext)); buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_reconnect_context_v2)); buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->dcontext.Fid.PersistentFileId = fid->persistent_fid; buf->dcontext.Fid.VolatileFileId = fid->volatile_fid; buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT); memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16); /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = '2'; buf->Name[3] = 'C'; return buf; } static int add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = create_durable_v2_buf(oparms->fid); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable_v2); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) - 4 + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2)); inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2)); *num_iovec = num + 1; return 0; } static int add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; /* indicate that we don't need to relock the file */ oparms->reconnect = false; iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) - 4 + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_handle_reconnect_v2)); inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_handle_reconnect_v2)); *num_iovec = num + 1; return 0; } static int add_durable_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms, bool use_persistent) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; if (use_persistent) { if (oparms->reconnect) return add_durable_reconnect_v2_context(iov, num_iovec, oparms); else return add_durable_v2_context(iov, num_iovec, oparms); } if (oparms->reconnect) { iov[num].iov_base = create_reconnect_durable_buf(oparms->fid); /* indicate that we don't need to relock the file */ oparms->reconnect = false; } else iov[num].iov_base = create_durable_buf(); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) - 4 + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable)); inc_rfc1001_len(&req->hdr, sizeof(struct create_durable)); *num_iovec = num + 1; return 0; } int SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path, __u8 *oplock, struct smb2_file_all_info *buf, struct smb2_err_rsp **err_buf) { struct smb2_create_req *req; struct smb2_create_rsp *rsp; struct TCP_Server_Info *server; struct cifs_tcon *tcon = oparms->tcon; struct cifs_ses *ses = tcon->ses; struct kvec iov[4]; struct kvec rsp_iov; int resp_buftype; int uni_path_len; __le16 *copy_path = NULL; int copy_size; int rc = 0; unsigned int n_iov = 2; __u32 file_attributes = 0; char *dhc_buf = NULL, *lc_buf = NULL; int flags = 0; cifs_dbg(FYI, "create/open\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; if (oparms->create_options & CREATE_OPTION_READONLY) file_attributes |= ATTR_READONLY; if (oparms->create_options & CREATE_OPTION_SPECIAL) file_attributes |= ATTR_SYSTEM; req->ImpersonationLevel = IL_IMPERSONATION; req->DesiredAccess = cpu_to_le32(oparms->desired_access); /* File attributes ignored on open (used in create though) */ req->FileAttributes = cpu_to_le32(file_attributes); req->ShareAccess = FILE_SHARE_ALL_LE; req->CreateDisposition = cpu_to_le32(oparms->disposition); req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK); uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2; /* do not count rfc1001 len field */ req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4); iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; /* MUST set path len (NameLength) to 0 opening root of share */ req->NameLength = cpu_to_le16(uni_path_len - 2); /* -1 since last byte is buf[0] which is sent below (path) */ iov[0].iov_len--; if (uni_path_len % 8 != 0) { copy_size = uni_path_len / 8 * 8; if (copy_size < uni_path_len) copy_size += 8; copy_path = kzalloc(copy_size, GFP_KERNEL); if (!copy_path) return -ENOMEM; memcpy((char *)copy_path, (const char *)path, uni_path_len); uni_path_len = copy_size; path = copy_path; } iov[1].iov_len = uni_path_len; iov[1].iov_base = path; /* -1 since last byte is buf[0] which was counted in smb2_buf_len */ inc_rfc1001_len(req, uni_path_len - 1); if (!server->oplocks) *oplock = SMB2_OPLOCK_LEVEL_NONE; if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) || *oplock == SMB2_OPLOCK_LEVEL_NONE) req->RequestedOplockLevel = *oplock; else { rc = add_lease_context(server, iov, &n_iov, oplock); if (rc) { cifs_small_buf_release(req); kfree(copy_path); return rc; } lc_buf = iov[n_iov-1].iov_base; } if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) { /* need to set Next field of lease context if we request it */ if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) { struct create_context *ccontext = (struct create_context *)iov[n_iov-1].iov_base; ccontext->Next = cpu_to_le32(server->vals->create_lease_size); } rc = add_durable_context(iov, &n_iov, oparms, tcon->use_persistent); if (rc) { cifs_small_buf_release(req); kfree(copy_path); kfree(lc_buf); return rc; } dhc_buf = iov[n_iov-1].iov_base; } rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_create_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CREATE_HE); if (err_buf) *err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4, GFP_KERNEL); goto creat_exit; } oparms->fid->persistent_fid = rsp->PersistentFileId; oparms->fid->volatile_fid = rsp->VolatileFileId; if (buf) { memcpy(buf, &rsp->CreationTime, 32); buf->AllocationSize = rsp->AllocationSize; buf->EndOfFile = rsp->EndofFile; buf->Attributes = rsp->FileAttributes; buf->NumberOfLinks = cpu_to_le32(1); buf->DeletePending = 0; } if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE) *oplock = parse_lease_state(server, rsp, &oparms->fid->epoch); else *oplock = rsp->OplockLevel; creat_exit: kfree(copy_path); kfree(lc_buf); kfree(dhc_buf); free_rsp_buf(resp_buftype, rsp); return rc; } /* * SMB2 IOCTL is used for both IOCTLs and FSCTLs */ int SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data, u32 indatalen, char **out_data, u32 *plen /* returned data len */) { struct smb2_ioctl_req *req; struct smb2_ioctl_rsp *rsp; struct smb2_sync_hdr *shdr; struct TCP_Server_Info *server; struct cifs_ses *ses; struct kvec iov[2]; struct kvec rsp_iov; int resp_buftype; int n_iov; int rc = 0; int flags = 0; cifs_dbg(FYI, "SMB2 IOCTL\n"); if (out_data != NULL) *out_data = NULL; /* zero out returned data len, in case of error */ if (plen) *plen = 0; if (tcon) ses = tcon->ses; else return -EIO; if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->CtlCode = cpu_to_le32(opcode); req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; if (indatalen) { req->InputCount = cpu_to_le32(indatalen); /* do not set InputOffset if no input data */ req->InputOffset = cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4); iov[1].iov_base = in_data; iov[1].iov_len = indatalen; n_iov = 2; } else n_iov = 1; req->OutputOffset = 0; req->OutputCount = 0; /* MBZ */ /* * Could increase MaxOutputResponse, but that would require more * than one credit. Windows typically sets this smaller, but for some * ioctls it may be useful to allow server to send more. No point * limiting what the server can send as long as fits in one credit */ req->MaxOutputResponse = cpu_to_le32(0xFF00); /* < 64K uses 1 credit */ if (is_fsctl) req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL); else req->Flags = 0; iov[0].iov_base = (char *)req; /* * If no input data, the size of ioctl struct in * protocol spec still includes a 1 byte data buffer, * but if input data passed to ioctl, we do not * want to double count this, so we do not send * the dummy one byte of data in iovec[0] if sending * input data (in iovec[1]). We also must add 4 bytes * in first iovec to allow for rfc1002 length field. */ if (indatalen) { iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; inc_rfc1001_len(req, indatalen - 1); } else iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base; if ((rc != 0) && (rc != -EINVAL)) { cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE); goto ioctl_exit; } else if (rc == -EINVAL) { if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) && (opcode != FSCTL_SRV_COPYCHUNK)) { cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE); goto ioctl_exit; } } /* check if caller wants to look at return data or just return rc */ if ((plen == NULL) || (out_data == NULL)) goto ioctl_exit; *plen = le32_to_cpu(rsp->OutputCount); /* We check for obvious errors in the output buffer length and offset */ if (*plen == 0) goto ioctl_exit; /* server returned no data */ else if (*plen > 0xFF00) { cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen); *plen = 0; rc = -EIO; goto ioctl_exit; } if (get_rfc1002_length(rsp) < le32_to_cpu(rsp->OutputOffset) + *plen) { cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen, le32_to_cpu(rsp->OutputOffset)); *plen = 0; rc = -EIO; goto ioctl_exit; } *out_data = kmalloc(*plen, GFP_KERNEL); if (*out_data == NULL) { rc = -ENOMEM; goto ioctl_exit; } shdr = get_sync_hdr(rsp); memcpy(*out_data, (char *)shdr + le32_to_cpu(rsp->OutputOffset), *plen); ioctl_exit: free_rsp_buf(resp_buftype, rsp); return rc; } /* * Individual callers to ioctl worker function follow */ int SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { int rc; struct compress_ioctl fsctl_input; char *ret_data = NULL; fsctl_input.CompressionState = cpu_to_le16(COMPRESSION_FORMAT_DEFAULT); rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid, FSCTL_SET_COMPRESSION, true /* is_fsctl */, (char *)&fsctl_input /* data input */, 2 /* in data len */, &ret_data /* out data */, NULL); cifs_dbg(FYI, "set compression rc %d\n", rc); return rc; } int SMB2_close(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { struct smb2_close_req *req; struct smb2_close_rsp *rsp; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype; int rc = 0; int flags = 0; cifs_dbg(FYI, "Close\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_close_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE); goto close_exit; } /* BB FIXME - decode close response, update inode for caching */ close_exit: free_rsp_buf(resp_buftype, rsp); return rc; } static int validate_buf(unsigned int offset, unsigned int buffer_length, struct smb2_hdr *hdr, unsigned int min_buf_size) { unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length); char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr; char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr; char *end_of_buf = begin_of_buf + buffer_length; if (buffer_length < min_buf_size) { cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n", buffer_length, min_buf_size); return -EINVAL; } /* check if beyond RFC1001 maximum length */ if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) { cifs_dbg(VFS, "buffer length %d or smb length %d too large\n", buffer_length, smb_len); return -EINVAL; } if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) { cifs_dbg(VFS, "illegal server response, bad offset to data\n"); return -EINVAL; } return 0; } /* * If SMB buffer fields are valid, copy into temporary buffer to hold result. * Caller must free buffer. */ static int validate_and_copy_buf(unsigned int offset, unsigned int buffer_length, struct smb2_hdr *hdr, unsigned int minbufsize, char *data) { char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr; int rc; if (!data) return -EINVAL; rc = validate_buf(offset, buffer_length, hdr, minbufsize); if (rc) return rc; memcpy(data, begin_of_buf, buffer_length); return 0; } static int query_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u8 info_class, size_t output_len, size_t min_len, void *data) { struct smb2_query_info_req *req; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; int flags = 0; cifs_dbg(FYI, "Query Info\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->InfoType = SMB2_O_INFO_FILE; req->FileInfoClass = info_class; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; /* 4 for rfc1002 length field and 1 for Buffer */ req->InputBufferOffset = cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4); req->OutputBufferLength = cpu_to_le32(output_len); iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qinf_exit; } rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr, min_len, data); qinf_exit: free_rsp_buf(resp_buftype, rsp); return rc; } int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_ALL_INFORMATION, sizeof(struct smb2_file_all_info) + PATH_MAX * 2, sizeof(struct smb2_file_all_info), data); } int SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_INTERNAL_INFORMATION, sizeof(struct smb2_file_internal_info), sizeof(struct smb2_file_internal_info), uniqueid); } /* * This is a no-op for now. We're not really interested in the reply, but * rather in the fact that the server sent one and that server->lstrp * gets updated. * * FIXME: maybe we should consider checking that the reply matches request? */ static void smb2_echo_callback(struct mid_q_entry *mid) { struct TCP_Server_Info *server = mid->callback_data; struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf; unsigned int credits_received = 1; if (mid->mid_state == MID_RESPONSE_RECEIVED) credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest); mutex_lock(&server->srv_mutex); DeleteMidQEntry(mid); mutex_unlock(&server->srv_mutex); add_credits(server, credits_received, CIFS_ECHO_OP); } void smb2_reconnect_server(struct work_struct *work) { struct TCP_Server_Info *server = container_of(work, struct TCP_Server_Info, reconnect.work); struct cifs_ses *ses; struct cifs_tcon *tcon, *tcon2; struct list_head tmp_list; int tcon_exist = false; /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */ mutex_lock(&server->reconnect_mutex); INIT_LIST_HEAD(&tmp_list); cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n"); spin_lock(&cifs_tcp_ses_lock); list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) { list_for_each_entry(tcon, &ses->tcon_list, tcon_list) { if (tcon->need_reconnect || tcon->need_reopen_files) { tcon->tc_count++; list_add_tail(&tcon->rlist, &tmp_list); tcon_exist = true; } } } /* * Get the reference to server struct to be sure that the last call of * cifs_put_tcon() in the loop below won't release the server pointer. */ if (tcon_exist) server->srv_count++; spin_unlock(&cifs_tcp_ses_lock); list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) { if (!smb2_reconnect(SMB2_INTERNAL_CMD, tcon)) cifs_reopen_persistent_handles(tcon); list_del_init(&tcon->rlist); cifs_put_tcon(tcon); } cifs_dbg(FYI, "Reconnecting tcons finished\n"); mutex_unlock(&server->reconnect_mutex); /* now we can safely release srv struct */ if (tcon_exist) cifs_put_tcp_session(server, 1); } int SMB2_echo(struct TCP_Server_Info *server) { struct smb2_echo_req *req; int rc = 0; struct kvec iov[2]; struct smb_rqst rqst = { .rq_iov = iov, .rq_nvec = 2 }; cifs_dbg(FYI, "In echo request\n"); if (server->tcpStatus == CifsNeedNegotiate) { /* No need to send echo on newly established connections */ queue_delayed_work(cifsiod_wq, &server->reconnect, 0); return rc; } rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req); if (rc) return rc; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); /* 4 for rfc1002 length field */ iov[0].iov_len = 4; iov[0].iov_base = (char *)req; iov[1].iov_len = get_rfc1002_length(req); iov[1].iov_base = (char *)req + 4; rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, server, CIFS_ECHO_OP); if (rc) cifs_dbg(FYI, "Echo request failed: %d\n", rc); cifs_small_buf_release(req); return rc; } int SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { struct smb2_flush_req *req; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype; int rc = 0; int flags = 0; cifs_dbg(FYI, "Flush\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field */ iov[0].iov_len = get_rfc1002_length(req) + 4; rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); if (rc != 0) cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } /* * To form a chain of read requests, any read requests after the first should * have the end_of_chain boolean set to true. */ static int smb2_new_read_req(void **buf, unsigned int *total_len, struct cifs_io_parms *io_parms, unsigned int remaining_bytes, int request_type) { int rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_sync_hdr *shdr; rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req, total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; shdr = &req->sync_hdr; shdr->ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->ReadChannelInfoOffset = 0; /* reserved */ req->ReadChannelInfoLength = 0; /* reserved */ req->Channel = 0; /* reserved */ req->MinimumCount = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); if (request_type & CHAINED_REQUEST) { if (!(request_type & END_OF_CHAIN)) { /* next 8-byte aligned request */ *total_len = DIV_ROUND_UP(*total_len, 8) * 8; shdr->NextCommand = cpu_to_le32(*total_len); } else /* END_OF_CHAIN */ shdr->NextCommand = 0; if (request_type & RELATED_REQUEST) { shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS; /* * Related requests use info from previous read request * in chain. */ shdr->SessionId = 0xFFFFFFFF; shdr->TreeId = 0xFFFFFFFF; req->PersistentFileId = 0xFFFFFFFF; req->VolatileFileId = 0xFFFFFFFF; } } if (remaining_bytes > io_parms->length) req->RemainingBytes = cpu_to_le32(remaining_bytes); else req->RemainingBytes = 0; *buf = req; return rc; } static void smb2_readv_callback(struct mid_q_entry *mid) { struct cifs_readdata *rdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)rdata->iov[1].iov_base; unsigned int credits_received = 1; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 2, .rq_pages = rdata->pages, .rq_npages = rdata->nr_pages, .rq_pagesz = rdata->pagesz, .rq_tailsz = rdata->tailsz }; cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n", __func__, mid->mid, mid->mid_state, rdata->result, rdata->bytes); switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits_received = le16_to_cpu(shdr->CreditRequest); /* result already set, check signature */ if (server->sign) { int rc; rc = smb2_verify_signature(&rqst, server); if (rc) cifs_dbg(VFS, "SMB signature verification returned error = %d\n", rc); } /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: rdata->result = -EAGAIN; if (server->sign && rdata->got_bytes) /* reset bytes number since we can not check a sign */ rdata->got_bytes = 0; /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; default: if (rdata->result != -ENODATA) rdata->result = -EIO; } if (rdata->result) cifs_stats_fail_inc(tcon, SMB2_READ_HE); queue_work(cifsiod_wq, &rdata->work); mutex_lock(&server->srv_mutex); DeleteMidQEntry(mid); mutex_unlock(&server->srv_mutex); add_credits(server, credits_received, 0); } /* smb2_async_readv - send an async read, and set up mid to handle result */ int smb2_async_readv(struct cifs_readdata *rdata) { int rc, flags = 0; char *buf; struct smb2_sync_hdr *shdr; struct cifs_io_parms io_parms; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 2 }; struct TCP_Server_Info *server; unsigned int total_len; __be32 req_len; cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n", __func__, rdata->offset, rdata->bytes); io_parms.tcon = tlink_tcon(rdata->cfile->tlink); io_parms.offset = rdata->offset; io_parms.length = rdata->bytes; io_parms.persistent_fid = rdata->cfile->fid.persistent_fid; io_parms.volatile_fid = rdata->cfile->fid.volatile_fid; io_parms.pid = rdata->pid; server = io_parms.tcon->ses->server; rc = smb2_new_read_req((void **) &buf, &total_len, &io_parms, 0, 0); if (rc) { if (rc == -EAGAIN && rdata->credits) { /* credits was reset by reconnect */ rdata->credits = 0; /* reduce in_flight value since we won't send the req */ spin_lock(&server->req_lock); server->in_flight--; spin_unlock(&server->req_lock); } return rc; } if (encryption_required(io_parms.tcon)) flags |= CIFS_TRANSFORM_REQ; req_len = cpu_to_be32(total_len); rdata->iov[0].iov_base = &req_len; rdata->iov[0].iov_len = sizeof(__be32); rdata->iov[1].iov_base = buf; rdata->iov[1].iov_len = total_len; shdr = (struct smb2_sync_hdr *)buf; if (rdata->credits) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes, SMB2_MAX_BUFFER_SIZE)); shdr->CreditRequest = shdr->CreditCharge; spin_lock(&server->req_lock); server->credits += rdata->credits - le16_to_cpu(shdr->CreditCharge); spin_unlock(&server->req_lock); wake_up(&server->request_q); flags |= CIFS_HAS_CREDITS; } kref_get(&rdata->refcount); rc = cifs_call_async(io_parms.tcon->ses->server, &rqst, cifs_readv_receive, smb2_readv_callback, rdata, flags); if (rc) { kref_put(&rdata->refcount, cifs_readdata_release); cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE); } cifs_small_buf_release(buf); return rc; } int SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct smb2_sync_hdr *shdr; struct kvec iov[2]; struct kvec rsp_iov; unsigned int total_len; __be32 req_len; struct smb_rqst rqst = { .rq_iov = iov, .rq_nvec = 2 }; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, 0, 0); if (rc) return rc; if (encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req_len = cpu_to_be32(total_len); iov[0].iov_base = &req_len; iov[0].iov_len = sizeof(__be32); iov[1].iov_base = req; iov[1].iov_len = total_len; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; shdr = get_sync_hdr(rsp); if (shdr->Status == STATUS_END_OF_FILE) { free_rsp_buf(resp_buftype, rsp_iov.iov_base); return 0; } if (rc) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, "Send error in read = %d\n", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, "bad length %d for count %d\n", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } } if (*buf) { memcpy(*buf, (char *)shdr + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; } /* * Check the mid_state and signature on received buffer (if any), and queue the * workqueue completion task. */ static void smb2_writev_callback(struct mid_q_entry *mid) { struct cifs_writedata *wdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; unsigned int written; struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf; unsigned int credits_received = 1; switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest); wdata->result = smb2_check_receive(mid, tcon->ses->server, 0); if (wdata->result != 0) break; written = le32_to_cpu(rsp->DataLength); /* * Mask off high 16 bits when bytes written as returned * by the server is greater than bytes requested by the * client. OS/2 servers are known to set incorrect * CountHigh values. */ if (written > wdata->bytes) written &= 0xFFFF; if (written < wdata->bytes) wdata->result = -ENOSPC; else wdata->bytes = written; break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: wdata->result = -EAGAIN; break; default: wdata->result = -EIO; break; } if (wdata->result) cifs_stats_fail_inc(tcon, SMB2_WRITE_HE); queue_work(cifsiod_wq, &wdata->work); mutex_lock(&server->srv_mutex); DeleteMidQEntry(mid); mutex_unlock(&server->srv_mutex); add_credits(tcon->ses->server, credits_received, 0); } /* smb2_async_writev - send an async write, and set up mid to handle result */ int smb2_async_writev(struct cifs_writedata *wdata, void (*release)(struct kref *kref)) { int rc = -EACCES, flags = 0; struct smb2_write_req *req = NULL; struct smb2_sync_hdr *shdr; struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct kvec iov[2]; struct smb_rqst rqst = { }; rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req); if (rc) { if (rc == -EAGAIN && wdata->credits) { /* credits was reset by reconnect */ wdata->credits = 0; /* reduce in_flight value since we won't send the req */ spin_lock(&server->req_lock); server->in_flight--; spin_unlock(&server->req_lock); } goto async_writev_out; } if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; shdr = get_sync_hdr(req); shdr->ProcessId = cpu_to_le32(wdata->cfile->pid); req->PersistentFileId = wdata->cfile->fid.persistent_fid; req->VolatileFileId = wdata->cfile->fid.volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Offset = cpu_to_le64(wdata->offset); /* 4 for rfc1002 length field */ req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer) - 4); req->RemainingBytes = 0; /* 4 for rfc1002 length field and 1 for Buffer */ iov[0].iov_len = 4; iov[0].iov_base = req; iov[1].iov_len = get_rfc1002_length(req) - 1; iov[1].iov_base = (char *)req + 4; rqst.rq_iov = iov; rqst.rq_nvec = 2; rqst.rq_pages = wdata->pages; rqst.rq_npages = wdata->nr_pages; rqst.rq_pagesz = wdata->pagesz; rqst.rq_tailsz = wdata->tailsz; cifs_dbg(FYI, "async write at %llu %u bytes\n", wdata->offset, wdata->bytes); req->Length = cpu_to_le32(wdata->bytes); inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */); if (wdata->credits) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes, SMB2_MAX_BUFFER_SIZE)); shdr->CreditRequest = shdr->CreditCharge; spin_lock(&server->req_lock); server->credits += wdata->credits - le16_to_cpu(shdr->CreditCharge); spin_unlock(&server->req_lock); wake_up(&server->request_q); flags |= CIFS_HAS_CREDITS; } kref_get(&wdata->refcount); rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, wdata, flags); if (rc) { kref_put(&wdata->refcount, release); cifs_stats_fail_inc(tcon, SMB2_WRITE_HE); } async_writev_out: cifs_small_buf_release(req); return rc; } /* * SMB2_write function gets iov pointer to kvec array with n_vec as a length. * The length field from io_parms must be at least 1 and indicates a number of * elements with data to write that begins with position 1 in iov array. All * data length is specified by count. */ int SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; *nbytes = 0; if (n_vec < 1) return rc; rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); /* 4 for rfc1002 length field */ req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer) - 4); req->RemainingBytes = 0; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for Buffer */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* length of entire message including data to be written */ inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */); rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else *nbytes = le32_to_cpu(rsp->DataLength); free_rsp_buf(resp_buftype, rsp); return rc; } static unsigned int num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size) { int len; unsigned int entrycount = 0; unsigned int next_offset = 0; FILE_DIRECTORY_INFO *entryptr; if (bufstart == NULL) return 0; entryptr = (FILE_DIRECTORY_INFO *)bufstart; while (1) { entryptr = (FILE_DIRECTORY_INFO *) ((char *)entryptr + next_offset); if ((char *)entryptr + size > end_of_buf) { cifs_dbg(VFS, "malformed search entry would overflow\n"); break; } len = le32_to_cpu(entryptr->FileNameLength); if ((char *)entryptr + len + size > end_of_buf) { cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n", end_of_buf); break; } *lastentry = (char *)entryptr; entrycount++; next_offset = le32_to_cpu(entryptr->NextEntryOffset); if (!next_offset) break; } return entrycount; } /* * Readdir/FindFirst */ int SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int index, struct cifs_search_info *srch_inf) { struct smb2_query_directory_req *req; struct smb2_query_directory_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov; int rc = 0; int len; int resp_buftype = CIFS_NO_BUFFER; unsigned char *bufptr; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; __le16 asteriks = cpu_to_le16('*'); char *end_of_smb; unsigned int output_size = CIFSMaxBufSize; size_t info_buf_size; int flags = 0; if (ses && (ses->server)) server = ses->server; else return -EIO; rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; switch (srch_inf->info_level) { case SMB_FIND_FILE_DIRECTORY_INFO: req->FileInformationClass = FILE_DIRECTORY_INFORMATION; info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1; break; case SMB_FIND_FILE_ID_FULL_DIR_INFO: req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION; info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1; break; default: cifs_dbg(VFS, "info level %u isn't supported\n", srch_inf->info_level); rc = -EINVAL; goto qdir_exit; } req->FileIndex = cpu_to_le32(index); req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; len = 0x2; bufptr = req->Buffer; memcpy(bufptr, &asteriks, len); req->FileNameOffset = cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4); req->FileNameLength = cpu_to_le16(len); /* * BB could be 30 bytes or so longer if we used SMB2 specific * buffer lengths, but this is safe and close enough. */ output_size = min_t(unsigned int, output_size, server->maxBuf); output_size = min_t(unsigned int, output_size, 2 << 15); req->OutputBufferLength = cpu_to_le32(output_size); iov[0].iov_base = (char *)req; /* 4 for RFC1001 length and 1 for Buffer */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; iov[1].iov_base = (char *)(req->Buffer); iov[1].iov_len = len; inc_rfc1001_len(req, len - 1 /* Buffer */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base; if (rc) { if (rc == -ENODATA && rsp->hdr.sync_hdr.Status == STATUS_NO_MORE_FILES) { srch_inf->endOfSearch = true; rc = 0; } cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE); goto qdir_exit; } rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr, info_buf_size); if (rc) goto qdir_exit; srch_inf->unicode = true; if (srch_inf->ntwrk_buf_start) { if (srch_inf->smallBuf) cifs_small_buf_release(srch_inf->ntwrk_buf_start); else cifs_buf_release(srch_inf->ntwrk_buf_start); } srch_inf->ntwrk_buf_start = (char *)rsp; srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ + (char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset); /* 4 for rfc1002 length field */ end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr; srch_inf->entries_in_buffer = num_entries(srch_inf->srch_entries_start, end_of_smb, &srch_inf->last_entry, info_buf_size); srch_inf->index_of_last_entry += srch_inf->entries_in_buffer; cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n", srch_inf->entries_in_buffer, srch_inf->index_of_last_entry, srch_inf->srch_entries_start, srch_inf->last_entry); if (resp_buftype == CIFS_LARGE_BUFFER) srch_inf->smallBuf = false; else if (resp_buftype == CIFS_SMALL_BUFFER) srch_inf->smallBuf = true; else cifs_dbg(VFS, "illegal search buffer type\n"); return rc; qdir_exit: free_rsp_buf(resp_buftype, rsp); return rc; } static int send_set_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 pid, int info_class, unsigned int num, void **data, unsigned int *size) { struct smb2_set_info_req *req; struct smb2_set_info_rsp *rsp = NULL; struct kvec *iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; unsigned int i; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; int flags = 0; if (ses && (ses->server)) server = ses->server; else return -EIO; if (!num) return -EINVAL; iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL); if (!iov) return -ENOMEM; rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req); if (rc) { kfree(iov); return rc; } if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid); req->InfoType = SMB2_O_INFO_FILE; req->FileInfoClass = info_class; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; /* 4 for RFC1001 length and 1 for Buffer */ req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4); req->BufferLength = cpu_to_le32(*size); inc_rfc1001_len(req, *size - 1 /* Buffer */); memcpy(req->Buffer, *data, *size); iov[0].iov_base = (char *)req; /* 4 for RFC1001 length */ iov[0].iov_len = get_rfc1002_length(req) + 4; for (i = 1; i < num; i++) { inc_rfc1001_len(req, size[i]); le32_add_cpu(&req->BufferLength, size[i]); iov[i].iov_base = (char *)data[i]; iov[i].iov_len = size[i]; } rc = SendReceive2(xid, ses, iov, num, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base; if (rc != 0) cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE); free_rsp_buf(resp_buftype, rsp); kfree(iov); return rc; } int SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le16 *target_file) { struct smb2_file_rename_info info; void **data; unsigned int size[2]; int rc; int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX)); data = kmalloc(sizeof(void *) * 2, GFP_KERNEL); if (!data) return -ENOMEM; info.ReplaceIfExists = 1; /* 1 = replace existing target with new */ /* 0 = fail if target already exists */ info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */ info.FileNameLength = cpu_to_le32(len); data[0] = &info; size[0] = sizeof(struct smb2_file_rename_info); data[1] = target_file; size[1] = len + 2 /* null */; rc = send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_RENAME_INFORMATION, 2, data, size); kfree(data); return rc; } int SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { __u8 delete_pending = 1; void *data; unsigned int size; data = &delete_pending; size = 1; /* sizeof __u8 */ return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_DISPOSITION_INFORMATION, 1, &data, &size); } int SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le16 *target_file) { struct smb2_file_link_info info; void **data; unsigned int size[2]; int rc; int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX)); data = kmalloc(sizeof(void *) * 2, GFP_KERNEL); if (!data) return -ENOMEM; info.ReplaceIfExists = 0; /* 1 = replace existing link with new */ /* 0 = fail if link already exists */ info.RootDirectory = 0; /* MBZ for network ops (why does spec say?) */ info.FileNameLength = cpu_to_le32(len); data[0] = &info; size[0] = sizeof(struct smb2_file_link_info); data[1] = target_file; size[1] = len + 2 /* null */; rc = send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_LINK_INFORMATION, 2, data, size); kfree(data); return rc; } int SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc) { struct smb2_file_eof_info info; void *data; unsigned int size; info.EndOfFile = *eof; data = &info; size = sizeof(struct smb2_file_eof_info); if (is_falloc) return send_set_info(xid, tcon, persistent_fid, volatile_fid, pid, FILE_ALLOCATION_INFORMATION, 1, &data, &size); else return send_set_info(xid, tcon, persistent_fid, volatile_fid, pid, FILE_END_OF_FILE_INFORMATION, 1, &data, &size); } int SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf) { unsigned int size; size = sizeof(FILE_BASIC_INFO); return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_BASIC_INFORMATION, 1, (void **)&buf, &size); } int SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon, const u64 persistent_fid, const u64 volatile_fid, __u8 oplock_level) { int rc; struct smb2_oplock_break *req = NULL; int flags = CIFS_OBREAK_OP; cifs_dbg(FYI, "SMB2_oplock_break\n"); rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->VolatileFid = volatile_fid; req->PersistentFid = persistent_fid; req->OplockLevel = oplock_level; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags); cifs_small_buf_release(req); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc); } return rc; } static void copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf, struct kstatfs *kst) { kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) * le32_to_cpu(pfs_inf->SectorsPerAllocationUnit); kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits); kst->f_bfree = le64_to_cpu(pfs_inf->ActualAvailableAllocationUnits); kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits); return; } static int build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level, int outbuf_len, u64 persistent_fid, u64 volatile_fid) { int rc; struct smb2_query_info_req *req; cifs_dbg(FYI, "Query FSInfo level %d\n", level); if ((tcon->ses == NULL) || (tcon->ses->server == NULL)) return -EIO; rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req); if (rc) return rc; req->InfoType = SMB2_O_INFO_FILESYSTEM; req->FileInfoClass = level; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; /* 4 for rfc1002 length field and 1 for pad */ req->InputBufferOffset = cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4); req->OutputBufferLength = cpu_to_le32( outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4); iov->iov_base = (char *)req; /* 4 for rfc1002 length field */ iov->iov_len = get_rfc1002_length(req) + 4; return 0; } int SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; struct smb2_fs_full_size_info *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION, sizeof(struct smb2_fs_full_size_info), persistent_fid, volatile_fid); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ + le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr); rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr, sizeof(struct smb2_fs_full_size_info)); if (!rc) copy_fs_info_to_kstatfs(info, fsdata); qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int level) { struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype, max_len, min_len; struct cifs_ses *ses = tcon->ses; unsigned int rsp_len, offset; int flags = 0; if (level == FS_DEVICE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_DEVICE_INFO); min_len = sizeof(FILE_SYSTEM_DEVICE_INFO); } else if (level == FS_ATTRIBUTE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO); min_len = MIN_FS_ATTR_INFO_SIZE; } else if (level == FS_SECTOR_SIZE_INFORMATION) { max_len = sizeof(struct smb3_fs_ss_info); min_len = sizeof(struct smb3_fs_ss_info); } else { cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level); return -EINVAL; } rc = build_qfs_info_req(&iov, tcon, level, max_len, persistent_fid, volatile_fid); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsattr_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; rsp_len = le32_to_cpu(rsp->OutputBufferLength); offset = le16_to_cpu(rsp->OutputBufferOffset); rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len); if (rc) goto qfsattr_exit; if (level == FS_ATTRIBUTE_INFORMATION) memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset + (char *)&rsp->hdr, min_t(unsigned int, rsp_len, max_len)); else if (level == FS_DEVICE_INFORMATION) memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset + (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO)); else if (level == FS_SECTOR_SIZE_INFORMATION) { struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *) (4 /* RFC1001 len */ + offset + (char *)&rsp->hdr); tcon->ss_flags = le32_to_cpu(ss_info->Flags); tcon->perf_sector_size = le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf); } qfsattr_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon, const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid, const __u32 num_lock, struct smb2_lock_element *buf) { int rc = 0; struct smb2_lock_req *req = NULL; struct kvec iov[2]; struct kvec rsp_iov; int resp_buf_type; unsigned int count; int flags = CIFS_NO_RESP; cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock); rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid); req->LockCount = cpu_to_le16(num_lock); req->PersistentFileId = persist_fid; req->VolatileFileId = volatile_fid; count = num_lock * sizeof(struct smb2_lock_element); inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element)); iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and count for all locks */ iov[0].iov_len = get_rfc1002_length(req) + 4 - count; iov[1].iov_base = (char *)buf; iov[1].iov_len = count; cifs_stats_inc(&tcon->stats.cifs_stats.num_locks); rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); if (rc) { cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc); cifs_stats_fail_inc(tcon, SMB2_LOCK_HE); } return rc; } int SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon, const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid, const __u64 length, const __u64 offset, const __u32 lock_flags, const bool wait) { struct smb2_lock_element lock; lock.Offset = cpu_to_le64(offset); lock.Length = cpu_to_le64(length); lock.Flags = cpu_to_le32(lock_flags); if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK) lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY); return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock); } int SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon, __u8 *lease_key, const __le32 lease_state) { int rc; struct smb2_lease_ack *req = NULL; int flags = CIFS_OBREAK_OP; cifs_dbg(FYI, "SMB2_lease_break\n"); rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req); if (rc) return rc; if (encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1); req->StructureSize = cpu_to_le16(36); inc_rfc1001_len(req, 12); memcpy(req->LeaseKey, lease_key, 16); req->LeaseState = lease_state; rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags); cifs_small_buf_release(req); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc); } return rc; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_101_1
crossvul-cpp_data_bad_5108_2
/* packet-usb-masstorage.c * * usb mass storage dissector * Ronnie Sahlberg 2006 * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include "packet-usb.h" #include "packet-scsi.h" void proto_register_usb_ms(void); void proto_reg_handoff_usb_ms(void); /* protocols and header fields */ static int proto_usb_ms = -1; static int hf_usb_ms_dCBWSignature = -1; static int hf_usb_ms_dCBWTag = -1; static int hf_usb_ms_dCBWDataTransferLength = -1; static int hf_usb_ms_dCBWFlags = -1; static int hf_usb_ms_dCBWTarget = -1; static int hf_usb_ms_dCBWLUN = -1; static int hf_usb_ms_dCBWCBLength = -1; static int hf_usb_ms_dCSWSignature = -1; static int hf_usb_ms_dCSWDataResidue = -1; static int hf_usb_ms_dCSWStatus = -1; static int hf_usb_ms_request = -1; static int hf_usb_ms_value = -1; static int hf_usb_ms_index = -1; static int hf_usb_ms_length = -1; static int hf_usb_ms_maxlun = -1; static gint ett_usb_ms = -1; /* there is one such structure for each masstorage conversation */ typedef struct _usb_ms_conv_info_t { wmem_tree_t *itl; /* indexed by LUN */ wmem_tree_t *itlq; /* pinfo->num */ } usb_ms_conv_info_t; static const value_string status_vals[] = { {0x00, "Command Passed"}, {0x01, "Command Failed"}, {0x02, "Phase Error"}, {0, NULL} }; static void dissect_usb_ms_reset(packet_info *pinfo _U_, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info _U_, usb_conv_info_t *usb_conv_info _U_) { if(is_request){ proto_tree_add_item(tree, hf_usb_ms_value, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_index, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_length, tvb, offset, 2, ENC_BIG_ENDIAN); /*offset += 2;*/ } else { /* no data in reset response */ } } static void dissect_usb_ms_get_max_lun(packet_info *pinfo _U_, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info _U_, usb_conv_info_t *usb_conv_info _U_) { if(is_request){ proto_tree_add_item(tree, hf_usb_ms_value, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_index, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_length, tvb, offset, 2, ENC_BIG_ENDIAN); /*offset += 2;*/ } else { proto_tree_add_item(tree, hf_usb_ms_maxlun, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } } typedef void (*usb_setup_dissector)(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info, usb_conv_info_t *usb_conv_info); typedef struct _usb_setup_dissector_table_t { guint8 request; usb_setup_dissector dissector; } usb_setup_dissector_table_t; #define USB_SETUP_RESET 0xff #define USB_SETUP_GET_MAX_LUN 0xfe static const usb_setup_dissector_table_t setup_dissectors[] = { {USB_SETUP_RESET, dissect_usb_ms_reset}, {USB_SETUP_GET_MAX_LUN, dissect_usb_ms_get_max_lun}, {0, NULL} }; static const value_string setup_request_names_vals[] = { {USB_SETUP_RESET, "RESET"}, {USB_SETUP_GET_MAX_LUN, "GET MAX LUN"}, {0, NULL} }; /* Dissector for mass storage control . * Returns tvb_captured_length(tvb) if a class specific dissector was found * and 0 othervise. */ static gint dissect_usb_ms_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { gboolean is_request; usb_conv_info_t *usb_conv_info; usb_trans_info_t *usb_trans_info; int offset=0; usb_setup_dissector dissector = NULL; const usb_setup_dissector_table_t *tmp; /* Reject the packet if data or usb_trans_info are NULL */ if (data == NULL || ((usb_conv_info_t *)data)->usb_trans_info == NULL) return 0; usb_conv_info = (usb_conv_info_t *)data; usb_trans_info = usb_conv_info->usb_trans_info; is_request=(pinfo->srcport==NO_ENDPOINT); /* See if we can find a class specific dissector for this request */ for(tmp=setup_dissectors;tmp->dissector;tmp++){ if (tmp->request == usb_trans_info->setup.request){ dissector=tmp->dissector; break; } } /* No we could not find any class specific dissector for this request * return 0 and let USB try any of the standard requests. */ if(!dissector){ return 0; } col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS"); col_add_fstr(pinfo->cinfo, COL_INFO, "%s %s", val_to_str(usb_trans_info->setup.request, setup_request_names_vals, "Unknown type %x"), is_request?"Request":"Response"); if(is_request){ proto_tree_add_item(tree, hf_usb_ms_request, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; } dissector(pinfo, tree, tvb, offset, is_request, usb_trans_info, usb_conv_info); return tvb_captured_length(tvb); } /* dissector for mass storage bulk data */ static int dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data) { usb_conv_info_t *usb_conv_info; usb_ms_conv_info_t *usb_ms_conv_info; proto_tree *tree; proto_item *ti; guint32 signature=0; int offset=0; gboolean is_request; itl_nexus_t *itl; itlq_nexus_t *itlq; /* Reject the packet if data is NULL */ if (data == NULL) return 0; usb_conv_info = (usb_conv_info_t *)data; /* verify that we do have a usb_ms_conv_info */ usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data; if(!usb_ms_conv_info){ usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t); usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope()); usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope()); usb_conv_info->class_data=usb_ms_conv_info; } is_request=(pinfo->srcport==NO_ENDPOINT); col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS"); col_clear(pinfo->cinfo, COL_INFO); ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage"); tree = proto_item_add_subtree(ti, ett_usb_ms); signature=tvb_get_letohl(tvb, offset); /* * SCSI CDB inside CBW */ if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){ tvbuff_t *cdb_tvb; int cdbrlen, cdblen; guint8 lun, flags; guint32 datalen; /* dCBWSignature */ proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCBWTag */ proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCBWDataTransferLength */ proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN); datalen=tvb_get_letohl(tvb, offset); offset+=4; /* dCBWFlags */ proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN); flags=tvb_get_guint8(tvb, offset); offset+=1; /* dCBWLUN */ proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN); lun=tvb_get_guint8(tvb, offset)&0x0f; offset+=1; /* make sure we have a ITL structure for this LUN */ itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun); if(!itl){ itl=wmem_new(wmem_file_scope(), itl_nexus_t); itl->cmdset=0xff; itl->conversation=NULL; wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl); } /* make sure we have an ITLQ structure for this LUN/transaction */ itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ itlq=wmem_new(wmem_file_scope(), itlq_nexus_t); itlq->lun=lun; itlq->scsi_opcode=0xffff; itlq->task_flags=0; if(datalen){ if(flags&0x80){ itlq->task_flags|=SCSI_DATA_READ; } else { itlq->task_flags|=SCSI_DATA_WRITE; } } itlq->data_length=datalen; itlq->bidir_data_length=0; itlq->fc_time=pinfo->abs_ts; itlq->first_exchange_frame=pinfo->num; itlq->last_exchange_frame=0; itlq->flags=0; itlq->alloc_len=0; itlq->extra_data=NULL; wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq); } /* dCBWCBLength */ proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN); cdbrlen=tvb_get_guint8(tvb, offset)&0x1f; offset+=1; cdblen=cdbrlen; if(cdblen>tvb_captured_length_remaining(tvb, offset)){ cdblen=tvb_captured_length_remaining(tvb, offset); } if(cdblen){ cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen); dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl); } return tvb_captured_length(tvb); } /* * SCSI RESPONSE inside CSW */ if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){ guint8 status; /* dCSWSignature */ proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWTag */ proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWDataResidue */ proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWStatus */ proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN); status=tvb_get_guint8(tvb, offset); /*offset+=1;*/ itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ return tvb_captured_length(tvb); } itlq->last_exchange_frame=pinfo->num; itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun); if(!itl){ return tvb_captured_length(tvb); } if(!status){ dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0); } else { /* just send "check condition" */ dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02); } return tvb_captured_length(tvb); } /* * Ok it was neither CDB not STATUS so just assume it is either data in/out */ itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ return tvb_captured_length(tvb); } itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun); if(!itl){ return tvb_captured_length(tvb); } dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0); return tvb_captured_length(tvb); } static gboolean dissect_usb_ms_bulk_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data) { const gchar usbc[] = {0x55, 0x53, 0x42, 0x43}; const gchar usbs[] = {0x55, 0x53, 0x42, 0x53}; if (tvb_reported_length(tvb) < 4) return FALSE; if (tvb_memeql(tvb, 0, usbc, sizeof(usbc)) == 0 || tvb_memeql(tvb, 0, usbs, sizeof(usbs)) == 0) { dissect_usb_ms_bulk(tvb, pinfo, tree, data); return TRUE; } return FALSE; } void proto_register_usb_ms(void) { static hf_register_info hf[] = { { &hf_usb_ms_dCBWSignature, { "Signature", "usbms.dCBWSignature", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWTag, { "Tag", "usbms.dCBWTag", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWDataTransferLength, { "DataTransferLength", "usbms.dCBWDataTransferLength", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWFlags, { "Flags", "usbms.dCBWFlags", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWTarget, { "Target", "usbms.dCBWTarget", FT_UINT8, BASE_HEX_DEC, NULL, 0x70, "Target Number when enabling multi-target mode", HFILL }}, { &hf_usb_ms_dCBWLUN, { "LUN", "usbms.dCBWLUN", FT_UINT8, BASE_HEX, NULL, 0x0f, NULL, HFILL }}, { &hf_usb_ms_dCBWCBLength, { "CDB Length", "usbms.dCBWCBLength", FT_UINT8, BASE_HEX, NULL, 0x1f, NULL, HFILL }}, { &hf_usb_ms_dCSWSignature, { "Signature", "usbms.dCSWSignature", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCSWDataResidue, { "DataResidue", "usbms.dCSWDataResidue", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCSWStatus, { "Status", "usbms.dCSWStatus", FT_UINT8, BASE_HEX, VALS(status_vals), 0x0, NULL, HFILL }}, { &hf_usb_ms_request, { "bRequest", "usbms.setup.bRequest", FT_UINT8, BASE_HEX, VALS(setup_request_names_vals), 0x0, NULL, HFILL }}, { &hf_usb_ms_value, { "wValue", "usbms.setup.wValue", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_index, { "wIndex", "usbms.setup.wIndex", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_length, { "wLength", "usbms.setup.wLength", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_maxlun, { "Max LUN", "usbms.setup.maxlun", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }}, }; static gint *usb_ms_subtrees[] = { &ett_usb_ms, }; proto_usb_ms = proto_register_protocol("USB Mass Storage", "USBMS", "usbms"); proto_register_field_array(proto_usb_ms, hf, array_length(hf)); proto_register_subtree_array(usb_ms_subtrees, array_length(usb_ms_subtrees)); register_dissector("usbms", dissect_usb_ms_bulk, proto_usb_ms); } void proto_reg_handoff_usb_ms(void) { dissector_handle_t usb_ms_bulk_handle; dissector_handle_t usb_ms_control_handle; usb_ms_bulk_handle = find_dissector("usbms"); dissector_add_uint("usb.bulk", IF_CLASS_MASS_STORAGE, usb_ms_bulk_handle); usb_ms_control_handle = create_dissector_handle(dissect_usb_ms_control, proto_usb_ms); dissector_add_uint("usb.control", IF_CLASS_MASS_STORAGE, usb_ms_control_handle); heur_dissector_add("usb.bulk", dissect_usb_ms_bulk_heur, "Mass Storage USB bulk endpoint", "ms_usb_bulk", proto_usb_ms, HEURISTIC_ENABLE); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5108_2
crossvul-cpp_data_good_1327_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 only if bFree is true. */ 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); } /* ** 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 ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); 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 if( sqlite3WindowRewrite(pParse, p) ){ 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-476/c/good_1327_2
crossvul-cpp_data_good_5108_2
/* packet-usb-masstorage.c * * usb mass storage dissector * Ronnie Sahlberg 2006 * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include "packet-usb.h" #include "packet-scsi.h" void proto_register_usb_ms(void); void proto_reg_handoff_usb_ms(void); /* protocols and header fields */ static int proto_usb_ms = -1; static int hf_usb_ms_dCBWSignature = -1; static int hf_usb_ms_dCBWTag = -1; static int hf_usb_ms_dCBWDataTransferLength = -1; static int hf_usb_ms_dCBWFlags = -1; static int hf_usb_ms_dCBWTarget = -1; static int hf_usb_ms_dCBWLUN = -1; static int hf_usb_ms_dCBWCBLength = -1; static int hf_usb_ms_dCSWSignature = -1; static int hf_usb_ms_dCSWDataResidue = -1; static int hf_usb_ms_dCSWStatus = -1; static int hf_usb_ms_request = -1; static int hf_usb_ms_value = -1; static int hf_usb_ms_index = -1; static int hf_usb_ms_length = -1; static int hf_usb_ms_maxlun = -1; static gint ett_usb_ms = -1; /* there is one such structure for each masstorage conversation */ typedef struct _usb_ms_conv_info_t { wmem_tree_t *itl; /* indexed by LUN */ wmem_tree_t *itlq; /* pinfo->num */ } usb_ms_conv_info_t; static const value_string status_vals[] = { {0x00, "Command Passed"}, {0x01, "Command Failed"}, {0x02, "Phase Error"}, {0, NULL} }; static void dissect_usb_ms_reset(packet_info *pinfo _U_, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info _U_, usb_conv_info_t *usb_conv_info _U_) { if(is_request){ proto_tree_add_item(tree, hf_usb_ms_value, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_index, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_length, tvb, offset, 2, ENC_BIG_ENDIAN); /*offset += 2;*/ } else { /* no data in reset response */ } } static void dissect_usb_ms_get_max_lun(packet_info *pinfo _U_, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info _U_, usb_conv_info_t *usb_conv_info _U_) { if(is_request){ proto_tree_add_item(tree, hf_usb_ms_value, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_index, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_usb_ms_length, tvb, offset, 2, ENC_BIG_ENDIAN); /*offset += 2;*/ } else { proto_tree_add_item(tree, hf_usb_ms_maxlun, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } } typedef void (*usb_setup_dissector)(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, gboolean is_request, usb_trans_info_t *usb_trans_info, usb_conv_info_t *usb_conv_info); typedef struct _usb_setup_dissector_table_t { guint8 request; usb_setup_dissector dissector; } usb_setup_dissector_table_t; #define USB_SETUP_RESET 0xff #define USB_SETUP_GET_MAX_LUN 0xfe static const usb_setup_dissector_table_t setup_dissectors[] = { {USB_SETUP_RESET, dissect_usb_ms_reset}, {USB_SETUP_GET_MAX_LUN, dissect_usb_ms_get_max_lun}, {0, NULL} }; static const value_string setup_request_names_vals[] = { {USB_SETUP_RESET, "RESET"}, {USB_SETUP_GET_MAX_LUN, "GET MAX LUN"}, {0, NULL} }; /* Dissector for mass storage control . * Returns tvb_captured_length(tvb) if a class specific dissector was found * and 0 othervise. */ static gint dissect_usb_ms_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { gboolean is_request; usb_conv_info_t *usb_conv_info; usb_trans_info_t *usb_trans_info; int offset=0; usb_setup_dissector dissector = NULL; const usb_setup_dissector_table_t *tmp; /* Reject the packet if data or usb_trans_info are NULL */ if (data == NULL || ((usb_conv_info_t *)data)->usb_trans_info == NULL) return 0; usb_conv_info = (usb_conv_info_t *)data; usb_trans_info = usb_conv_info->usb_trans_info; is_request=(pinfo->srcport==NO_ENDPOINT); /* See if we can find a class specific dissector for this request */ for(tmp=setup_dissectors;tmp->dissector;tmp++){ if (tmp->request == usb_trans_info->setup.request){ dissector=tmp->dissector; break; } } /* No we could not find any class specific dissector for this request * return 0 and let USB try any of the standard requests. */ if(!dissector){ return 0; } col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS"); col_add_fstr(pinfo->cinfo, COL_INFO, "%s %s", val_to_str(usb_trans_info->setup.request, setup_request_names_vals, "Unknown type %x"), is_request?"Request":"Response"); if(is_request){ proto_tree_add_item(tree, hf_usb_ms_request, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; } dissector(pinfo, tree, tvb, offset, is_request, usb_trans_info, usb_conv_info); return tvb_captured_length(tvb); } /* dissector for mass storage bulk data */ static int dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data) { usb_conv_info_t *usb_conv_info; usb_ms_conv_info_t *usb_ms_conv_info; proto_tree *tree; proto_item *ti; guint32 signature=0; int offset=0; gboolean is_request; itl_nexus_t *itl; itlq_nexus_t *itlq; /* Reject the packet if data is NULL */ if (data == NULL) return 0; usb_conv_info = (usb_conv_info_t *)data; /* verify that we do have a usb_ms_conv_info */ usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data; if(!usb_ms_conv_info){ usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t); usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope()); usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope()); usb_conv_info->class_data=usb_ms_conv_info; usb_conv_info->class_data_type = USB_CONV_MASS_STORAGE; } else if (usb_conv_info->class_data_type != USB_CONV_MASS_STORAGE) { /* Don't dissect if another USB type is in the conversation */ return 0; } is_request=(pinfo->srcport==NO_ENDPOINT); col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS"); col_clear(pinfo->cinfo, COL_INFO); ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage"); tree = proto_item_add_subtree(ti, ett_usb_ms); signature=tvb_get_letohl(tvb, offset); /* * SCSI CDB inside CBW */ if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){ tvbuff_t *cdb_tvb; int cdbrlen, cdblen; guint8 lun, flags; guint32 datalen; /* dCBWSignature */ proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCBWTag */ proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCBWDataTransferLength */ proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN); datalen=tvb_get_letohl(tvb, offset); offset+=4; /* dCBWFlags */ proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN); flags=tvb_get_guint8(tvb, offset); offset+=1; /* dCBWLUN */ proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN); lun=tvb_get_guint8(tvb, offset)&0x0f; offset+=1; /* make sure we have a ITL structure for this LUN */ itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun); if(!itl){ itl=wmem_new(wmem_file_scope(), itl_nexus_t); itl->cmdset=0xff; itl->conversation=NULL; wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl); } /* make sure we have an ITLQ structure for this LUN/transaction */ itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ itlq=wmem_new(wmem_file_scope(), itlq_nexus_t); itlq->lun=lun; itlq->scsi_opcode=0xffff; itlq->task_flags=0; if(datalen){ if(flags&0x80){ itlq->task_flags|=SCSI_DATA_READ; } else { itlq->task_flags|=SCSI_DATA_WRITE; } } itlq->data_length=datalen; itlq->bidir_data_length=0; itlq->fc_time=pinfo->abs_ts; itlq->first_exchange_frame=pinfo->num; itlq->last_exchange_frame=0; itlq->flags=0; itlq->alloc_len=0; itlq->extra_data=NULL; wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq); } /* dCBWCBLength */ proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN); cdbrlen=tvb_get_guint8(tvb, offset)&0x1f; offset+=1; cdblen=cdbrlen; if(cdblen>tvb_captured_length_remaining(tvb, offset)){ cdblen=tvb_captured_length_remaining(tvb, offset); } if(cdblen){ cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen); dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl); } return tvb_captured_length(tvb); } /* * SCSI RESPONSE inside CSW */ if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){ guint8 status; /* dCSWSignature */ proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWTag */ proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWDataResidue */ proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWStatus */ proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN); status=tvb_get_guint8(tvb, offset); /*offset+=1;*/ itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ return tvb_captured_length(tvb); } itlq->last_exchange_frame=pinfo->num; itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun); if(!itl){ return tvb_captured_length(tvb); } if(!status){ dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0); } else { /* just send "check condition" */ dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02); } return tvb_captured_length(tvb); } /* * Ok it was neither CDB not STATUS so just assume it is either data in/out */ itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ return tvb_captured_length(tvb); } itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun); if(!itl){ return tvb_captured_length(tvb); } dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0); return tvb_captured_length(tvb); } static gboolean dissect_usb_ms_bulk_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data) { const gchar usbc[] = {0x55, 0x53, 0x42, 0x43}; const gchar usbs[] = {0x55, 0x53, 0x42, 0x53}; if (tvb_reported_length(tvb) < 4) return FALSE; if (tvb_memeql(tvb, 0, usbc, sizeof(usbc)) == 0 || tvb_memeql(tvb, 0, usbs, sizeof(usbs)) == 0) { dissect_usb_ms_bulk(tvb, pinfo, tree, data); return TRUE; } return FALSE; } void proto_register_usb_ms(void) { static hf_register_info hf[] = { { &hf_usb_ms_dCBWSignature, { "Signature", "usbms.dCBWSignature", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWTag, { "Tag", "usbms.dCBWTag", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWDataTransferLength, { "DataTransferLength", "usbms.dCBWDataTransferLength", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWFlags, { "Flags", "usbms.dCBWFlags", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCBWTarget, { "Target", "usbms.dCBWTarget", FT_UINT8, BASE_HEX_DEC, NULL, 0x70, "Target Number when enabling multi-target mode", HFILL }}, { &hf_usb_ms_dCBWLUN, { "LUN", "usbms.dCBWLUN", FT_UINT8, BASE_HEX, NULL, 0x0f, NULL, HFILL }}, { &hf_usb_ms_dCBWCBLength, { "CDB Length", "usbms.dCBWCBLength", FT_UINT8, BASE_HEX, NULL, 0x1f, NULL, HFILL }}, { &hf_usb_ms_dCSWSignature, { "Signature", "usbms.dCSWSignature", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCSWDataResidue, { "DataResidue", "usbms.dCSWDataResidue", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_dCSWStatus, { "Status", "usbms.dCSWStatus", FT_UINT8, BASE_HEX, VALS(status_vals), 0x0, NULL, HFILL }}, { &hf_usb_ms_request, { "bRequest", "usbms.setup.bRequest", FT_UINT8, BASE_HEX, VALS(setup_request_names_vals), 0x0, NULL, HFILL }}, { &hf_usb_ms_value, { "wValue", "usbms.setup.wValue", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_index, { "wIndex", "usbms.setup.wIndex", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_length, { "wLength", "usbms.setup.wLength", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_usb_ms_maxlun, { "Max LUN", "usbms.setup.maxlun", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }}, }; static gint *usb_ms_subtrees[] = { &ett_usb_ms, }; proto_usb_ms = proto_register_protocol("USB Mass Storage", "USBMS", "usbms"); proto_register_field_array(proto_usb_ms, hf, array_length(hf)); proto_register_subtree_array(usb_ms_subtrees, array_length(usb_ms_subtrees)); register_dissector("usbms", dissect_usb_ms_bulk, proto_usb_ms); } void proto_reg_handoff_usb_ms(void) { dissector_handle_t usb_ms_bulk_handle; dissector_handle_t usb_ms_control_handle; usb_ms_bulk_handle = find_dissector("usbms"); dissector_add_uint("usb.bulk", IF_CLASS_MASS_STORAGE, usb_ms_bulk_handle); usb_ms_control_handle = create_dissector_handle(dissect_usb_ms_control, proto_usb_ms); dissector_add_uint("usb.control", IF_CLASS_MASS_STORAGE, usb_ms_control_handle); heur_dissector_add("usb.bulk", dissect_usb_ms_bulk_heur, "Mass Storage USB bulk endpoint", "ms_usb_bulk", proto_usb_ms, HEURISTIC_ENABLE); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
./CrossVul/dataset_final_sorted/CWE-476/c/good_5108_2
crossvul-cpp_data_bad_4997_0
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* kdc/kdc_util.c - Utility functions for the KDC implementation */ /* * Copyright 1990,1991,2007,2008,2009 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Copyright (c) 2006-2008, Novell, 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 copyright holder's name is not 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. */ #include "k5-int.h" #include "kdc_util.h" #include "extern.h" #include <stdio.h> #include <ctype.h> #include <syslog.h> #include <kadm5/admin.h> #include "adm_proto.h" #include "net-server.h" #include <limits.h> #ifdef KRBCONF_VAGUE_ERRORS const int vague_errors = 1; #else const int vague_errors = 0; #endif static krb5_error_code kdc_rd_ap_req(kdc_realm_t *kdc_active_realm, krb5_ap_req *apreq, krb5_auth_context auth_context, krb5_db_entry **server, krb5_keyblock **tgskey); static krb5_error_code find_server_key(krb5_context, krb5_db_entry *, krb5_enctype, krb5_kvno, krb5_keyblock **, krb5_kvno *); /* * concatenate first two authdata arrays, returning an allocated replacement. * The replacement should be freed with krb5_free_authdata(). */ krb5_error_code concat_authorization_data(krb5_context context, krb5_authdata **first, krb5_authdata **second, krb5_authdata ***output) { register int i, j; register krb5_authdata **ptr, **retdata; /* count up the entries */ i = 0; if (first) for (ptr = first; *ptr; ptr++) i++; if (second) for (ptr = second; *ptr; ptr++) i++; retdata = (krb5_authdata **)malloc((i+1)*sizeof(*retdata)); if (!retdata) return ENOMEM; retdata[i] = 0; /* null-terminated array */ for (i = 0, j = 0, ptr = first; j < 2 ; ptr = second, j++) while (ptr && *ptr) { /* now walk & copy */ retdata[i] = (krb5_authdata *)malloc(sizeof(*retdata[i])); if (!retdata[i]) { krb5_free_authdata(context, retdata); return ENOMEM; } *retdata[i] = **ptr; if (!(retdata[i]->contents = (krb5_octet *)malloc(retdata[i]->length))) { free(retdata[i]); retdata[i] = 0; krb5_free_authdata(context, retdata); return ENOMEM; } memcpy(retdata[i]->contents, (*ptr)->contents, retdata[i]->length); ptr++; i++; } *output = retdata; return 0; } krb5_boolean is_local_principal(kdc_realm_t *kdc_active_realm, krb5_const_principal princ1) { return krb5_realm_compare(kdc_context, princ1, tgs_server); } /* * Returns TRUE if the kerberos principal is the name of a Kerberos ticket * service. */ krb5_boolean krb5_is_tgs_principal(krb5_const_principal principal) { if (krb5_princ_size(kdc_context, principal) != 2) return FALSE; if (data_eq_string(*krb5_princ_component(kdc_context, principal, 0), KRB5_TGS_NAME)) return TRUE; else return FALSE; } /* Returns TRUE if principal is the name of a cross-realm TGS. */ krb5_boolean is_cross_tgs_principal(krb5_const_principal principal) { if (!krb5_is_tgs_principal(principal)) return FALSE; if (!data_eq(*krb5_princ_component(kdc_context, principal, 1), *krb5_princ_realm(kdc_context, principal))) return TRUE; else return FALSE; } /* * given authentication data (provides seed for checksum), verify checksum * for source data. */ static krb5_error_code comp_cksum(krb5_context kcontext, krb5_data *source, krb5_ticket *ticket, krb5_checksum *his_cksum) { krb5_error_code retval; krb5_boolean valid; if (!krb5_c_valid_cksumtype(his_cksum->checksum_type)) return KRB5KDC_ERR_SUMTYPE_NOSUPP; /* must be collision proof */ if (!krb5_c_is_coll_proof_cksum(his_cksum->checksum_type)) return KRB5KRB_AP_ERR_INAPP_CKSUM; /* verify checksum */ if ((retval = krb5_c_verify_checksum(kcontext, ticket->enc_part2->session, KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM, source, his_cksum, &valid))) return(retval); if (!valid) return(KRB5KRB_AP_ERR_BAD_INTEGRITY); return(0); } /* If a header ticket is decrypted, *ticket_out is filled in even on error. */ krb5_error_code kdc_process_tgs_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, const krb5_fulladdr *from, krb5_data *pkt, krb5_ticket **ticket_out, krb5_db_entry **krbtgt_ptr, krb5_keyblock **tgskey, krb5_keyblock **subkey, krb5_pa_data **pa_tgs_req) { krb5_pa_data * tmppa; krb5_ap_req * apreq; krb5_error_code retval; krb5_authdata **authdata = NULL; krb5_data scratch1; krb5_data * scratch = NULL; krb5_boolean foreign_server = FALSE; krb5_auth_context auth_context = NULL; krb5_authenticator * authenticator = NULL; krb5_checksum * his_cksum = NULL; krb5_db_entry * krbtgt = NULL; krb5_ticket * ticket; *ticket_out = NULL; *krbtgt_ptr = NULL; *tgskey = NULL; tmppa = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_AP_REQ); if (!tmppa) return KRB5KDC_ERR_PADATA_TYPE_NOSUPP; scratch1.length = tmppa->length; scratch1.data = (char *)tmppa->contents; if ((retval = decode_krb5_ap_req(&scratch1, &apreq))) return retval; ticket = apreq->ticket; if (isflagset(apreq->ap_options, AP_OPTS_USE_SESSION_KEY) || isflagset(apreq->ap_options, AP_OPTS_MUTUAL_REQUIRED)) { krb5_klog_syslog(LOG_INFO, _("TGS_REQ: SESSION KEY or MUTUAL")); retval = KRB5KDC_ERR_POLICY; goto cleanup; } /* If the "server" principal in the ticket is not something in the local realm, then we must refuse to service the request if the client claims to be from the local realm. If we don't do this, then some other realm's nasty KDC can claim to be authenticating a client from our realm, and we'll give out tickets concurring with it! we set a flag here for checking below. */ foreign_server = !is_local_principal(kdc_active_realm, apreq->ticket->server); if ((retval = krb5_auth_con_init(kdc_context, &auth_context))) goto cleanup; /* Don't use a replay cache. */ if ((retval = krb5_auth_con_setflags(kdc_context, auth_context, 0))) goto cleanup; if ((retval = krb5_auth_con_setaddrs(kdc_context, auth_context, NULL, from->address)) ) goto cleanup_auth_context; retval = kdc_rd_ap_req(kdc_active_realm, apreq, auth_context, &krbtgt, tgskey); if (retval) goto cleanup_auth_context; /* "invalid flag" tickets can must be used to validate */ if (isflagset(ticket->enc_part2->flags, TKT_FLG_INVALID) && !isflagset(request->kdc_options, KDC_OPT_VALIDATE)) { retval = KRB5KRB_AP_ERR_TKT_INVALID; goto cleanup_auth_context; } if ((retval = krb5_auth_con_getrecvsubkey(kdc_context, auth_context, subkey))) goto cleanup_auth_context; if ((retval = krb5_auth_con_getauthenticator(kdc_context, auth_context, &authenticator))) goto cleanup_auth_context; retval = krb5_find_authdata(kdc_context, ticket->enc_part2->authorization_data, authenticator->authorization_data, KRB5_AUTHDATA_FX_ARMOR, &authdata); if (retval != 0) goto cleanup_authenticator; if (authdata&& authdata[0]) { k5_setmsg(kdc_context, KRB5KDC_ERR_POLICY, "ticket valid only as FAST armor"); retval = KRB5KDC_ERR_POLICY; krb5_free_authdata(kdc_context, authdata); goto cleanup_authenticator; } krb5_free_authdata(kdc_context, authdata); /* Check for a checksum */ if (!(his_cksum = authenticator->checksum)) { retval = KRB5KRB_AP_ERR_INAPP_CKSUM; goto cleanup_authenticator; } /* make sure the client is of proper lineage (see above) */ if (foreign_server && !krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER)) { if (is_local_principal(kdc_active_realm, ticket->enc_part2->client)) { /* someone in a foreign realm claiming to be local */ krb5_klog_syslog(LOG_INFO, _("PROCESS_TGS: failed lineage check")); retval = KRB5KDC_ERR_POLICY; goto cleanup_authenticator; } } /* * Check application checksum vs. tgs request * * We try checksumming the req-body two different ways: first we * try reaching into the raw asn.1 stream (if available), and * checksum that directly; if that fails, then we try encoding * using our local asn.1 library. */ if (pkt && (fetch_asn1_field((unsigned char *) pkt->data, 1, 4, &scratch1) >= 0)) { if (comp_cksum(kdc_context, &scratch1, ticket, his_cksum)) { if (!(retval = encode_krb5_kdc_req_body(request, &scratch))) retval = comp_cksum(kdc_context, scratch, ticket, his_cksum); krb5_free_data(kdc_context, scratch); if (retval) goto cleanup_authenticator; } } *pa_tgs_req = tmppa; *krbtgt_ptr = krbtgt; krbtgt = NULL; cleanup_authenticator: krb5_free_authenticator(kdc_context, authenticator); cleanup_auth_context: krb5_auth_con_free(kdc_context, auth_context); cleanup: if (retval != 0) { krb5_free_keyblock(kdc_context, *tgskey); *tgskey = NULL; } if (apreq->ticket->enc_part2 != NULL) { /* Steal the decrypted ticket pointer, even on error. */ *ticket_out = apreq->ticket; apreq->ticket = NULL; } krb5_free_ap_req(kdc_context, apreq); krb5_db_free_principal(kdc_context, krbtgt); return retval; } /* * This is a KDC wrapper around krb5_rd_req_decoded_anyflag(). * * We can't depend on KDB-as-keytab for handling the AP-REQ here for * optimization reasons: we want to minimize the number of KDB lookups. We'll * need the KDB entry for the TGS principal, and the TGS key used to decrypt * the TGT, elsewhere in the TGS code. * * This function also implements key rollover support for kvno 0 cross-realm * TGTs issued by AD. */ static krb5_error_code kdc_rd_ap_req(kdc_realm_t *kdc_active_realm, krb5_ap_req *apreq, krb5_auth_context auth_context, krb5_db_entry **server, krb5_keyblock **tgskey) { krb5_error_code retval; krb5_enctype search_enctype = apreq->ticket->enc_part.enctype; krb5_boolean match_enctype = 1; krb5_kvno kvno; size_t tries = 3; /* * When we issue tickets we use the first key in the principals' highest * kvno keyset. For non-cross-realm krbtgt principals we want to only * allow the use of the first key of the principal's keyset that matches * the given kvno. */ if (krb5_is_tgs_principal(apreq->ticket->server) && !is_cross_tgs_principal(apreq->ticket->server)) { search_enctype = -1; match_enctype = 0; } retval = kdc_get_server_key(kdc_context, apreq->ticket, KRB5_KDB_FLAG_ALIAS_OK, match_enctype, server, NULL, NULL); if (retval) return retval; *tgskey = NULL; kvno = apreq->ticket->enc_part.kvno; do { krb5_free_keyblock(kdc_context, *tgskey); retval = find_server_key(kdc_context, *server, search_enctype, kvno, tgskey, &kvno); if (retval) continue; /* Make the TGS key available to krb5_rd_req_decoded_anyflag() */ retval = krb5_auth_con_setuseruserkey(kdc_context, auth_context, *tgskey); if (retval) return retval; retval = krb5_rd_req_decoded_anyflag(kdc_context, &auth_context, apreq, apreq->ticket->server, kdc_active_realm->realm_keytab, NULL, NULL); /* If the ticket was decrypted, don't try any more keys. */ if (apreq->ticket->enc_part2 != NULL) break; } while (retval && apreq->ticket->enc_part.kvno == 0 && kvno-- > 1 && --tries > 0); return retval; } /* * The KDC should take the keytab associated with the realm and pass * that to the krb5_rd_req_decoded_anyflag(), but we still need to use * the service (TGS, here) key elsewhere. This approach is faster than * the KDB keytab approach too. * * This is also used by do_tgs_req() for u2u auth. */ krb5_error_code kdc_get_server_key(krb5_context context, krb5_ticket *ticket, unsigned int flags, krb5_boolean match_enctype, krb5_db_entry **server_ptr, krb5_keyblock **key, krb5_kvno *kvno) { krb5_error_code retval; krb5_db_entry * server = NULL; krb5_enctype search_enctype = -1; krb5_kvno search_kvno = -1; if (match_enctype) search_enctype = ticket->enc_part.enctype; if (ticket->enc_part.kvno) search_kvno = ticket->enc_part.kvno; *server_ptr = NULL; retval = krb5_db_get_principal(context, ticket->server, flags, &server); if (retval == KRB5_KDB_NOENTRY) { char *sname; if (!krb5_unparse_name(context, ticket->server, &sname)) { limit_string(sname); krb5_klog_syslog(LOG_ERR, _("TGS_REQ: UNKNOWN SERVER: server='%s'"), sname); free(sname); } return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } else if (retval) return retval; if (server->attributes & KRB5_KDB_DISALLOW_SVR || server->attributes & KRB5_KDB_DISALLOW_ALL_TIX) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto errout; } if (key) { retval = find_server_key(context, server, search_enctype, search_kvno, key, kvno); if (retval) goto errout; } *server_ptr = server; server = NULL; return 0; errout: krb5_db_free_principal(context, server); return retval; } /* * A utility function to get the right key from a KDB entry. Used in handling * of kvno 0 TGTs, for example. */ static krb5_error_code find_server_key(krb5_context context, krb5_db_entry *server, krb5_enctype enctype, krb5_kvno kvno, krb5_keyblock **key_out, krb5_kvno *kvno_out) { krb5_error_code retval; krb5_key_data * server_key; krb5_keyblock * key; *key_out = NULL; retval = krb5_dbe_find_enctype(context, server, enctype, -1, kvno ? (krb5_int32)kvno : -1, &server_key); if (retval) return retval; if (!server_key) return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; if ((key = (krb5_keyblock *)malloc(sizeof *key)) == NULL) return ENOMEM; retval = krb5_dbe_decrypt_key_data(context, NULL, server_key, key, NULL); if (retval) goto errout; if (enctype != -1) { krb5_boolean similar; retval = krb5_c_enctype_compare(context, enctype, key->enctype, &similar); if (retval) goto errout; if (!similar) { retval = KRB5_KDB_NO_PERMITTED_KEY; goto errout; } key->enctype = enctype; } *key_out = key; key = NULL; if (kvno_out) *kvno_out = server_key->key_data_kvno; errout: krb5_free_keyblock(context, key); return retval; } /* * If candidate is the local TGT for realm, set *alias_out to candidate and * *storage_out to NULL. Otherwise, load the local TGT into *storage_out and * set *alias_out to *storage_out. * * In the future we might generalize this to a small per-request principal * cache. For now, it saves a load operation in the common case where the AS * server or TGS header ticket server is the local TGT. */ krb5_error_code get_local_tgt(krb5_context context, const krb5_data *realm, krb5_db_entry *candidate, krb5_db_entry **alias_out, krb5_db_entry **storage_out) { krb5_error_code ret; krb5_principal princ; krb5_db_entry *tgt; *alias_out = NULL; *storage_out = NULL; ret = krb5_build_principal_ext(context, &princ, realm->length, realm->data, KRB5_TGS_NAME_SIZE, KRB5_TGS_NAME, realm->length, realm->data, 0); if (ret) return ret; if (!krb5_principal_compare(context, candidate->princ, princ)) { ret = krb5_db_get_principal(context, princ, 0, &tgt); if (!ret) *storage_out = *alias_out = tgt; } else { *alias_out = candidate; } krb5_free_principal(context, princ); return ret; } /* This probably wants to be updated if you support last_req stuff */ static krb5_last_req_entry nolrentry = { KV5M_LAST_REQ_ENTRY, KRB5_LRQ_NONE, 0 }; static krb5_last_req_entry *nolrarray[] = { &nolrentry, 0 }; krb5_error_code fetch_last_req_info(krb5_db_entry *dbentry, krb5_last_req_entry ***lrentry) { *lrentry = nolrarray; return 0; } /* XXX! This is a temporary place-holder */ krb5_error_code check_hot_list(krb5_ticket *ticket) { return 0; } /* Convert an API error code to a protocol error code. */ int errcode_to_protocol(krb5_error_code code) { int protcode; protcode = code - ERROR_TABLE_BASE_krb5; return (protcode >= 0 && protcode <= 128) ? protcode : KRB_ERR_GENERIC; } /* Return -1 if the AS or TGS request is disallowed due to KDC policy on * anonymous tickets. */ int check_anon(kdc_realm_t *kdc_active_realm, krb5_principal client, krb5_principal server) { /* If restrict_anon is set, reject requests from anonymous to principals * other than the local TGT. */ if (kdc_active_realm->realm_restrict_anon && krb5_principal_compare_any_realm(kdc_context, client, krb5_anonymous_principal()) && !krb5_principal_compare(kdc_context, server, tgs_server)) return -1; return 0; } /* * Routines that validate a AS request; checks a lot of things. :-) * * Returns a Kerberos protocol error number, which is _not_ the same * as a com_err error number! */ #define AS_INVALID_OPTIONS (KDC_OPT_FORWARDED | KDC_OPT_PROXY | \ KDC_OPT_VALIDATE | KDC_OPT_RENEW | \ KDC_OPT_ENC_TKT_IN_SKEY | KDC_OPT_CNAME_IN_ADDL_TKT) int validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = "CLIENT EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "CLIENT KEY EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = "SERVICE EXPIRED"; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "REQUIRED PWCHANGE"; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = "POSTDATE NOT ALLOWED"; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = "PROXIABLE NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "CLIENT LOCKED OUT"; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "SERVICE LOCKED OUT"; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = "SERVICE NOT ALLOWED"; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, request->client, request->server) != 0) { *status = "ANONYMOUS NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; } int validate_forwardable(krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status) { *status = NULL; if (isflagset(request->kdc_options, KDC_OPT_FORWARDABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_FORWARDABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_FORWARDABLE))) { *status = "FORWARDABLE NOT ALLOWED"; return(KDC_ERR_POLICY); } else return 0; } /* Return KRB5KDC_ERR_POLICY if indicators does not contain the required auth * indicators for server, ENOMEM on allocation error, 0 otherwise. */ krb5_error_code check_indicators(krb5_context context, krb5_db_entry *server, krb5_data *const *indicators) { krb5_error_code ret; char *str = NULL, *copy = NULL, *save, *ind; ret = krb5_dbe_get_string(context, server, KRB5_KDB_SK_REQUIRE_AUTH, &str); if (ret || str == NULL) goto cleanup; copy = strdup(str); if (copy == NULL) { ret = ENOMEM; goto cleanup; } /* Look for any of the space-separated strings in indicators. */ ind = strtok_r(copy, " ", &save); while (ind != NULL) { if (authind_contains(indicators, ind)) goto cleanup; ind = strtok_r(NULL, " ", &save); } ret = KRB5KDC_ERR_POLICY; k5_setmsg(context, ret, _("Required auth indicators not present in ticket: %s"), str); cleanup: krb5_dbe_free_string(context, str); free(copy); return ret; } #define ASN1_ID_CLASS (0xc0) #define ASN1_ID_TYPE (0x20) #define ASN1_ID_TAG (0x1f) #define ASN1_CLASS_UNIV (0) #define ASN1_CLASS_APP (1) #define ASN1_CLASS_CTX (2) #define ASN1_CLASS_PRIV (3) #define asn1_id_constructed(x) (x & ASN1_ID_TYPE) #define asn1_id_primitive(x) (!asn1_id_constructed(x)) #define asn1_id_class(x) ((x & ASN1_ID_CLASS) >> 6) #define asn1_id_tag(x) (x & ASN1_ID_TAG) /* * asn1length - return encoded length of value. * * passed a pointer into the asn.1 stream, which is updated * to point right after the length bits. * * returns -1 on failure. */ static int asn1length(unsigned char **astream) { int length; /* resulting length */ int sublen; /* sublengths */ int blen; /* bytes of length */ unsigned char *p; /* substring searching */ if (**astream & 0x80) { blen = **astream & 0x7f; if (blen > 3) { return(-1); } for (++*astream, length = 0; blen; ++*astream, blen--) { length = (length << 8) | **astream; } if (length == 0) { /* indefinite length, figure out by hand */ p = *astream; p++; while (1) { /* compute value length. */ if ((sublen = asn1length(&p)) < 0) { return(-1); } p += sublen; /* check for termination */ if ((!*p++) && (!*p)) { p++; break; } } length = p - *astream; } } else { length = **astream; ++*astream; } return(length); } /* * fetch_asn1_field - return raw asn.1 stream of subfield. * * this routine is passed a context-dependent tag number and "level" and returns * the size and length of the corresponding level subfield. * * levels and are numbered starting from 1. * * returns 0 on success, -1 otherwise. */ int fetch_asn1_field(unsigned char *astream, unsigned int level, unsigned int field, krb5_data *data) { unsigned char *estream; /* end of stream */ int classes; /* # classes seen so far this level */ unsigned int levels = 0; /* levels seen so far */ int lastlevel = 1000; /* last level seen */ int length; /* various lengths */ int tag; /* tag number */ unsigned char savelen; /* saved length of our field */ classes = -1; /* we assume that the first identifier/length will tell us how long the entire stream is. */ astream++; estream = astream; if ((length = asn1length(&astream)) < 0) { return(-1); } estream += length; /* search down the stream, checking identifiers. we process identifiers until we hit the "level" we want, and then process that level for our subfield, always making sure we don't go off the end of the stream. */ while (astream < estream) { if (!asn1_id_constructed(*astream)) { return(-1); } if (asn1_id_class(*astream) == ASN1_CLASS_CTX) { if ((tag = (int)asn1_id_tag(*astream)) <= lastlevel) { levels++; classes = -1; } lastlevel = tag; if (levels == level) { /* in our context-dependent class, is this the one we're looking for ? */ if (tag == (int)field) { /* return length and data */ astream++; savelen = *astream; if ((length = asn1length(&astream)) < 0) { return(-1); } data->length = length; /* if the field length is indefinite, we will have to subtract two (terminating octets) from the length returned since we don't want to pass any info from the "wrapper" back. asn1length will always return the *total* length of the field, not just what's contained in it */ if ((savelen & 0xff) == 0x80) { data->length -=2 ; } data->data = (char *)astream; return(0); } else if (tag <= classes) { /* we've seen this class before, something must be wrong */ return(-1); } else { classes = tag; } } } /* if we're not on our level yet, process this value. otherwise skip over it */ astream++; if ((length = asn1length(&astream)) < 0) { return(-1); } if (levels == level) { astream += length; } } return(-1); } /* Return true if we believe server can support enctype as a session key. */ static krb5_boolean dbentry_supports_enctype(kdc_realm_t *kdc_active_realm, krb5_db_entry *server, krb5_enctype enctype) { krb5_error_code retval; krb5_key_data *datap; char *etypes_str = NULL; krb5_enctype default_enctypes[1] = { 0 }; krb5_enctype *etypes = NULL; krb5_boolean in_list; /* Look up the supported session key enctypes list in the KDB. */ retval = krb5_dbe_get_string(kdc_context, server, KRB5_KDB_SK_SESSION_ENCTYPES, &etypes_str); if (retval == 0 && etypes_str != NULL && *etypes_str != '\0') { /* Pass a fake profile key for tracing of unrecognized tokens. */ retval = krb5int_parse_enctype_list(kdc_context, "KDB-session_etypes", etypes_str, default_enctypes, &etypes); if (retval == 0 && etypes != NULL && etypes[0]) { in_list = k5_etypes_contains(etypes, enctype); free(etypes_str); free(etypes); return in_list; } /* Fall through on error or empty list */ } free(etypes_str); free(etypes); /* If configured to, assume every server without a session_enctypes * attribute supports DES_CBC_CRC. */ if (kdc_active_realm->realm_assume_des_crc_sess && enctype == ENCTYPE_DES_CBC_CRC) return TRUE; /* Due to an ancient interop problem, assume nothing supports des-cbc-md5 * unless there's a session_enctypes explicitly saying that it does. */ if (enctype == ENCTYPE_DES_CBC_MD5) return FALSE; /* Assume the server supports any enctype it has a long-term key for. */ return !krb5_dbe_find_enctype(kdc_context, server, enctype, -1, 0, &datap); } /* * This function returns the keytype which should be selected for the * session key. It is based on the ordered list which the user * requested, and what the KDC and the application server can support. */ krb5_enctype select_session_keytype(kdc_realm_t *kdc_active_realm, krb5_db_entry *server, int nktypes, krb5_enctype *ktype) { int i; for (i = 0; i < nktypes; i++) { if (!krb5_c_valid_enctype(ktype[i])) continue; if (!krb5_is_permitted_enctype(kdc_context, ktype[i])) continue; if (dbentry_supports_enctype(kdc_active_realm, server, ktype[i])) return ktype[i]; } return 0; } /* * Limit strings to a "reasonable" length to prevent crowding out of * other useful information in the log entry */ #define NAME_LENGTH_LIMIT 128 void limit_string(char *name) { int i; if (!name) return; if (strlen(name) < NAME_LENGTH_LIMIT) return; i = NAME_LENGTH_LIMIT-4; name[i++] = '.'; name[i++] = '.'; name[i++] = '.'; name[i] = '\0'; return; } /* * L10_2 = log10(2**x), rounded up; log10(2) ~= 0.301. */ #define L10_2(x) ((int)(((x * 301) + 999) / 1000)) /* * Max length of sprintf("%ld") for an int of type T; includes leading * minus sign and terminating NUL. */ #define D_LEN(t) (L10_2(sizeof(t) * CHAR_BIT) + 2) void ktypes2str(char *s, size_t len, int nktypes, krb5_enctype *ktype) { int i; char stmp[D_LEN(krb5_enctype) + 1]; char *p; if (nktypes < 0 || len < (sizeof(" etypes {...}") + D_LEN(int))) { *s = '\0'; return; } snprintf(s, len, "%d etypes {", nktypes); for (i = 0; i < nktypes; i++) { snprintf(stmp, sizeof(stmp), "%s%ld", i ? " " : "", (long)ktype[i]); if (strlen(s) + strlen(stmp) + sizeof("}") > len) break; strlcat(s, stmp, len); } if (i < nktypes) { /* * We broke out of the loop. Try to truncate the list. */ p = s + strlen(s); while (p - s + sizeof("...}") > len) { while (p > s && *p != ' ' && *p != '{') *p-- = '\0'; if (p > s && *p == ' ') { *p-- = '\0'; continue; } } strlcat(s, "...", len); } strlcat(s, "}", len); return; } void rep_etypes2str(char *s, size_t len, krb5_kdc_rep *rep) { char stmp[sizeof("ses=") + D_LEN(krb5_enctype)]; if (len < (3 * D_LEN(krb5_enctype) + sizeof("etypes {rep= tkt= ses=}"))) { *s = '\0'; return; } snprintf(s, len, "etypes {rep=%ld", (long)rep->enc_part.enctype); if (rep->ticket != NULL) { snprintf(stmp, sizeof(stmp), " tkt=%ld", (long)rep->ticket->enc_part.enctype); strlcat(s, stmp, len); } if (rep->ticket != NULL && rep->ticket->enc_part2 != NULL && rep->ticket->enc_part2->session != NULL) { snprintf(stmp, sizeof(stmp), " ses=%ld", (long)rep->ticket->enc_part2->session->enctype); strlcat(s, stmp, len); } strlcat(s, "}", len); return; } static krb5_error_code verify_for_user_checksum(krb5_context context, krb5_keyblock *key, krb5_pa_for_user *req) { krb5_error_code code; int i; krb5_int32 name_type; char *p; krb5_data data; krb5_boolean valid = FALSE; if (!krb5_c_is_keyed_cksum(req->cksum.checksum_type)) { return KRB5KRB_AP_ERR_INAPP_CKSUM; } /* * Checksum is over name type and string components of * client principal name and auth_package. */ data.length = 4; for (i = 0; i < krb5_princ_size(context, req->user); i++) { data.length += krb5_princ_component(context, req->user, i)->length; } data.length += krb5_princ_realm(context, req->user)->length; data.length += req->auth_package.length; p = data.data = malloc(data.length); if (data.data == NULL) { return ENOMEM; } name_type = krb5_princ_type(context, req->user); p[0] = (name_type >> 0 ) & 0xFF; p[1] = (name_type >> 8 ) & 0xFF; p[2] = (name_type >> 16) & 0xFF; p[3] = (name_type >> 24) & 0xFF; p += 4; for (i = 0; i < krb5_princ_size(context, req->user); i++) { if (krb5_princ_component(context, req->user, i)->length > 0) { memcpy(p, krb5_princ_component(context, req->user, i)->data, krb5_princ_component(context, req->user, i)->length); } p += krb5_princ_component(context, req->user, i)->length; } if (krb5_princ_realm(context, req->user)->length > 0) { memcpy(p, krb5_princ_realm(context, req->user)->data, krb5_princ_realm(context, req->user)->length); } p += krb5_princ_realm(context, req->user)->length; if (req->auth_package.length > 0) memcpy(p, req->auth_package.data, req->auth_package.length); p += req->auth_package.length; code = krb5_c_verify_checksum(context, key, KRB5_KEYUSAGE_APP_DATA_CKSUM, &data, &req->cksum, &valid); if (code == 0 && valid == FALSE) code = KRB5KRB_AP_ERR_MODIFIED; free(data.data); return code; } /* * Legacy protocol transition (Windows 2003 and above) */ static krb5_error_code kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) return code; code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; } static krb5_error_code verify_s4u_x509_user_checksum(krb5_context context, krb5_keyblock *key, krb5_data *req_data, krb5_int32 kdc_req_nonce, krb5_pa_s4u_x509_user *req) { krb5_error_code code; krb5_data scratch; krb5_boolean valid = FALSE; if (enctype_requires_etype_info_2(key->enctype) && !krb5_c_is_keyed_cksum(req->cksum.checksum_type)) return KRB5KRB_AP_ERR_INAPP_CKSUM; if (req->user_id.nonce != kdc_req_nonce) return KRB5KRB_AP_ERR_MODIFIED; /* * Verify checksum over the encoded userid. If that fails, * re-encode, and verify that. This is similar to the * behaviour in kdc_process_tgs_req(). */ if (fetch_asn1_field((unsigned char *)req_data->data, 1, 0, &scratch) < 0) return ASN1_PARSE_ERROR; code = krb5_c_verify_checksum(context, key, KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST, &scratch, &req->cksum, &valid); if (code != 0) return code; if (valid == FALSE) { krb5_data *data; code = encode_krb5_s4u_userid(&req->user_id, &data); if (code != 0) return code; code = krb5_c_verify_checksum(context, key, KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST, data, &req->cksum, &valid); krb5_free_data(context, data); if (code != 0) return code; } return valid ? 0 : KRB5KRB_AP_ERR_MODIFIED; } /* * New protocol transition request (Windows 2008 and above) */ static krb5_error_code kdc_process_s4u_x509_user(krb5_context context, krb5_kdc_req *request, krb5_pa_data *pa_data, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user); if (code) return code; code = verify_s4u_x509_user_checksum(context, tgs_subkey ? tgs_subkey : tgs_session, &req_data, request->nonce, *s4u_x509_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_s4u_x509_user(context, *s4u_x509_user); *s4u_x509_user = NULL; return code; } if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 || (*s4u_x509_user)->user_id.subject_cert.length != 0) { *status = "INVALID_S4U2SELF_REQUEST"; krb5_free_pa_s4u_x509_user(context, *s4u_x509_user); *s4u_x509_user = NULL; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } return 0; } krb5_error_code kdc_make_s4u2self_rep(krb5_context context, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user *req_s4u_user, krb5_kdc_rep *reply, krb5_enc_kdc_rep_part *reply_encpart) { krb5_error_code code; krb5_data *data = NULL; krb5_pa_s4u_x509_user rep_s4u_user; krb5_pa_data padata; krb5_enctype enctype; krb5_keyusage usage; memset(&rep_s4u_user, 0, sizeof(rep_s4u_user)); rep_s4u_user.user_id.nonce = req_s4u_user->user_id.nonce; rep_s4u_user.user_id.user = req_s4u_user->user_id.user; rep_s4u_user.user_id.options = req_s4u_user->user_id.options & KRB5_S4U_OPTS_USE_REPLY_KEY_USAGE; code = encode_krb5_s4u_userid(&rep_s4u_user.user_id, &data); if (code != 0) goto cleanup; if (req_s4u_user->user_id.options & KRB5_S4U_OPTS_USE_REPLY_KEY_USAGE) usage = KRB5_KEYUSAGE_PA_S4U_X509_USER_REPLY; else usage = KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST; code = krb5_c_make_checksum(context, req_s4u_user->cksum.checksum_type, tgs_subkey != NULL ? tgs_subkey : tgs_session, usage, data, &rep_s4u_user.cksum); if (code != 0) goto cleanup; krb5_free_data(context, data); data = NULL; code = encode_krb5_pa_s4u_x509_user(&rep_s4u_user, &data); if (code != 0) goto cleanup; padata.magic = KV5M_PA_DATA; padata.pa_type = KRB5_PADATA_S4U_X509_USER; padata.length = data->length; padata.contents = (krb5_octet *)data->data; code = add_pa_data_element(context, &padata, &reply->padata, FALSE); if (code != 0) goto cleanup; free(data); data = NULL; if (tgs_subkey != NULL) enctype = tgs_subkey->enctype; else enctype = tgs_session->enctype; /* * Owing to a bug in Windows, unkeyed checksums were used for older * enctypes, including rc4-hmac. A forthcoming workaround for this * includes the checksum bytes in the encrypted padata. */ if ((req_s4u_user->user_id.options & KRB5_S4U_OPTS_USE_REPLY_KEY_USAGE) && enctype_requires_etype_info_2(enctype) == FALSE) { padata.length = req_s4u_user->cksum.length + rep_s4u_user.cksum.length; padata.contents = malloc(padata.length); if (padata.contents == NULL) { code = ENOMEM; goto cleanup; } memcpy(padata.contents, req_s4u_user->cksum.contents, req_s4u_user->cksum.length); memcpy(&padata.contents[req_s4u_user->cksum.length], rep_s4u_user.cksum.contents, rep_s4u_user.cksum.length); code = add_pa_data_element(context,&padata, &reply_encpart->enc_padata, FALSE); if (code != 0) { free(padata.contents); goto cleanup; } } cleanup: if (rep_s4u_user.cksum.contents != NULL) krb5_free_checksum_contents(context, &rep_s4u_user.cksum); krb5_free_data(context, data); return code; } /* * Protocol transition (S4U2Self) */ krb5_error_code kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_const_principal client_princ, const krb5_db_entry *server, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_timestamp kdc_time, krb5_pa_s4u_x509_user **s4u_x509_user, krb5_db_entry **princ_ptr, const char **status) { krb5_error_code code; krb5_pa_data *pa_data; int flags; krb5_db_entry *princ; *princ_ptr = NULL; pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_S4U_X509_USER); if (pa_data != NULL) { code = kdc_process_s4u_x509_user(kdc_context, request, pa_data, tgs_subkey, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else { pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER); if (pa_data != NULL) { code = kdc_process_for_user(kdc_active_realm, pa_data, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else return 0; } /* * We need to compare the client name in the TGT with the requested * server name. Supporting server name aliases without assuming a * global name service makes this difficult to do. * * The comparison below handles the following cases (note that the * term "principal name" below excludes the realm). * * (1) The requested service is a host-based service with two name * components, in which case we assume the principal name to * contain sufficient qualifying information. The realm is * ignored for the purpose of comparison. * * (2) The requested service name is an enterprise principal name: * the service principal name is compared with the unparsed * form of the client name (including its realm). * * (3) The requested service is some other name type: an exact * match is required. * * An alternative would be to look up the server once again with * FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact * match between the returned name and client_princ. However, this * assumes that the client set FLAG_CANONICALIZE when requesting * the TGT and that we have a global name service. */ flags = 0; switch (krb5_princ_type(kdc_context, request->server)) { case KRB5_NT_SRV_HST: /* (1) */ if (krb5_princ_size(kdc_context, request->server) == 2) flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM; break; case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */ flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE; break; default: /* (3) */ break; } if (!krb5_principal_compare_flags(kdc_context, request->server, client_princ, flags)) { *status = "INVALID_S4U2SELF_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */ } /* * Protocol transition is mutually exclusive with renew/forward/etc * as well as user-to-user and constrained delegation. This check * is also made in validate_as_request(). * * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KRB5KDC_ERR_BADOPTION; } /* * Do not attempt to lookup principals in foreign realms. */ if (is_local_principal(kdc_active_realm, (*s4u_x509_user)->user_id.user)) { krb5_db_entry no_server; krb5_pa_data **e_data = NULL; code = krb5_db_get_principal(kdc_context, (*s4u_x509_user)->user_id.user, KRB5_KDB_FLAG_INCLUDE_PAC, &princ); if (code == KRB5_KDB_NOENTRY) { *status = "UNKNOWN_S4U2SELF_PRINCIPAL"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } else if (code) { *status = "LOOKING_UP_S4U2SELF_PRINCIPAL"; return code; /* caller can free for_user */ } memset(&no_server, 0, sizeof(no_server)); code = validate_as_request(kdc_active_realm, request, *princ, no_server, kdc_time, status, &e_data); if (code) { krb5_db_free_principal(kdc_context, princ); krb5_free_pa_data(kdc_context, e_data); return code; } *princ_ptr = princ; } return 0; } static krb5_error_code check_allowed_to_delegate_to(krb5_context context, krb5_const_principal client, const krb5_db_entry *server, krb5_const_principal proxy) { /* Can't get a TGT (otherwise it would be unconstrained delegation) */ if (krb5_is_tgs_principal(proxy)) return KRB5KDC_ERR_POLICY; /* Must be in same realm */ if (!krb5_realm_compare(context, server->princ, proxy)) return KRB5KDC_ERR_POLICY; return krb5_db_check_allowed_to_delegate(context, client, server, proxy); } krb5_error_code kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, const krb5_enc_tkt_part *t2enc, const krb5_db_entry *server, krb5_const_principal server_princ, krb5_const_principal proxy_princ, const char **status) { krb5_error_code errcode; /* * Constrained delegation is mutually exclusive with renew/forward/etc. * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) { return KRB5KDC_ERR_BADOPTION; } /* Ensure that evidence ticket server matches TGT client */ if (!krb5_principal_compare(kdc_context, server->princ, /* after canon */ server_princ)) { return KRB5KDC_ERR_SERVER_NOMATCH; } if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) { *status = "EVIDENCE_TKT_NOT_FORWARDABLE"; return KRB5_TKT_NOT_FORWARDABLE; } /* Backend policy check */ errcode = check_allowed_to_delegate_to(kdc_context, t2enc->client, server, proxy_princ); if (errcode) { *status = "NOT_ALLOWED_TO_DELEGATE"; return errcode; } return 0; } krb5_error_code kdc_check_transited_list(kdc_realm_t *kdc_active_realm, const krb5_data *trans, const krb5_data *realm1, const krb5_data *realm2) { krb5_error_code code; /* Check against the KDB module. Treat this answer as authoritative if the * method is supported and doesn't explicitly pass control. */ code = krb5_db_check_transited_realms(kdc_context, trans, realm1, realm2); if (code != KRB5_PLUGIN_OP_NOTSUPP && code != KRB5_PLUGIN_NO_HANDLE) return code; /* Check using krb5.conf [capaths] or hierarchical relationships. */ return krb5_check_transited_list(kdc_context, trans, realm1, realm2); } krb5_error_code validate_transit_path(krb5_context context, krb5_const_principal client, krb5_db_entry *server, krb5_db_entry *header_srv) { /* Incoming */ if (isflagset(server->attributes, KRB5_KDB_XREALM_NON_TRANSITIVE)) { return KRB5KDC_ERR_PATH_NOT_ACCEPTED; } /* Outgoing */ if (isflagset(header_srv->attributes, KRB5_KDB_XREALM_NON_TRANSITIVE) && (!krb5_principal_compare(context, server->princ, header_srv->princ) || !krb5_realm_compare(context, client, header_srv->princ))) { return KRB5KDC_ERR_PATH_NOT_ACCEPTED; } return 0; } krb5_boolean enctype_requires_etype_info_2(krb5_enctype enctype) { switch(enctype) { case ENCTYPE_DES_CBC_CRC: case ENCTYPE_DES_CBC_MD4: case ENCTYPE_DES_CBC_MD5: case ENCTYPE_DES3_CBC_SHA1: case ENCTYPE_DES3_CBC_RAW: case ENCTYPE_ARCFOUR_HMAC: case ENCTYPE_ARCFOUR_HMAC_EXP : return 0; default: return krb5_c_valid_enctype(enctype); } } /* XXX where are the generic helper routines for this? */ krb5_error_code add_pa_data_element(krb5_context context, krb5_pa_data *padata, krb5_pa_data ***inout_padata, krb5_boolean copy) { int i; krb5_pa_data **p; if (*inout_padata != NULL) { for (i = 0; (*inout_padata)[i] != NULL; i++) ; } else i = 0; p = realloc(*inout_padata, (i + 2) * sizeof(krb5_pa_data *)); if (p == NULL) return ENOMEM; *inout_padata = p; p[i] = (krb5_pa_data *)malloc(sizeof(krb5_pa_data)); if (p[i] == NULL) return ENOMEM; *(p[i]) = *padata; p[i + 1] = NULL; if (copy) { p[i]->contents = (krb5_octet *)malloc(padata->length); if (p[i]->contents == NULL) { free(p[i]); p[i] = NULL; return ENOMEM; } memcpy(p[i]->contents, padata->contents, padata->length); } return 0; } void kdc_get_ticket_endtime(kdc_realm_t *kdc_active_realm, krb5_timestamp starttime, krb5_timestamp endtime, krb5_timestamp till, krb5_db_entry *client, krb5_db_entry *server, krb5_timestamp *out_endtime) { krb5_timestamp until, life; if (till == 0) till = kdc_infinity; until = min(till, endtime); life = until - starttime; if (client != NULL && client->max_life != 0) life = min(life, client->max_life); if (server->max_life != 0) life = min(life, server->max_life); if (kdc_active_realm->realm_maxlife != 0) life = min(life, kdc_active_realm->realm_maxlife); *out_endtime = starttime + life; } /* * Set tkt->renew_till to the requested renewable lifetime as modified by * policy. Set the TKT_FLG_RENEWABLE flag if we set a nonzero renew_till. * client and tgt may be NULL. */ void kdc_get_ticket_renewtime(kdc_realm_t *realm, krb5_kdc_req *request, krb5_enc_tkt_part *tgt, krb5_db_entry *client, krb5_db_entry *server, krb5_enc_tkt_part *tkt) { krb5_timestamp rtime, max_rlife; tkt->times.renew_till = 0; /* Don't issue renewable tickets if the client or server don't allow it, * or if this is a TGS request and the TGT isn't renewable. */ if (server->attributes & KRB5_KDB_DISALLOW_RENEWABLE) return; if (client != NULL && (client->attributes & KRB5_KDB_DISALLOW_RENEWABLE)) return; if (tgt != NULL && !(tgt->flags & TKT_FLG_RENEWABLE)) return; /* Determine the requested renewable time. */ if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) rtime = request->rtime ? request->rtime : kdc_infinity; else if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) && tkt->times.endtime < request->till) rtime = request->till; else return; /* Truncate it to the allowable renewable time. */ if (tgt != NULL) rtime = min(rtime, tgt->times.renew_till); max_rlife = min(server->max_renewable_life, realm->realm_maxrlife); if (client != NULL) max_rlife = min(max_rlife, client->max_renewable_life); rtime = min(rtime, tkt->times.starttime + max_rlife); /* Make the ticket renewable if the truncated requested time is larger than * the ticket end time. */ if (rtime > tkt->times.endtime) { setflag(tkt->flags, TKT_FLG_RENEWABLE); tkt->times.renew_till = rtime; } } /** * Handle protected negotiation of FAST using enc_padata * - If ENCPADATA_REQ_ENC_PA_REP is present, then: * - Return ENCPADATA_REQ_ENC_PA_REP with checksum of AS-REQ from client * - Include PADATA_FX_FAST in the enc_padata to indicate FAST * @pre @c out_enc_padata has space for at least two more padata * @param index in/out index into @c out_enc_padata for next item */ krb5_error_code kdc_handle_protected_negotiation(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, const krb5_keyblock *reply_key, krb5_pa_data ***out_enc_padata) { krb5_error_code retval = 0; krb5_checksum checksum; krb5_data *out = NULL; krb5_pa_data pa, *pa_in; pa_in = krb5int_find_pa_data(context, request->padata, KRB5_ENCPADATA_REQ_ENC_PA_REP); if (pa_in == NULL) return 0; pa.magic = KV5M_PA_DATA; pa.pa_type = KRB5_ENCPADATA_REQ_ENC_PA_REP; memset(&checksum, 0, sizeof(checksum)); retval = krb5_c_make_checksum(context,0, reply_key, KRB5_KEYUSAGE_AS_REQ, req_pkt, &checksum); if (retval != 0) goto cleanup; retval = encode_krb5_checksum(&checksum, &out); if (retval != 0) goto cleanup; pa.contents = (krb5_octet *) out->data; pa.length = out->length; retval = add_pa_data_element(context, &pa, out_enc_padata, FALSE); if (retval) goto cleanup; out->data = NULL; pa.magic = KV5M_PA_DATA; pa.pa_type = KRB5_PADATA_FX_FAST; pa.length = 0; pa.contents = NULL; retval = add_pa_data_element(context, &pa, out_enc_padata, FALSE); cleanup: if (checksum.contents) krb5_free_checksum_contents(context, &checksum); if (out != NULL) krb5_free_data(context, out); return retval; } /* * Although the KDC doesn't call this function directly, * process_tcp_connection_read() in net-server.c does call it. */ krb5_error_code make_toolong_error (void *handle, krb5_data **out) { krb5_error errpkt; krb5_error_code retval; krb5_data *scratch; struct server_handle *h = handle; retval = krb5_us_timeofday(h->kdc_err_context, &errpkt.stime, &errpkt.susec); if (retval) return retval; errpkt.error = KRB_ERR_FIELD_TOOLONG; errpkt.server = h->kdc_realmlist[0]->realm_tgsprinc; errpkt.client = NULL; errpkt.cusec = 0; errpkt.ctime = 0; errpkt.text.length = 0; errpkt.text.data = 0; errpkt.e_data.length = 0; errpkt.e_data.data = 0; scratch = malloc(sizeof(*scratch)); if (scratch == NULL) return ENOMEM; retval = krb5_mk_error(h->kdc_err_context, &errpkt, scratch); if (retval) { free(scratch); return retval; } *out = scratch; return 0; } void reset_for_hangup(void *ctx) { int k; struct server_handle *h = ctx; for (k = 0; k < h->kdc_numrealms; k++) krb5_db_refresh_config(h->kdc_realmlist[k]->realm_context); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_4997_0
crossvul-cpp_data_good_576_2
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* plugins/kdb/ldap/libkdb_ldap/ldap_principal2.c */ /* * Copyright (C) 2016 by the Massachusetts Institute of Technology. * 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. * * 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 HOLDER 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. */ /* * Copyright (c) 2004-2005, Novell, 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 copyright holder's name is not 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. */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include "ldap_main.h" #include "kdb_ldap.h" #include "ldap_principal.h" #include "princ_xdr.h" #include "ldap_tkt_policy.h" #include "ldap_pwd_policy.h" #include "ldap_err.h" #include <kadm5/admin.h> #include <time.h> extern char* principal_attributes[]; extern char* max_pwd_life_attr[]; static char * getstringtime(krb5_timestamp); krb5_error_code berval2tl_data(struct berval *in, krb5_tl_data **out) { *out = (krb5_tl_data *) malloc (sizeof (krb5_tl_data)); if (*out == NULL) return ENOMEM; (*out)->tl_data_length = in->bv_len - 2; (*out)->tl_data_contents = (krb5_octet *) malloc ((*out)->tl_data_length * sizeof (krb5_octet)); if ((*out)->tl_data_contents == NULL) { free (*out); return ENOMEM; } UNSTORE16_INT (in->bv_val, (*out)->tl_data_type); memcpy ((*out)->tl_data_contents, in->bv_val + 2, (*out)->tl_data_length); return 0; } /* * look up a principal in the directory. */ krb5_error_code krb5_ldap_get_principal(krb5_context context, krb5_const_principal searchfor, unsigned int flags, krb5_db_entry **entry_ptr) { char *user=NULL, *filter=NULL, *filtuser=NULL; unsigned int tree=0, ntrees=1, princlen=0; krb5_error_code tempst=0, st=0; char **values=NULL, **subtree=NULL, *cname=NULL; LDAP *ld=NULL; LDAPMessage *result=NULL, *ent=NULL; krb5_ldap_context *ldap_context=NULL; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; krb5_principal cprinc=NULL; krb5_boolean found=FALSE; krb5_db_entry *entry = NULL; *entry_ptr = NULL; /* Clear the global error string */ krb5_clear_error_message(context); if (searchfor == NULL) return EINVAL; dal_handle = context->dal_handle; ldap_context = (krb5_ldap_context *) dal_handle->db_context; CHECK_LDAP_HANDLE(ldap_context); if (!is_principal_in_realm(ldap_context, searchfor)) { st = KRB5_KDB_NOENTRY; k5_setmsg(context, st, _("Principal does not belong to realm")); goto cleanup; } if ((st=krb5_unparse_name(context, searchfor, &user)) != 0) goto cleanup; if ((st=krb5_ldap_unparse_principal_name(user)) != 0) goto cleanup; filtuser = ldap_filter_correct(user); if (filtuser == NULL) { st = ENOMEM; goto cleanup; } princlen = strlen(FILTER) + strlen(filtuser) + 2 + 1; /* 2 for closing brackets */ if ((filter = malloc(princlen)) == NULL) { st = ENOMEM; goto cleanup; } snprintf(filter, princlen, FILTER"%s))", filtuser); if ((st = krb5_get_subtree_info(ldap_context, &subtree, &ntrees)) != 0) goto cleanup; GET_HANDLE(); for (tree=0; tree < ntrees && !found; ++tree) { LDAP_SEARCH(subtree[tree], ldap_context->lrparams->search_scope, filter, principal_attributes); for (ent=ldap_first_entry(ld, result); ent != NULL && !found; ent=ldap_next_entry(ld, ent)) { /* get the associated directory user information */ if ((values=ldap_get_values(ld, ent, "krbprincipalname")) != NULL) { int i; /* a wild-card in a principal name can return a list of kerberos principals. * Make sure that the correct principal is returned. * NOTE: a principalname k* in ldap server will return all the principals starting with a k */ for (i=0; values[i] != NULL; ++i) { if (strcmp(values[i], user) == 0) { found = TRUE; break; } } ldap_value_free(values); if (!found) /* no matching principal found */ continue; } if ((values=ldap_get_values(ld, ent, "krbcanonicalname")) != NULL) { if (values[0] && strcmp(values[0], user) != 0) { /* We matched an alias, not the canonical name. */ if (flags & KRB5_KDB_FLAG_ALIAS_OK) { st = krb5_ldap_parse_principal_name(values[0], &cname); if (st != 0) goto cleanup; st = krb5_parse_name(context, cname, &cprinc); if (st != 0) goto cleanup; } else /* No canonicalization, so don't return aliases. */ found = FALSE; } ldap_value_free(values); if (!found) continue; } entry = k5alloc(sizeof(*entry), &st); if (entry == NULL) goto cleanup; if ((st = populate_krb5_db_entry(context, ldap_context, ld, ent, cprinc ? cprinc : searchfor, entry)) != 0) goto cleanup; } ldap_msgfree(result); result = NULL; } /* for (tree=0 ... */ if (found) { *entry_ptr = entry; entry = NULL; } else st = KRB5_KDB_NOENTRY; cleanup: ldap_msgfree(result); krb5_db_free_principal(context, entry); if (filter) free (filter); if (subtree) { for (; ntrees; --ntrees) if (subtree[ntrees-1]) free (subtree[ntrees-1]); free (subtree); } if (ldap_server_handle) krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); if (user) free(user); if (filtuser) free(filtuser); if (cname) free(cname); if (cprinc) krb5_free_principal(context, cprinc); return st; } typedef enum{ ADD_PRINCIPAL, MODIFY_PRINCIPAL } OPERATION; /* * ptype is creating confusions. Additionally the logic * surronding ptype is redundunt and can be achevied * with the help of dn and containerdn members. * so dropping the ptype member */ typedef struct _xargs_t { char *dn; char *linkdn; krb5_boolean dn_from_kbd; char *containerdn; char *tktpolicydn; }xargs_t; static void free_xargs(xargs_t xargs) { if (xargs.dn) free (xargs.dn); if (xargs.linkdn) free(xargs.linkdn); if (xargs.containerdn) free (xargs.containerdn); if (xargs.tktpolicydn) free (xargs.tktpolicydn); } static krb5_error_code process_db_args(krb5_context context, char **db_args, xargs_t *xargs, OPERATION optype) { int i=0; krb5_error_code st=0; char *arg=NULL, *arg_val=NULL; char **dptr=NULL; unsigned int arg_val_len=0; if (db_args) { for (i=0; db_args[i]; ++i) { arg = strtok_r(db_args[i], "=", &arg_val); arg = (arg != NULL) ? arg : ""; if (strcmp(arg, TKTPOLICY_ARG) == 0) { dptr = &xargs->tktpolicydn; } else { if (strcmp(arg, USERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->dn; } else if (strcmp(arg, CONTAINERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->containerdn; } else if (strcmp(arg, LINKDN_ARG) == 0) { if (xargs->dn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->linkdn; } else { st = EINVAL; k5_setmsg(context, st, _("unknown option: %s"), arg); goto cleanup; } xargs->dn_from_kbd = TRUE; if (arg_val == NULL || strlen(arg_val) == 0) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } } if (arg_val == NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } arg_val_len = strlen(arg_val) + 1; if (strcmp(arg, TKTPOLICY_ARG) == 0) { if ((st = krb5_ldap_name_to_policydn (context, arg_val, dptr)) != 0) goto cleanup; } else { *dptr = k5memdup(arg_val, arg_val_len, &st); if (*dptr == NULL) goto cleanup; } } } cleanup: return st; } krb5int_access accessor; static krb5_error_code asn1_encode_sequence_of_keys(krb5_key_data *key_data, krb5_int16 n_key_data, krb5_int32 mkvno, krb5_data **code) { krb5_error_code err; ldap_seqof_key_data val; /* * This should be pushed back into other library initialization * code. */ err = kldap_ensure_initialized (); if (err) return err; val.key_data = key_data; val.n_key_data = n_key_data; val.mkvno = mkvno; val.kvno = key_data[0].key_data_kvno; return accessor.asn1_ldap_encode_sequence_of_keys(&val, code); } static krb5_error_code asn1_decode_sequence_of_keys(krb5_data *in, ldap_seqof_key_data *out) { krb5_error_code err; ldap_seqof_key_data *p; int i; memset(out, 0, sizeof(*out)); /* * This should be pushed back into other library initialization * code. */ err = kldap_ensure_initialized (); if (err) return err; err = accessor.asn1_ldap_decode_sequence_of_keys(in, &p); if (err) return err; /* Set kvno and key_data_ver in each key_data element. */ for (i = 0; i < p->n_key_data; i++) { p->key_data[i].key_data_kvno = p->kvno; /* The decoder sets key_data_ver to 1 if no salt is present, but leaves * it at 0 if salt is present. */ if (p->key_data[i].key_data_ver == 0) p->key_data[i].key_data_ver = 2; } *out = *p; free(p); return 0; } /* * Free a NULL-terminated struct berval *array[] and all its contents. * Does not set array to NULL after freeing it. */ void free_berdata(struct berval **array) { int i; if (array != NULL) { for (i = 0; array[i] != NULL; i++) { if (array[i]->bv_val != NULL) free(array[i]->bv_val); free(array[i]); } free(array); } } /* * Encode krb5_key_data into a berval struct for insertion into LDAP. */ static krb5_error_code encode_keys(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno, struct berval **bval_out) { krb5_error_code err = 0; int i; krb5_key_data *key_data = NULL; struct berval *bval = NULL; krb5_data *code; *bval_out = NULL; if (n_key_data <= 0) { err = EINVAL; goto cleanup; } /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } bval = k5alloc(sizeof(struct berval), &err); if (bval == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data, n_key_data, mkvno, &code); if (err) goto cleanup; /* Steal the data pointer from code for bval and discard code. */ bval->bv_len = code->length; bval->bv_val = code->data; free(code); *bval_out = bval; bval = NULL; cleanup: free(key_data); free(bval); return err; } /* Decoding ASN.1 encoded key */ struct berval ** krb5_encode_krbsecretkey(krb5_key_data *key_data, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 0; int i, j, last; krb5_error_code err = 0; if (n_key_data < 0) return NULL; /* Find the number of key versions */ if (n_key_data > 0) { for (i = 0, num_versions = 1; i < n_key_data - 1; i++) { if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; } } ret = calloc(num_versions + 1, sizeof(struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } ret[num_versions] = NULL; /* n_key_data may be 0 if a principal is created without a key. */ if (n_key_data == 0) goto cleanup; currkvno = key_data[0].key_data_kvno; for (i = 0, last = 0, j = 0; i < n_key_data; i++) { if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { err = encode_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &ret[j]); if (err) goto cleanup; j++; last = i + 1; if (i < n_key_data - 1) currkvno = key_data[i + 1].key_data_kvno; } } cleanup: if (err != 0) { free_berdata(ret); ret = NULL; } return ret; } /* * Encode a principal's key history for insertion into ldap. */ static struct berval ** krb5_encode_histkey(osa_princ_ent_rec *princ_ent) { unsigned int i; krb5_error_code err = 0; struct berval **ret = NULL; if (princ_ent->old_key_len <= 0) return NULL; ret = k5calloc(princ_ent->old_key_len + 1, sizeof(struct berval *), &err); if (ret == NULL) goto cleanup; for (i = 0; i < princ_ent->old_key_len; i++) { if (princ_ent->old_keys[i].n_key_data <= 0) { err = EINVAL; goto cleanup; } err = encode_keys(princ_ent->old_keys[i].key_data, princ_ent->old_keys[i].n_key_data, princ_ent->admin_history_kvno, &ret[i]); if (err) goto cleanup; } ret[princ_ent->old_key_len] = NULL; cleanup: if (err != 0) { free_berdata(ret); ret = NULL; } return ret; } static krb5_error_code tl_data2berval (krb5_tl_data *in, struct berval **out) { *out = (struct berval *) malloc (sizeof (struct berval)); if (*out == NULL) return ENOMEM; (*out)->bv_len = in->tl_data_length + 2; (*out)->bv_val = (char *) malloc ((*out)->bv_len); if ((*out)->bv_val == NULL) { free (*out); return ENOMEM; } STORE16_INT((*out)->bv_val, in->tl_data_type); memcpy ((*out)->bv_val + 2, in->tl_data_contents, in->tl_data_length); return 0; } /* Parse the "require_auth" string for auth indicators, adding them to the * krbPrincipalAuthInd attribute. */ static krb5_error_code update_ldap_mod_auth_ind(krb5_context context, krb5_db_entry *entry, LDAPMod ***mods) { int i = 0; krb5_error_code ret; char *auth_ind = NULL; char *strval[10] = {}; char *ai, *ai_save = NULL; int sv_num = sizeof(strval) / sizeof(*strval); ret = krb5_dbe_get_string(context, entry, KRB5_KDB_SK_REQUIRE_AUTH, &auth_ind); if (ret || auth_ind == NULL) goto cleanup; ai = strtok_r(auth_ind, " ", &ai_save); while (ai != NULL && i < sv_num) { strval[i++] = ai; ai = strtok_r(NULL, " ", &ai_save); } ret = krb5_add_str_mem_ldap_mod(mods, "krbPrincipalAuthInd", LDAP_MOD_REPLACE, strval); cleanup: krb5_dbe_free_string(context, auth_ind); return ret; } static krb5_error_code check_dn_in_container(krb5_context context, const char *dn, char *const *subtrees, unsigned int ntrees) { unsigned int i; size_t dnlen = strlen(dn), stlen; for (i = 0; i < ntrees; i++) { if (subtrees[i] == NULL || *subtrees[i] == '\0') return 0; stlen = strlen(subtrees[i]); if (dnlen >= stlen && strcasecmp(dn + dnlen - stlen, subtrees[i]) == 0 && (dnlen == stlen || dn[dnlen - stlen - 1] == ',')) return 0; } k5_setmsg(context, EINVAL, _("DN is out of the realm subtree")); return EINVAL; } static krb5_error_code check_dn_exists(krb5_context context, krb5_ldap_server_handle *ldap_server_handle, const char *dn, krb5_boolean nonkrb_only) { krb5_error_code st = 0, tempst; krb5_ldap_context *ldap_context = context->dal_handle->db_context; LDAP *ld = ldap_server_handle->ldap_handle; LDAPMessage *result = NULL, *ent; char *attrs[] = { "krbticketpolicyreference", "krbprincipalname", NULL }; char **values; LDAP_SEARCH_1(dn, LDAP_SCOPE_BASE, 0, attrs, IGNORE_STATUS); if (st != LDAP_SUCCESS) return set_ldap_error(context, st, OP_SEARCH); ent = ldap_first_entry(ld, result); CHECK_NULL(ent); values = ldap_get_values(ld, ent, "krbticketpolicyreference"); if (values != NULL) ldap_value_free(values); values = ldap_get_values(ld, ent, "krbprincipalname"); if (values != NULL) { ldap_value_free(values); if (nonkrb_only) { st = EINVAL; k5_setmsg(context, st, _("ldap object is already kerberized")); goto cleanup; } } cleanup: ldap_msgfree(result); return st; } static krb5_error_code validate_xargs(krb5_context context, krb5_ldap_server_handle *ldap_server_handle, const xargs_t *xargs, const char *standalone_dn, char *const *subtrees, unsigned int ntrees) { krb5_error_code st; if (xargs->dn != NULL) { /* The supplied dn must be within a realm container. */ st = check_dn_in_container(context, xargs->dn, subtrees, ntrees); if (st) return st; /* The supplied dn must exist without Kerberos attributes. */ st = check_dn_exists(context, ldap_server_handle, xargs->dn, TRUE); if (st) return st; } if (xargs->linkdn != NULL) { /* The supplied linkdn must be within a realm container. */ st = check_dn_in_container(context, xargs->linkdn, subtrees, ntrees); if (st) return st; /* The supplied linkdn must exist. */ st = check_dn_exists(context, ldap_server_handle, xargs->linkdn, FALSE); if (st) return st; } if (xargs->containerdn != NULL && standalone_dn != NULL) { /* standalone_dn (likely composed using containerdn) must be within a * container. */ st = check_dn_in_container(context, standalone_dn, subtrees, ntrees); if (st) return st; } return 0; } krb5_error_code krb5_ldap_put_principal(krb5_context context, krb5_db_entry *entry, char **db_args) { int l=0, kerberos_principal_object_type=0; unsigned int ntrees=0, tre=0; krb5_error_code st=0, tempst=0; LDAP *ld=NULL; LDAPMessage *result=NULL, *ent=NULL; char **subtreelist = NULL; char *user=NULL, *subtree=NULL, *principal_dn=NULL; char *strval[10]={NULL}, errbuf[1024]; char *filtuser=NULL; struct berval **bersecretkey=NULL; LDAPMod **mods=NULL; krb5_boolean create_standalone=FALSE; krb5_boolean establish_links=FALSE; char *standalone_principal_dn=NULL; krb5_tl_data *tl_data=NULL; krb5_key_data **keys=NULL; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_context *ldap_context=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; osa_princ_ent_rec princ_ent = {0}; xargs_t xargs = {0}; char *polname = NULL; OPERATION optype; krb5_boolean found_entry = FALSE; /* Clear the global error string */ krb5_clear_error_message(context); SETUP_CONTEXT(); if (ldap_context->lrparams == NULL || ldap_context->container_dn == NULL) return EINVAL; /* get ldap handle */ GET_HANDLE(); if (!is_principal_in_realm(ldap_context, entry->princ)) { st = EINVAL; k5_setmsg(context, st, _("Principal does not belong to the default realm")); goto cleanup; } /* get the principal information to act on */ if (((st=krb5_unparse_name(context, entry->princ, &user)) != 0) || ((st=krb5_ldap_unparse_principal_name(user)) != 0)) goto cleanup; filtuser = ldap_filter_correct(user); if (filtuser == NULL) { st = ENOMEM; goto cleanup; } /* Identity the type of operation, it can be * add principal or modify principal. * hack if the entry->mask has KRB_PRINCIPAL flag set * then it is a add operation */ if (entry->mask & KADM5_PRINCIPAL) optype = ADD_PRINCIPAL; else optype = MODIFY_PRINCIPAL; if (((st=krb5_get_princ_type(context, entry, &kerberos_principal_object_type)) != 0) || ((st=krb5_get_userdn(context, entry, &principal_dn)) != 0)) goto cleanup; if ((st=process_db_args(context, db_args, &xargs, optype)) != 0) goto cleanup; if (entry->mask & KADM5_LOAD) { unsigned int tree = 0; int numlentries = 0; char *filter = NULL; /* A load operation is special, will do a mix-in (add krbprinc * attrs to a non-krb object entry) if an object exists with a * matching krbprincipalname attribute so try to find existing * object and set principal_dn. This assumes that the * krbprincipalname attribute is unique (only one object entry has * a particular krbprincipalname attribute). */ if (asprintf(&filter, FILTER"%s))", filtuser) < 0) { filter = NULL; st = ENOMEM; goto cleanup; } /* get the current subtree list */ if ((st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees)) != 0) goto cleanup; found_entry = FALSE; /* search for entry with matching krbprincipalname attribute */ for (tree = 0; found_entry == FALSE && tree < ntrees; ++tree) { if (principal_dn == NULL) { LDAP_SEARCH_1(subtreelist[tree], ldap_context->lrparams->search_scope, filter, principal_attributes, IGNORE_STATUS); } else { /* just look for entry with principal_dn */ LDAP_SEARCH_1(principal_dn, LDAP_SCOPE_BASE, filter, principal_attributes, IGNORE_STATUS); } if (st == LDAP_SUCCESS) { numlentries = ldap_count_entries(ld, result); if (numlentries > 1) { free(filter); st = EINVAL; k5_setmsg(context, st, _("operation can not continue, more than one " "entry with principal name \"%s\" found"), user); goto cleanup; } else if (numlentries == 1) { found_entry = TRUE; if (principal_dn == NULL) { ent = ldap_first_entry(ld, result); if (ent != NULL) { /* setting principal_dn will cause that entry to be modified further down */ if ((principal_dn = ldap_get_dn(ld, ent)) == NULL) { ldap_get_option (ld, LDAP_OPT_RESULT_CODE, &st); st = set_ldap_error (context, st, 0); free(filter); goto cleanup; } } } } } else if (st != LDAP_NO_SUCH_OBJECT) { /* could not perform search, return with failure */ st = set_ldap_error (context, st, 0); free(filter); goto cleanup; } ldap_msgfree(result); result = NULL; /* * If it isn't found then assume a standalone princ entry is to * be created. */ } /* end for (tree = 0; principal_dn == ... */ free(filter); if (found_entry == FALSE && principal_dn != NULL) { /* * if principal_dn is null then there is code further down to * deal with setting standalone_principal_dn. Also note that * this will set create_standalone true for * non-mix-in entries which is okay if loading from a dump. */ create_standalone = TRUE; standalone_principal_dn = strdup(principal_dn); CHECK_NULL(standalone_principal_dn); } } /* end if (entry->mask & KADM5_LOAD */ /* time to generate the DN information with the help of * containerdn, principalcontainerreference or * realmcontainerdn information */ if (principal_dn == NULL && xargs.dn == NULL) { /* creation of standalone principal */ /* get the subtree information */ if (entry->princ->length == 2 && entry->princ->data[0].length == strlen("krbtgt") && strncmp(entry->princ->data[0].data, "krbtgt", entry->princ->data[0].length) == 0) { /* if the principal is a inter-realm principal, always created in the realm container */ subtree = strdup(ldap_context->lrparams->realmdn); } else if (xargs.containerdn) { if ((st=checkattributevalue(ld, xargs.containerdn, NULL, NULL, NULL)) != 0) { if (st == KRB5_KDB_NOENTRY || st == KRB5_KDB_CONSTRAINT_VIOLATION) { int ost = st; st = EINVAL; k5_wrapmsg(context, ost, st, _("'%s' not found"), xargs.containerdn); } goto cleanup; } subtree = strdup(xargs.containerdn); } else if (ldap_context->lrparams->containerref && strlen(ldap_context->lrparams->containerref) != 0) { /* * Here the subtree should be changed with * principalcontainerreference attribute value */ subtree = strdup(ldap_context->lrparams->containerref); } else { subtree = strdup(ldap_context->lrparams->realmdn); } CHECK_NULL(subtree); if (asprintf(&standalone_principal_dn, "krbprincipalname=%s,%s", filtuser, subtree) < 0) standalone_principal_dn = NULL; CHECK_NULL(standalone_principal_dn); /* * free subtree when you are done using the subtree * set the boolean create_standalone to TRUE */ create_standalone = TRUE; free(subtree); subtree = NULL; } /* * If the DN information is presented by the user, time to * validate the input to ensure that the DN falls under * any of the subtrees */ if (xargs.dn_from_kbd == TRUE) { /* Get the current subtree list if we haven't already done so. */ if (subtreelist == NULL) { st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees); if (st) goto cleanup; } st = validate_xargs(context, ldap_server_handle, &xargs, standalone_principal_dn, subtreelist, ntrees); if (st) goto cleanup; } if (xargs.linkdn != NULL) { /* * link information can be changed using modprinc. * However, link information can be changed only on the * standalone kerberos principal objects. A standalone * kerberos principal object is of type krbprincipal * structural objectclass. * * NOTE: kerberos principals on an ldap object can't be * linked to other ldap objects. */ if (optype == MODIFY_PRINCIPAL && kerberos_principal_object_type != KDB_STANDALONE_PRINCIPAL_OBJECT) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("link information can not be set/updated as the " "kerberos principal belongs to an ldap object")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } /* * Check the link information. If there is already a link * existing then this operation is not allowed. */ { char **linkdns=NULL; int j=0; if ((st=krb5_get_linkdn(context, entry, &linkdns)) != 0) { snprintf(errbuf, sizeof(errbuf), _("Failed getting object references")); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (linkdns != NULL) { st = EINVAL; snprintf(errbuf, sizeof(errbuf), _("kerberos principal is already linked to a ldap " "object")); k5_setmsg(context, st, "%s", errbuf); for (j=0; linkdns[j] != NULL; ++j) free (linkdns[j]); free (linkdns); goto cleanup; } } establish_links = TRUE; } if (entry->mask & KADM5_LAST_SUCCESS) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->last_success)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastSuccessfulAuth", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_LAST_FAILED) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->last_failed)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastFailedAuth", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free(strval[0]); } if (entry->mask & KADM5_FAIL_AUTH_COUNT) { krb5_kvno fail_auth_count; fail_auth_count = entry->fail_auth_count; if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) fail_auth_count++; st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_REPLACE, fail_auth_count); if (st != 0) goto cleanup; } else if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) { int attr_mask = 0; krb5_boolean has_fail_count; /* Check if the krbLoginFailedCount attribute exists. (Through * krb5 1.8.1, it wasn't set in new entries.) */ st = krb5_get_attributes_mask(context, entry, &attr_mask); if (st != 0) goto cleanup; has_fail_count = ((attr_mask & KDB_FAIL_AUTH_COUNT_ATTR) != 0); /* * If the client library and server supports RFC 4525, * then use it to increment by one the value of the * krbLoginFailedCount attribute. Otherwise, assert the * (provided) old value by deleting it before adding. */ #ifdef LDAP_MOD_INCREMENT if (ldap_server_handle->server_info->modify_increment && has_fail_count) { st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_INCREMENT, 1); if (st != 0) goto cleanup; } else { #endif /* LDAP_MOD_INCREMENT */ if (has_fail_count) { st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_DELETE, entry->fail_auth_count); if (st != 0) goto cleanup; } st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_ADD, entry->fail_auth_count + 1); if (st != 0) goto cleanup; #ifdef LDAP_MOD_INCREMENT } #endif } else if (optype == ADD_PRINCIPAL) { /* Initialize krbLoginFailedCount in new entries to help avoid a * race during the first failed login. */ st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount", LDAP_MOD_ADD, 0); } if (entry->mask & KADM5_MAX_LIFE) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxticketlife", LDAP_MOD_REPLACE, entry->max_life)) != 0) goto cleanup; } if (entry->mask & KADM5_MAX_RLIFE) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxrenewableage", LDAP_MOD_REPLACE, entry->max_renewable_life)) != 0) goto cleanup; } if (entry->mask & KADM5_ATTRIBUTES) { if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbticketflags", LDAP_MOD_REPLACE, entry->attributes)) != 0) goto cleanup; } if (entry->mask & KADM5_PRINCIPAL) { memset(strval, 0, sizeof(strval)); strval[0] = user; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalname", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } if (entry->mask & KADM5_PRINC_EXPIRE_TIME) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_PW_EXPIRATION) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } if (entry->mask & KADM5_POLICY || entry->mask & KADM5_KEY_HIST) { memset(&princ_ent, 0, sizeof(princ_ent)); for (tl_data=entry->tl_data; tl_data; tl_data=tl_data->tl_data_next) { if (tl_data->tl_data_type == KRB5_TL_KADM_DATA) { if ((st = krb5_lookup_tl_kadm_data(tl_data, &princ_ent)) != 0) { goto cleanup; } break; } } } if (entry->mask & KADM5_POLICY) { if (princ_ent.aux_attributes & KADM5_POLICY) { memset(strval, 0, sizeof(strval)); if ((st = krb5_ldap_name_to_policydn (context, princ_ent.policy, &polname)) != 0) goto cleanup; strval[0] = polname; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } else { st = EINVAL; k5_setmsg(context, st, "Password policy value null"); goto cleanup; } } else if (entry->mask & KADM5_LOAD && found_entry == TRUE) { /* * a load is special in that existing entries must have attrs that * removed. */ if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, NULL)) != 0) goto cleanup; } if (entry->mask & KADM5_POLICY_CLR) { if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_DELETE, NULL)) != 0) goto cleanup; } if (entry->mask & KADM5_KEY_HIST) { bersecretkey = krb5_encode_histkey(&princ_ent); if (bersecretkey == NULL) { st = ENOMEM; goto cleanup; } st = krb5_add_ber_mem_ldap_mod(&mods, "krbpwdhistory", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, bersecretkey); if (st != 0) goto cleanup; free_berdata(bersecretkey); bersecretkey = NULL; } if (entry->mask & KADM5_KEY_DATA || entry->mask & KADM5_KVNO) { krb5_kvno mkvno; if ((st=krb5_dbe_lookup_mkvno(context, entry, &mkvno)) != 0) goto cleanup; bersecretkey = krb5_encode_krbsecretkey (entry->key_data, entry->n_key_data, mkvno); if (bersecretkey == NULL) { st = ENOMEM; goto cleanup; } /* An empty list of bervals is only accepted for modify operations, * not add operations. */ if (bersecretkey[0] != NULL || !create_standalone) { st = krb5_add_ber_mem_ldap_mod(&mods, "krbprincipalkey", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, bersecretkey); if (st != 0) goto cleanup; } if (!(entry->mask & KADM5_PRINCIPAL)) { memset(strval, 0, sizeof(strval)); if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } /* Update last password change whenever a new key is set */ { krb5_timestamp last_pw_changed; if ((st=krb5_dbe_lookup_last_pwd_change(context, entry, &last_pw_changed)) != 0) goto cleanup; memset(strval, 0, sizeof(strval)); if ((strval[0] = getstringtime(last_pw_changed)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastPwdChange", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } } /* Modify Key data ends here */ /* Auth indicators will also be stored in krbExtraData when processing * tl_data. */ st = update_ldap_mod_auth_ind(context, entry, &mods); if (st != 0) goto cleanup; /* Set tl_data */ if (entry->tl_data != NULL) { int count = 0; struct berval **ber_tl_data = NULL; krb5_tl_data *ptr; krb5_timestamp unlock_time; for (ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) { if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE #ifdef SECURID || ptr->tl_data_type == KRB5_TL_DB_ARGS #endif || ptr->tl_data_type == KRB5_TL_KADM_DATA || ptr->tl_data_type == KDB_TL_USER_INFO || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK) continue; count++; } if (count != 0) { int j; ber_tl_data = (struct berval **) calloc (count + 1, sizeof (struct berval*)); if (ber_tl_data == NULL) { st = ENOMEM; goto cleanup; } for (j = 0, ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) { /* Ignore tl_data that are stored in separate directory * attributes */ if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE #ifdef SECURID || ptr->tl_data_type == KRB5_TL_DB_ARGS #endif || ptr->tl_data_type == KRB5_TL_KADM_DATA || ptr->tl_data_type == KDB_TL_USER_INFO || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK) continue; if ((st = tl_data2berval (ptr, &ber_tl_data[j])) != 0) break; j++; } if (st == 0) { ber_tl_data[count] = NULL; st=krb5_add_ber_mem_ldap_mod(&mods, "krbExtraData", LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, ber_tl_data); } free_berdata(ber_tl_data); if (st != 0) goto cleanup; } if ((st=krb5_dbe_lookup_last_admin_unlock(context, entry, &unlock_time)) != 0) goto cleanup; if (unlock_time != 0) { /* Update last admin unlock */ memset(strval, 0, sizeof(strval)); if ((strval[0] = getstringtime(unlock_time)) == NULL) goto cleanup; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastAdminUnlock", LDAP_MOD_REPLACE, strval)) != 0) { free (strval[0]); goto cleanup; } free (strval[0]); } } /* Directory specific attribute */ if (xargs.tktpolicydn != NULL) { int tmask=0; if (strlen(xargs.tktpolicydn) != 0) { st = checkattributevalue(ld, xargs.tktpolicydn, "objectclass", policyclass, &tmask); CHECK_CLASS_VALIDITY(st, tmask, _("ticket policy object value: ")); strval[0] = xargs.tktpolicydn; strval[1] = NULL; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } else { /* if xargs.tktpolicydn is a empty string, then delete * already existing krbticketpolicyreference attr */ if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_DELETE, NULL)) != 0) goto cleanup; } } if (establish_links == TRUE) { memset(strval, 0, sizeof(strval)); strval[0] = xargs.linkdn; if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbObjectReferences", LDAP_MOD_REPLACE, strval)) != 0) goto cleanup; } /* * in case mods is NULL then return * not sure but can happen in a modprinc * so no need to return an error * addprinc will at least have the principal name * and the keys passed in */ if (mods == NULL) goto cleanup; if (create_standalone == TRUE) { memset(strval, 0, sizeof(strval)); strval[0] = "krbprincipal"; strval[1] = "krbprincipalaux"; strval[2] = "krbTicketPolicyAux"; if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL); if (st == LDAP_ALREADY_EXISTS && entry->mask & KADM5_LOAD) { /* a load operation must replace an existing entry */ st = ldap_delete_ext_s(ld, standalone_principal_dn, NULL, NULL); if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("Principal delete failed (trying to replace " "entry): %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_ADD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } else { st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL); } } if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("Principal add failed: %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_ADD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } } else { /* * Here existing ldap object is modified and can be related * to any attribute, so always ensure that the ldap * object is extended with all the kerberos related * objectclasses so that there are no constraint * violations. */ { char *attrvalues[] = {"krbprincipalaux", "krbTicketPolicyAux", NULL}; int p, q, r=0, amask=0; if ((st=checkattributevalue(ld, (xargs.dn) ? xargs.dn : principal_dn, "objectclass", attrvalues, &amask)) != 0) goto cleanup; memset(strval, 0, sizeof(strval)); for (p=1, q=0; p<=2; p<<=1, ++q) { if ((p & amask) == 0) strval[r++] = attrvalues[q]; } if (r != 0) { if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; } } if (xargs.dn != NULL) st=ldap_modify_ext_s(ld, xargs.dn, mods, NULL, NULL); else st = ldap_modify_ext_s(ld, principal_dn, mods, NULL, NULL); if (st != LDAP_SUCCESS) { snprintf(errbuf, sizeof(errbuf), _("User modification failed: %s"), ldap_err2string(st)); st = translate_ldap_error (st, OP_MOD); k5_setmsg(context, st, "%s", errbuf); goto cleanup; } if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) entry->fail_auth_count++; } cleanup: if (user) free(user); if (filtuser) free(filtuser); free_xargs(xargs); if (standalone_principal_dn) free(standalone_principal_dn); if (principal_dn) free (principal_dn); if (polname != NULL) free(polname); for (tre = 0; tre < ntrees; tre++) free(subtreelist[tre]); free(subtreelist); if (subtree) free (subtree); if (bersecretkey) { for (l=0; bersecretkey[l]; ++l) { if (bersecretkey[l]->bv_val) free (bersecretkey[l]->bv_val); free (bersecretkey[l]); } free (bersecretkey); } if (keys) free (keys); ldap_mods_free(mods, 1); ldap_osa_free_princ_ent(&princ_ent); ldap_msgfree(result); krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); return(st); } krb5_error_code krb5_read_tkt_policy(krb5_context context, krb5_ldap_context *ldap_context, krb5_db_entry *entries, char *policy) { krb5_error_code st=0; int mask=0, omask=0; int tkt_mask=(KDB_MAX_LIFE_ATTR | KDB_MAX_RLIFE_ATTR | KDB_TKT_FLAGS_ATTR); krb5_ldap_policy_params *tktpoldnparam=NULL; if ((st=krb5_get_attributes_mask(context, entries, &mask)) != 0) goto cleanup; if ((mask & tkt_mask) == tkt_mask) goto cleanup; if (policy != NULL) { st = krb5_ldap_read_policy(context, policy, &tktpoldnparam, &omask); if (st && st != KRB5_KDB_NOENTRY) { k5_prependmsg(context, st, _("Error reading ticket policy")); goto cleanup; } st = 0; /* reset the return status */ } if ((mask & KDB_MAX_LIFE_ATTR) == 0) { if ((omask & KDB_MAX_LIFE_ATTR) == KDB_MAX_LIFE_ATTR) entries->max_life = tktpoldnparam->maxtktlife; else if (ldap_context->lrparams->max_life) entries->max_life = ldap_context->lrparams->max_life; } if ((mask & KDB_MAX_RLIFE_ATTR) == 0) { if ((omask & KDB_MAX_RLIFE_ATTR) == KDB_MAX_RLIFE_ATTR) entries->max_renewable_life = tktpoldnparam->maxrenewlife; else if (ldap_context->lrparams->max_renewable_life) entries->max_renewable_life = ldap_context->lrparams->max_renewable_life; } if ((mask & KDB_TKT_FLAGS_ATTR) == 0) { if ((omask & KDB_TKT_FLAGS_ATTR) == KDB_TKT_FLAGS_ATTR) entries->attributes = tktpoldnparam->tktflags; else if (ldap_context->lrparams->tktflags) entries->attributes |= ldap_context->lrparams->tktflags; } krb5_ldap_free_policy(context, tktpoldnparam); cleanup: return st; } static void free_ldap_seqof_key_data(ldap_seqof_key_data *keysets, krb5_int16 n_keysets) { int i; if (keysets == NULL) return; for (i = 0; i < n_keysets; i++) k5_free_key_data(keysets[i].n_key_data, keysets[i].key_data); free(keysets); } /* * Decode keys from ldap search results. * * Arguments: * - bvalues * The ldap search results containing the key data. * - mkvno * The master kvno that the keys were encrypted with. * - keysets_out * The decoded keys in a ldap_seqof_key_data struct. Must be freed using * free_ldap_seqof_key_data. * - n_keysets_out * The number of entries in keys_out. * - total_keys_out * An optional argument that if given will be set to the total number of * keys found throughout all the entries: sum(keys_out.n_key_data) * May be NULL. */ static krb5_error_code decode_keys(struct berval **bvalues, ldap_seqof_key_data **keysets_out, krb5_int16 *n_keysets_out, krb5_int16 *total_keys_out) { krb5_error_code err = 0; krb5_int16 n_keys, i, ki, total_keys; ldap_seqof_key_data *keysets = NULL; *keysets_out = NULL; *n_keysets_out = 0; if (total_keys_out) *total_keys_out = 0; /* Precount the number of keys. */ for (n_keys = 0, i = 0; bvalues[i] != NULL; i++) { if (bvalues[i]->bv_len > 0) n_keys++; } keysets = k5calloc(n_keys, sizeof(ldap_seqof_key_data), &err); if (keysets == NULL) goto cleanup; memset(keysets, 0, n_keys * sizeof(ldap_seqof_key_data)); for (i = 0, ki = 0, total_keys = 0; bvalues[i] != NULL; i++) { krb5_data in; if (bvalues[i]->bv_len == 0) continue; in.length = bvalues[i]->bv_len; in.data = bvalues[i]->bv_val; err = asn1_decode_sequence_of_keys(&in, &keysets[ki]); if (err) goto cleanup; if (total_keys_out) total_keys += keysets[ki].n_key_data; ki++; } if (total_keys_out) *total_keys_out = total_keys; *n_keysets_out = n_keys; *keysets_out = keysets; keysets = NULL; n_keys = 0; cleanup: free_ldap_seqof_key_data(keysets, n_keys); return err; } krb5_error_code krb5_decode_krbsecretkey(krb5_context context, krb5_db_entry *entries, struct berval **bvalues, krb5_kvno *mkvno) { krb5_key_data *key_data = NULL, *tmp; krb5_error_code err = 0; ldap_seqof_key_data *keysets = NULL; krb5_int16 i, n_keysets = 0, total_keys = 0; err = decode_keys(bvalues, &keysets, &n_keysets, &total_keys); if (err != 0) { k5_prependmsg(context, err, _("unable to decode stored principal key data")); goto cleanup; } key_data = k5calloc(total_keys, sizeof(krb5_key_data), &err); if (key_data == NULL) goto cleanup; memset(key_data, 0, total_keys * sizeof(krb5_key_data)); if (n_keysets > 0) *mkvno = keysets[0].mkvno; /* Transfer key data values from keysets to a flat list in entries. */ tmp = key_data; for (i = 0; i < n_keysets; i++) { memcpy(tmp, keysets[i].key_data, sizeof(krb5_key_data) * keysets[i].n_key_data); tmp += keysets[i].n_key_data; keysets[i].n_key_data = 0; } entries->n_key_data = total_keys; entries->key_data = key_data; key_data = NULL; cleanup: free_ldap_seqof_key_data(keysets, n_keysets); k5_free_key_data(total_keys, key_data); return err; } static int compare_osa_pw_hist_ent(const void *left_in, const void *right_in) { int kvno_left, kvno_right; osa_pw_hist_ent *left = (osa_pw_hist_ent *)left_in; osa_pw_hist_ent *right = (osa_pw_hist_ent *)right_in; kvno_left = left->n_key_data ? left->key_data[0].key_data_kvno : 0; kvno_right = right->n_key_data ? right->key_data[0].key_data_kvno : 0; return kvno_left - kvno_right; } /* * Decode the key history entries from an LDAP search. * * NOTE: the caller must free princ_ent->old_keys even on error. */ krb5_error_code krb5_decode_histkey(krb5_context context, struct berval **bvalues, osa_princ_ent_rec *princ_ent) { krb5_error_code err = 0; krb5_int16 i, n_keysets = 0; ldap_seqof_key_data *keysets = NULL; err = decode_keys(bvalues, &keysets, &n_keysets, NULL); if (err != 0) { k5_prependmsg(context, err, _("unable to decode stored principal pw history")); goto cleanup; } princ_ent->old_keys = k5calloc(n_keysets, sizeof(osa_pw_hist_ent), &err); if (princ_ent->old_keys == NULL) goto cleanup; princ_ent->old_key_len = n_keysets; if (n_keysets > 0) princ_ent->admin_history_kvno = keysets[0].mkvno; /* Transfer key data pointers from keysets to princ_ent. */ for (i = 0; i < n_keysets; i++) { princ_ent->old_keys[i].n_key_data = keysets[i].n_key_data; princ_ent->old_keys[i].key_data = keysets[i].key_data; keysets[i].n_key_data = 0; keysets[i].key_data = NULL; } /* Sort the principal entries by kvno in ascending order. */ qsort(princ_ent->old_keys, princ_ent->old_key_len, sizeof(osa_pw_hist_ent), &compare_osa_pw_hist_ent); princ_ent->aux_attributes |= KADM5_KEY_HIST; /* Set the next key to the end of the list. The queue will be lengthened * if it isn't full yet; the first entry will be replaced if it is full. */ princ_ent->old_key_next = princ_ent->old_key_len; cleanup: free_ldap_seqof_key_data(keysets, n_keysets); return err; } static char * getstringtime(krb5_timestamp epochtime) { struct tm tme; char *strtime=NULL; time_t posixtime = ts2tt(epochtime); strtime = calloc (50, 1); if (strtime == NULL) return NULL; if (gmtime_r(&posixtime, &tme) == NULL) return NULL; strftime(strtime, 50, "%Y%m%d%H%M%SZ", &tme); return strtime; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_576_2
crossvul-cpp_data_bad_3000_0
/* * i8042 keyboard and mouse controller driver for Linux * * Copyright (c) 1999-2004 Vojtech Pavlik */ /* * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/serio.h> #include <linux/err.h> #include <linux/rcupdate.h> #include <linux/platform_device.h> #include <linux/i8042.h> #include <linux/slab.h> #include <linux/suspend.h> #include <asm/io.h> MODULE_AUTHOR("Vojtech Pavlik <vojtech@suse.cz>"); MODULE_DESCRIPTION("i8042 keyboard and mouse controller driver"); MODULE_LICENSE("GPL"); static bool i8042_nokbd; module_param_named(nokbd, i8042_nokbd, bool, 0); MODULE_PARM_DESC(nokbd, "Do not probe or use KBD port."); static bool i8042_noaux; module_param_named(noaux, i8042_noaux, bool, 0); MODULE_PARM_DESC(noaux, "Do not probe or use AUX (mouse) port."); static bool i8042_nomux; module_param_named(nomux, i8042_nomux, bool, 0); MODULE_PARM_DESC(nomux, "Do not check whether an active multiplexing controller is present."); static bool i8042_unlock; module_param_named(unlock, i8042_unlock, bool, 0); MODULE_PARM_DESC(unlock, "Ignore keyboard lock."); enum i8042_controller_reset_mode { I8042_RESET_NEVER, I8042_RESET_ALWAYS, I8042_RESET_ON_S2RAM, #define I8042_RESET_DEFAULT I8042_RESET_ON_S2RAM }; static enum i8042_controller_reset_mode i8042_reset = I8042_RESET_DEFAULT; static int i8042_set_reset(const char *val, const struct kernel_param *kp) { enum i8042_controller_reset_mode *arg = kp->arg; int error; bool reset; if (val) { error = kstrtobool(val, &reset); if (error) return error; } else { reset = true; } *arg = reset ? I8042_RESET_ALWAYS : I8042_RESET_NEVER; return 0; } static const struct kernel_param_ops param_ops_reset_param = { .flags = KERNEL_PARAM_OPS_FL_NOARG, .set = i8042_set_reset, }; #define param_check_reset_param(name, p) \ __param_check(name, p, enum i8042_controller_reset_mode) module_param_named(reset, i8042_reset, reset_param, 0); MODULE_PARM_DESC(reset, "Reset controller on resume, cleanup or both"); static bool i8042_direct; module_param_named(direct, i8042_direct, bool, 0); MODULE_PARM_DESC(direct, "Put keyboard port into non-translated mode."); static bool i8042_dumbkbd; module_param_named(dumbkbd, i8042_dumbkbd, bool, 0); MODULE_PARM_DESC(dumbkbd, "Pretend that controller can only read data from keyboard"); static bool i8042_noloop; module_param_named(noloop, i8042_noloop, bool, 0); MODULE_PARM_DESC(noloop, "Disable the AUX Loopback command while probing for the AUX port"); static bool i8042_notimeout; module_param_named(notimeout, i8042_notimeout, bool, 0); MODULE_PARM_DESC(notimeout, "Ignore timeouts signalled by i8042"); static bool i8042_kbdreset; module_param_named(kbdreset, i8042_kbdreset, bool, 0); MODULE_PARM_DESC(kbdreset, "Reset device connected to KBD port"); #ifdef CONFIG_X86 static bool i8042_dritek; module_param_named(dritek, i8042_dritek, bool, 0); MODULE_PARM_DESC(dritek, "Force enable the Dritek keyboard extension"); #endif #ifdef CONFIG_PNP static bool i8042_nopnp; module_param_named(nopnp, i8042_nopnp, bool, 0); MODULE_PARM_DESC(nopnp, "Do not use PNP to detect controller settings"); #endif #define DEBUG #ifdef DEBUG static bool i8042_debug; module_param_named(debug, i8042_debug, bool, 0600); MODULE_PARM_DESC(debug, "Turn i8042 debugging mode on and off"); static bool i8042_unmask_kbd_data; module_param_named(unmask_kbd_data, i8042_unmask_kbd_data, bool, 0600); MODULE_PARM_DESC(unmask_kbd_data, "Unconditional enable (may reveal sensitive data) of normally sanitize-filtered kbd data traffic debug log [pre-condition: i8042.debug=1 enabled]"); #endif static bool i8042_bypass_aux_irq_test; static char i8042_kbd_firmware_id[128]; static char i8042_aux_firmware_id[128]; #include "i8042.h" /* * i8042_lock protects serialization between i8042_command and * the interrupt handler. */ static DEFINE_SPINLOCK(i8042_lock); /* * Writers to AUX and KBD ports as well as users issuing i8042_command * directly should acquire i8042_mutex (by means of calling * i8042_lock_chip() and i8042_unlock_ship() helpers) to ensure that * they do not disturb each other (unfortunately in many i8042 * implementations write to one of the ports will immediately abort * command that is being processed by another port). */ static DEFINE_MUTEX(i8042_mutex); struct i8042_port { struct serio *serio; int irq; bool exists; bool driver_bound; signed char mux; }; #define I8042_KBD_PORT_NO 0 #define I8042_AUX_PORT_NO 1 #define I8042_MUX_PORT_NO 2 #define I8042_NUM_PORTS (I8042_NUM_MUX_PORTS + 2) static struct i8042_port i8042_ports[I8042_NUM_PORTS]; static unsigned char i8042_initial_ctr; static unsigned char i8042_ctr; static bool i8042_mux_present; static bool i8042_kbd_irq_registered; static bool i8042_aux_irq_registered; static unsigned char i8042_suppress_kbd_ack; static struct platform_device *i8042_platform_device; static struct notifier_block i8042_kbd_bind_notifier_block; static irqreturn_t i8042_interrupt(int irq, void *dev_id); static bool (*i8042_platform_filter)(unsigned char data, unsigned char str, struct serio *serio); void i8042_lock_chip(void) { mutex_lock(&i8042_mutex); } EXPORT_SYMBOL(i8042_lock_chip); void i8042_unlock_chip(void) { mutex_unlock(&i8042_mutex); } EXPORT_SYMBOL(i8042_unlock_chip); int i8042_install_filter(bool (*filter)(unsigned char data, unsigned char str, struct serio *serio)) { unsigned long flags; int ret = 0; spin_lock_irqsave(&i8042_lock, flags); if (i8042_platform_filter) { ret = -EBUSY; goto out; } i8042_platform_filter = filter; out: spin_unlock_irqrestore(&i8042_lock, flags); return ret; } EXPORT_SYMBOL(i8042_install_filter); int i8042_remove_filter(bool (*filter)(unsigned char data, unsigned char str, struct serio *port)) { unsigned long flags; int ret = 0; spin_lock_irqsave(&i8042_lock, flags); if (i8042_platform_filter != filter) { ret = -EINVAL; goto out; } i8042_platform_filter = NULL; out: spin_unlock_irqrestore(&i8042_lock, flags); return ret; } EXPORT_SYMBOL(i8042_remove_filter); /* * The i8042_wait_read() and i8042_wait_write functions wait for the i8042 to * be ready for reading values from it / writing values to it. * Called always with i8042_lock held. */ static int i8042_wait_read(void) { int i = 0; while ((~i8042_read_status() & I8042_STR_OBF) && (i < I8042_CTL_TIMEOUT)) { udelay(50); i++; } return -(i == I8042_CTL_TIMEOUT); } static int i8042_wait_write(void) { int i = 0; while ((i8042_read_status() & I8042_STR_IBF) && (i < I8042_CTL_TIMEOUT)) { udelay(50); i++; } return -(i == I8042_CTL_TIMEOUT); } /* * i8042_flush() flushes all data that may be in the keyboard and mouse buffers * of the i8042 down the toilet. */ static int i8042_flush(void) { unsigned long flags; unsigned char data, str; int count = 0; int retval = 0; spin_lock_irqsave(&i8042_lock, flags); while ((str = i8042_read_status()) & I8042_STR_OBF) { if (count++ < I8042_BUFFER_SIZE) { udelay(50); data = i8042_read_data(); dbg("%02x <- i8042 (flush, %s)\n", data, str & I8042_STR_AUXDATA ? "aux" : "kbd"); } else { retval = -EIO; break; } } spin_unlock_irqrestore(&i8042_lock, flags); return retval; } /* * i8042_command() executes a command on the i8042. It also sends the input * parameter(s) of the commands to it, and receives the output value(s). The * parameters are to be stored in the param array, and the output is placed * into the same array. The number of the parameters and output values is * encoded in bits 8-11 of the command number. */ static int __i8042_command(unsigned char *param, int command) { int i, error; if (i8042_noloop && command == I8042_CMD_AUX_LOOP) return -1; error = i8042_wait_write(); if (error) return error; dbg("%02x -> i8042 (command)\n", command & 0xff); i8042_write_command(command & 0xff); for (i = 0; i < ((command >> 12) & 0xf); i++) { error = i8042_wait_write(); if (error) { dbg(" -- i8042 (wait write timeout)\n"); return error; } dbg("%02x -> i8042 (parameter)\n", param[i]); i8042_write_data(param[i]); } for (i = 0; i < ((command >> 8) & 0xf); i++) { error = i8042_wait_read(); if (error) { dbg(" -- i8042 (wait read timeout)\n"); return error; } if (command == I8042_CMD_AUX_LOOP && !(i8042_read_status() & I8042_STR_AUXDATA)) { dbg(" -- i8042 (auxerr)\n"); return -1; } param[i] = i8042_read_data(); dbg("%02x <- i8042 (return)\n", param[i]); } return 0; } int i8042_command(unsigned char *param, int command) { unsigned long flags; int retval; spin_lock_irqsave(&i8042_lock, flags); retval = __i8042_command(param, command); spin_unlock_irqrestore(&i8042_lock, flags); return retval; } EXPORT_SYMBOL(i8042_command); /* * i8042_kbd_write() sends a byte out through the keyboard interface. */ static int i8042_kbd_write(struct serio *port, unsigned char c) { unsigned long flags; int retval = 0; spin_lock_irqsave(&i8042_lock, flags); if (!(retval = i8042_wait_write())) { dbg("%02x -> i8042 (kbd-data)\n", c); i8042_write_data(c); } spin_unlock_irqrestore(&i8042_lock, flags); return retval; } /* * i8042_aux_write() sends a byte out through the aux interface. */ static int i8042_aux_write(struct serio *serio, unsigned char c) { struct i8042_port *port = serio->port_data; return i8042_command(&c, port->mux == -1 ? I8042_CMD_AUX_SEND : I8042_CMD_MUX_SEND + port->mux); } /* * i8042_port_close attempts to clear AUX or KBD port state by disabling * and then re-enabling it. */ static void i8042_port_close(struct serio *serio) { int irq_bit; int disable_bit; const char *port_name; if (serio == i8042_ports[I8042_AUX_PORT_NO].serio) { irq_bit = I8042_CTR_AUXINT; disable_bit = I8042_CTR_AUXDIS; port_name = "AUX"; } else { irq_bit = I8042_CTR_KBDINT; disable_bit = I8042_CTR_KBDDIS; port_name = "KBD"; } i8042_ctr &= ~irq_bit; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) pr_warn("Can't write CTR while closing %s port\n", port_name); udelay(50); i8042_ctr &= ~disable_bit; i8042_ctr |= irq_bit; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) pr_err("Can't reactivate %s port\n", port_name); /* * See if there is any data appeared while we were messing with * port state. */ i8042_interrupt(0, NULL); } /* * i8042_start() is called by serio core when port is about to finish * registering. It will mark port as existing so i8042_interrupt can * start sending data through it. */ static int i8042_start(struct serio *serio) { struct i8042_port *port = serio->port_data; port->exists = true; mb(); return 0; } /* * i8042_stop() marks serio port as non-existing so i8042_interrupt * will not try to send data to the port that is about to go away. * The function is called by serio core as part of unregister procedure. */ static void i8042_stop(struct serio *serio) { struct i8042_port *port = serio->port_data; port->exists = false; /* * We synchronize with both AUX and KBD IRQs because there is * a (very unlikely) chance that AUX IRQ is raised for KBD port * and vice versa. */ synchronize_irq(I8042_AUX_IRQ); synchronize_irq(I8042_KBD_IRQ); port->serio = NULL; } /* * i8042_filter() filters out unwanted bytes from the input data stream. * It is called from i8042_interrupt and thus is running with interrupts * off and i8042_lock held. */ static bool i8042_filter(unsigned char data, unsigned char str, struct serio *serio) { if (unlikely(i8042_suppress_kbd_ack)) { if ((~str & I8042_STR_AUXDATA) && (data == 0xfa || data == 0xfe)) { i8042_suppress_kbd_ack--; dbg("Extra keyboard ACK - filtered out\n"); return true; } } if (i8042_platform_filter && i8042_platform_filter(data, str, serio)) { dbg("Filtered out by platform filter\n"); return true; } return false; } /* * i8042_interrupt() is the most important function in this driver - * it handles the interrupts from the i8042, and sends incoming bytes * to the upper layers. */ static irqreturn_t i8042_interrupt(int irq, void *dev_id) { struct i8042_port *port; struct serio *serio; unsigned long flags; unsigned char str, data; unsigned int dfl; unsigned int port_no; bool filtered; int ret = 1; spin_lock_irqsave(&i8042_lock, flags); str = i8042_read_status(); if (unlikely(~str & I8042_STR_OBF)) { spin_unlock_irqrestore(&i8042_lock, flags); if (irq) dbg("Interrupt %d, without any data\n", irq); ret = 0; goto out; } data = i8042_read_data(); if (i8042_mux_present && (str & I8042_STR_AUXDATA)) { static unsigned long last_transmit; static unsigned char last_str; dfl = 0; if (str & I8042_STR_MUXERR) { dbg("MUX error, status is %02x, data is %02x\n", str, data); /* * When MUXERR condition is signalled the data register can only contain * 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately * it is not always the case. Some KBCs also report 0xfc when there is * nothing connected to the port while others sometimes get confused which * port the data came from and signal error leaving the data intact. They * _do not_ revert to legacy mode (actually I've never seen KBC reverting * to legacy mode yet, when we see one we'll add proper handling). * Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the * rest assume that the data came from the same serio last byte * was transmitted (if transmission happened not too long ago). */ switch (data) { default: if (time_before(jiffies, last_transmit + HZ/10)) { str = last_str; break; } /* fall through - report timeout */ case 0xfc: case 0xfd: case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break; case 0xff: dfl = SERIO_PARITY; data = 0xfe; break; } } port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3); last_str = str; last_transmit = jiffies; } else { dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) | ((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0); port_no = (str & I8042_STR_AUXDATA) ? I8042_AUX_PORT_NO : I8042_KBD_PORT_NO; } port = &i8042_ports[port_no]; serio = port->exists ? port->serio : NULL; filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n", port_no, irq, dfl & SERIO_PARITY ? ", bad parity" : "", dfl & SERIO_TIMEOUT ? ", timeout" : ""); filtered = i8042_filter(data, str, serio); spin_unlock_irqrestore(&i8042_lock, flags); if (likely(port->exists && !filtered)) serio_interrupt(serio, data, dfl); out: return IRQ_RETVAL(ret); } /* * i8042_enable_kbd_port enables keyboard port on chip */ static int i8042_enable_kbd_port(void) { i8042_ctr &= ~I8042_CTR_KBDDIS; i8042_ctr |= I8042_CTR_KBDINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { i8042_ctr &= ~I8042_CTR_KBDINT; i8042_ctr |= I8042_CTR_KBDDIS; pr_err("Failed to enable KBD port\n"); return -EIO; } return 0; } /* * i8042_enable_aux_port enables AUX (mouse) port on chip */ static int i8042_enable_aux_port(void) { i8042_ctr &= ~I8042_CTR_AUXDIS; i8042_ctr |= I8042_CTR_AUXINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { i8042_ctr &= ~I8042_CTR_AUXINT; i8042_ctr |= I8042_CTR_AUXDIS; pr_err("Failed to enable AUX port\n"); return -EIO; } return 0; } /* * i8042_enable_mux_ports enables 4 individual AUX ports after * the controller has been switched into Multiplexed mode */ static int i8042_enable_mux_ports(void) { unsigned char param; int i; for (i = 0; i < I8042_NUM_MUX_PORTS; i++) { i8042_command(&param, I8042_CMD_MUX_PFX + i); i8042_command(&param, I8042_CMD_AUX_ENABLE); } return i8042_enable_aux_port(); } /* * i8042_set_mux_mode checks whether the controller has an * active multiplexor and puts the chip into Multiplexed (true) * or Legacy (false) mode. */ static int i8042_set_mux_mode(bool multiplex, unsigned char *mux_version) { unsigned char param, val; /* * Get rid of bytes in the queue. */ i8042_flush(); /* * Internal loopback test - send three bytes, they should come back from the * mouse interface, the last should be version. */ param = val = 0xf0; if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != val) return -1; param = val = multiplex ? 0x56 : 0xf6; if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param != val) return -1; param = val = multiplex ? 0xa4 : 0xa5; if (i8042_command(&param, I8042_CMD_AUX_LOOP) || param == val) return -1; /* * Workaround for interference with USB Legacy emulation * that causes a v10.12 MUX to be found. */ if (param == 0xac) return -1; if (mux_version) *mux_version = param; return 0; } /* * i8042_check_mux() checks whether the controller supports the PS/2 Active * Multiplexing specification by Synaptics, Phoenix, Insyde and * LCS/Telegraphics. */ static int __init i8042_check_mux(void) { unsigned char mux_version; if (i8042_set_mux_mode(true, &mux_version)) return -1; pr_info("Detected active multiplexing controller, rev %d.%d\n", (mux_version >> 4) & 0xf, mux_version & 0xf); /* * Disable all muxed ports by disabling AUX. */ i8042_ctr |= I8042_CTR_AUXDIS; i8042_ctr &= ~I8042_CTR_AUXINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_err("Failed to disable AUX port, can't use MUX\n"); return -EIO; } i8042_mux_present = true; return 0; } /* * The following is used to test AUX IRQ delivery. */ static struct completion i8042_aux_irq_delivered __initdata; static bool i8042_irq_being_tested __initdata; static irqreturn_t __init i8042_aux_test_irq(int irq, void *dev_id) { unsigned long flags; unsigned char str, data; int ret = 0; spin_lock_irqsave(&i8042_lock, flags); str = i8042_read_status(); if (str & I8042_STR_OBF) { data = i8042_read_data(); dbg("%02x <- i8042 (aux_test_irq, %s)\n", data, str & I8042_STR_AUXDATA ? "aux" : "kbd"); if (i8042_irq_being_tested && data == 0xa5 && (str & I8042_STR_AUXDATA)) complete(&i8042_aux_irq_delivered); ret = 1; } spin_unlock_irqrestore(&i8042_lock, flags); return IRQ_RETVAL(ret); } /* * i8042_toggle_aux - enables or disables AUX port on i8042 via command and * verifies success by readinng CTR. Used when testing for presence of AUX * port. */ static int __init i8042_toggle_aux(bool on) { unsigned char param; int i; if (i8042_command(&param, on ? I8042_CMD_AUX_ENABLE : I8042_CMD_AUX_DISABLE)) return -1; /* some chips need some time to set the I8042_CTR_AUXDIS bit */ for (i = 0; i < 100; i++) { udelay(50); if (i8042_command(&param, I8042_CMD_CTL_RCTR)) return -1; if (!(param & I8042_CTR_AUXDIS) == on) return 0; } return -1; } /* * i8042_check_aux() applies as much paranoia as it can at detecting * the presence of an AUX interface. */ static int __init i8042_check_aux(void) { int retval = -1; bool irq_registered = false; bool aux_loop_broken = false; unsigned long flags; unsigned char param; /* * Get rid of bytes in the queue. */ i8042_flush(); /* * Internal loopback test - filters out AT-type i8042's. Unfortunately * SiS screwed up and their 5597 doesn't support the LOOP command even * though it has an AUX port. */ param = 0x5a; retval = i8042_command(&param, I8042_CMD_AUX_LOOP); if (retval || param != 0x5a) { /* * External connection test - filters out AT-soldered PS/2 i8042's * 0x00 - no error, 0x01-0x03 - clock/data stuck, 0xff - general error * 0xfa - no error on some notebooks which ignore the spec * Because it's common for chipsets to return error on perfectly functioning * AUX ports, we test for this only when the LOOP command failed. */ if (i8042_command(&param, I8042_CMD_AUX_TEST) || (param && param != 0xfa && param != 0xff)) return -1; /* * If AUX_LOOP completed without error but returned unexpected data * mark it as broken */ if (!retval) aux_loop_broken = true; } /* * Bit assignment test - filters out PS/2 i8042's in AT mode */ if (i8042_toggle_aux(false)) { pr_warn("Failed to disable AUX port, but continuing anyway... Is this a SiS?\n"); pr_warn("If AUX port is really absent please use the 'i8042.noaux' option\n"); } if (i8042_toggle_aux(true)) return -1; /* * Reset keyboard (needed on some laptops to successfully detect * touchpad, e.g., some Gigabyte laptop models with Elantech * touchpads). */ if (i8042_kbdreset) { pr_warn("Attempting to reset device connected to KBD port\n"); i8042_kbd_write(NULL, (unsigned char) 0xff); } /* * Test AUX IRQ delivery to make sure BIOS did not grab the IRQ and * used it for a PCI card or somethig else. */ if (i8042_noloop || i8042_bypass_aux_irq_test || aux_loop_broken) { /* * Without LOOP command we can't test AUX IRQ delivery. Assume the port * is working and hope we are right. */ retval = 0; goto out; } if (request_irq(I8042_AUX_IRQ, i8042_aux_test_irq, IRQF_SHARED, "i8042", i8042_platform_device)) goto out; irq_registered = true; if (i8042_enable_aux_port()) goto out; spin_lock_irqsave(&i8042_lock, flags); init_completion(&i8042_aux_irq_delivered); i8042_irq_being_tested = true; param = 0xa5; retval = __i8042_command(&param, I8042_CMD_AUX_LOOP & 0xf0ff); spin_unlock_irqrestore(&i8042_lock, flags); if (retval) goto out; if (wait_for_completion_timeout(&i8042_aux_irq_delivered, msecs_to_jiffies(250)) == 0) { /* * AUX IRQ was never delivered so we need to flush the controller to * get rid of the byte we put there; otherwise keyboard may not work. */ dbg(" -- i8042 (aux irq test timeout)\n"); i8042_flush(); retval = -1; } out: /* * Disable the interface. */ i8042_ctr |= I8042_CTR_AUXDIS; i8042_ctr &= ~I8042_CTR_AUXINT; if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) retval = -1; if (irq_registered) free_irq(I8042_AUX_IRQ, i8042_platform_device); return retval; } static int i8042_controller_check(void) { if (i8042_flush()) { pr_info("No controller found\n"); return -ENODEV; } return 0; } static int i8042_controller_selftest(void) { unsigned char param; int i = 0; /* * We try this 5 times; on some really fragile systems this does not * take the first time... */ do { if (i8042_command(&param, I8042_CMD_CTL_TEST)) { pr_err("i8042 controller selftest timeout\n"); return -ENODEV; } if (param == I8042_RET_CTL_TEST) return 0; dbg("i8042 controller selftest: %#x != %#x\n", param, I8042_RET_CTL_TEST); msleep(50); } while (i++ < 5); #ifdef CONFIG_X86 /* * On x86, we don't fail entire i8042 initialization if controller * reset fails in hopes that keyboard port will still be functional * and user will still get a working keyboard. This is especially * important on netbooks. On other arches we trust hardware more. */ pr_info("giving up on controller selftest, continuing anyway...\n"); return 0; #else pr_err("i8042 controller selftest failed\n"); return -EIO; #endif } /* * i8042_controller init initializes the i8042 controller, and, * most importantly, sets it into non-xlated mode if that's * desired. */ static int i8042_controller_init(void) { unsigned long flags; int n = 0; unsigned char ctr[2]; /* * Save the CTR for restore on unload / reboot. */ do { if (n >= 10) { pr_err("Unable to get stable CTR read\n"); return -EIO; } if (n != 0) udelay(50); if (i8042_command(&ctr[n++ % 2], I8042_CMD_CTL_RCTR)) { pr_err("Can't read CTR while initializing i8042\n"); return -EIO; } } while (n < 2 || ctr[0] != ctr[1]); i8042_initial_ctr = i8042_ctr = ctr[0]; /* * Disable the keyboard interface and interrupt. */ i8042_ctr |= I8042_CTR_KBDDIS; i8042_ctr &= ~I8042_CTR_KBDINT; /* * Handle keylock. */ spin_lock_irqsave(&i8042_lock, flags); if (~i8042_read_status() & I8042_STR_KEYLOCK) { if (i8042_unlock) i8042_ctr |= I8042_CTR_IGNKEYLOCK; else pr_warn("Warning: Keylock active\n"); } spin_unlock_irqrestore(&i8042_lock, flags); /* * If the chip is configured into nontranslated mode by the BIOS, don't * bother enabling translating and be happy. */ if (~i8042_ctr & I8042_CTR_XLATE) i8042_direct = true; /* * Set nontranslated mode for the kbd interface if requested by an option. * After this the kbd interface becomes a simple serial in/out, like the aux * interface is. We don't do this by default, since it can confuse notebook * BIOSes. */ if (i8042_direct) i8042_ctr &= ~I8042_CTR_XLATE; /* * Write CTR back. */ if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_err("Can't write CTR while initializing i8042\n"); return -EIO; } /* * Flush whatever accumulated while we were disabling keyboard port. */ i8042_flush(); return 0; } /* * Reset the controller and reset CRT to the original value set by BIOS. */ static void i8042_controller_reset(bool s2r_wants_reset) { i8042_flush(); /* * Disable both KBD and AUX interfaces so they don't get in the way */ i8042_ctr |= I8042_CTR_KBDDIS | I8042_CTR_AUXDIS; i8042_ctr &= ~(I8042_CTR_KBDINT | I8042_CTR_AUXINT); if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) pr_warn("Can't write CTR while resetting\n"); /* * Disable MUX mode if present. */ if (i8042_mux_present) i8042_set_mux_mode(false, NULL); /* * Reset the controller if requested. */ if (i8042_reset == I8042_RESET_ALWAYS || (i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) { i8042_controller_selftest(); } /* * Restore the original control register setting. */ if (i8042_command(&i8042_initial_ctr, I8042_CMD_CTL_WCTR)) pr_warn("Can't restore CTR\n"); } /* * i8042_panic_blink() will turn the keyboard LEDs on or off and is called * when kernel panics. Flashing LEDs is useful for users running X who may * not see the console and will help distinguishing panics from "real" * lockups. * * Note that DELAY has a limit of 10ms so we will not get stuck here * waiting for KBC to free up even if KBD interrupt is off */ #define DELAY do { mdelay(1); if (++delay > 10) return delay; } while(0) static long i8042_panic_blink(int state) { long delay = 0; char led; led = (state) ? 0x01 | 0x04 : 0; while (i8042_read_status() & I8042_STR_IBF) DELAY; dbg("%02x -> i8042 (panic blink)\n", 0xed); i8042_suppress_kbd_ack = 2; i8042_write_data(0xed); /* set leds */ DELAY; while (i8042_read_status() & I8042_STR_IBF) DELAY; DELAY; dbg("%02x -> i8042 (panic blink)\n", led); i8042_write_data(led); DELAY; return delay; } #undef DELAY #ifdef CONFIG_X86 static void i8042_dritek_enable(void) { unsigned char param = 0x90; int error; error = i8042_command(&param, 0x1059); if (error) pr_warn("Failed to enable DRITEK extension: %d\n", error); } #endif #ifdef CONFIG_PM /* * Here we try to reset everything back to a state we had * before suspending. */ static int i8042_controller_resume(bool s2r_wants_reset) { int error; error = i8042_controller_check(); if (error) return error; if (i8042_reset == I8042_RESET_ALWAYS || (i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) { error = i8042_controller_selftest(); if (error) return error; } /* * Restore original CTR value and disable all ports */ i8042_ctr = i8042_initial_ctr; if (i8042_direct) i8042_ctr &= ~I8042_CTR_XLATE; i8042_ctr |= I8042_CTR_AUXDIS | I8042_CTR_KBDDIS; i8042_ctr &= ~(I8042_CTR_AUXINT | I8042_CTR_KBDINT); if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_warn("Can't write CTR to resume, retrying...\n"); msleep(50); if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) { pr_err("CTR write retry failed\n"); return -EIO; } } #ifdef CONFIG_X86 if (i8042_dritek) i8042_dritek_enable(); #endif if (i8042_mux_present) { if (i8042_set_mux_mode(true, NULL) || i8042_enable_mux_ports()) pr_warn("failed to resume active multiplexor, mouse won't work\n"); } else if (i8042_ports[I8042_AUX_PORT_NO].serio) i8042_enable_aux_port(); if (i8042_ports[I8042_KBD_PORT_NO].serio) i8042_enable_kbd_port(); i8042_interrupt(0, NULL); return 0; } /* * Here we try to restore the original BIOS settings to avoid * upsetting it. */ static int i8042_pm_suspend(struct device *dev) { int i; if (pm_suspend_via_firmware()) i8042_controller_reset(true); /* Set up serio interrupts for system wakeup. */ for (i = 0; i < I8042_NUM_PORTS; i++) { struct serio *serio = i8042_ports[i].serio; if (serio && device_may_wakeup(&serio->dev)) enable_irq_wake(i8042_ports[i].irq); } return 0; } static int i8042_pm_resume_noirq(struct device *dev) { if (!pm_resume_via_firmware()) i8042_interrupt(0, NULL); return 0; } static int i8042_pm_resume(struct device *dev) { bool want_reset; int i; for (i = 0; i < I8042_NUM_PORTS; i++) { struct serio *serio = i8042_ports[i].serio; if (serio && device_may_wakeup(&serio->dev)) disable_irq_wake(i8042_ports[i].irq); } /* * If platform firmware was not going to be involved in suspend, we did * not restore the controller state to whatever it had been at boot * time, so we do not need to do anything. */ if (!pm_suspend_via_firmware()) return 0; /* * We only need to reset the controller if we are resuming after handing * off control to the platform firmware, otherwise we can simply restore * the mode. */ want_reset = pm_resume_via_firmware(); return i8042_controller_resume(want_reset); } static int i8042_pm_thaw(struct device *dev) { i8042_interrupt(0, NULL); return 0; } static int i8042_pm_reset(struct device *dev) { i8042_controller_reset(false); return 0; } static int i8042_pm_restore(struct device *dev) { return i8042_controller_resume(false); } static const struct dev_pm_ops i8042_pm_ops = { .suspend = i8042_pm_suspend, .resume_noirq = i8042_pm_resume_noirq, .resume = i8042_pm_resume, .thaw = i8042_pm_thaw, .poweroff = i8042_pm_reset, .restore = i8042_pm_restore, }; #endif /* CONFIG_PM */ /* * We need to reset the 8042 back to original mode on system shutdown, * because otherwise BIOSes will be confused. */ static void i8042_shutdown(struct platform_device *dev) { i8042_controller_reset(false); } static int __init i8042_create_kbd_port(void) { struct serio *serio; struct i8042_port *port = &i8042_ports[I8042_KBD_PORT_NO]; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; serio->id.type = i8042_direct ? SERIO_8042 : SERIO_8042_XL; serio->write = i8042_dumbkbd ? NULL : i8042_kbd_write; serio->start = i8042_start; serio->stop = i8042_stop; serio->close = i8042_port_close; serio->ps2_cmd_mutex = &i8042_mutex; serio->port_data = port; serio->dev.parent = &i8042_platform_device->dev; strlcpy(serio->name, "i8042 KBD port", sizeof(serio->name)); strlcpy(serio->phys, I8042_KBD_PHYS_DESC, sizeof(serio->phys)); strlcpy(serio->firmware_id, i8042_kbd_firmware_id, sizeof(serio->firmware_id)); port->serio = serio; port->irq = I8042_KBD_IRQ; return 0; } static int __init i8042_create_aux_port(int idx) { struct serio *serio; int port_no = idx < 0 ? I8042_AUX_PORT_NO : I8042_MUX_PORT_NO + idx; struct i8042_port *port = &i8042_ports[port_no]; serio = kzalloc(sizeof(struct serio), GFP_KERNEL); if (!serio) return -ENOMEM; serio->id.type = SERIO_8042; serio->write = i8042_aux_write; serio->start = i8042_start; serio->stop = i8042_stop; serio->ps2_cmd_mutex = &i8042_mutex; serio->port_data = port; serio->dev.parent = &i8042_platform_device->dev; if (idx < 0) { strlcpy(serio->name, "i8042 AUX port", sizeof(serio->name)); strlcpy(serio->phys, I8042_AUX_PHYS_DESC, sizeof(serio->phys)); strlcpy(serio->firmware_id, i8042_aux_firmware_id, sizeof(serio->firmware_id)); serio->close = i8042_port_close; } else { snprintf(serio->name, sizeof(serio->name), "i8042 AUX%d port", idx); snprintf(serio->phys, sizeof(serio->phys), I8042_MUX_PHYS_DESC, idx + 1); strlcpy(serio->firmware_id, i8042_aux_firmware_id, sizeof(serio->firmware_id)); } port->serio = serio; port->mux = idx; port->irq = I8042_AUX_IRQ; return 0; } static void __init i8042_free_kbd_port(void) { kfree(i8042_ports[I8042_KBD_PORT_NO].serio); i8042_ports[I8042_KBD_PORT_NO].serio = NULL; } static void __init i8042_free_aux_ports(void) { int i; for (i = I8042_AUX_PORT_NO; i < I8042_NUM_PORTS; i++) { kfree(i8042_ports[i].serio); i8042_ports[i].serio = NULL; } } static void __init i8042_register_ports(void) { int i; for (i = 0; i < I8042_NUM_PORTS; i++) { struct serio *serio = i8042_ports[i].serio; if (serio) { printk(KERN_INFO "serio: %s at %#lx,%#lx irq %d\n", serio->name, (unsigned long) I8042_DATA_REG, (unsigned long) I8042_COMMAND_REG, i8042_ports[i].irq); serio_register_port(serio); device_set_wakeup_capable(&serio->dev, true); } } } static void i8042_unregister_ports(void) { int i; for (i = 0; i < I8042_NUM_PORTS; i++) { if (i8042_ports[i].serio) { serio_unregister_port(i8042_ports[i].serio); i8042_ports[i].serio = NULL; } } } static void i8042_free_irqs(void) { if (i8042_aux_irq_registered) free_irq(I8042_AUX_IRQ, i8042_platform_device); if (i8042_kbd_irq_registered) free_irq(I8042_KBD_IRQ, i8042_platform_device); i8042_aux_irq_registered = i8042_kbd_irq_registered = false; } static int __init i8042_setup_aux(void) { int (*aux_enable)(void); int error; int i; if (i8042_check_aux()) return -ENODEV; if (i8042_nomux || i8042_check_mux()) { error = i8042_create_aux_port(-1); if (error) goto err_free_ports; aux_enable = i8042_enable_aux_port; } else { for (i = 0; i < I8042_NUM_MUX_PORTS; i++) { error = i8042_create_aux_port(i); if (error) goto err_free_ports; } aux_enable = i8042_enable_mux_ports; } error = request_irq(I8042_AUX_IRQ, i8042_interrupt, IRQF_SHARED, "i8042", i8042_platform_device); if (error) goto err_free_ports; if (aux_enable()) goto err_free_irq; i8042_aux_irq_registered = true; return 0; err_free_irq: free_irq(I8042_AUX_IRQ, i8042_platform_device); err_free_ports: i8042_free_aux_ports(); return error; } static int __init i8042_setup_kbd(void) { int error; error = i8042_create_kbd_port(); if (error) return error; error = request_irq(I8042_KBD_IRQ, i8042_interrupt, IRQF_SHARED, "i8042", i8042_platform_device); if (error) goto err_free_port; error = i8042_enable_kbd_port(); if (error) goto err_free_irq; i8042_kbd_irq_registered = true; return 0; err_free_irq: free_irq(I8042_KBD_IRQ, i8042_platform_device); err_free_port: i8042_free_kbd_port(); return error; } static int i8042_kbd_bind_notifier(struct notifier_block *nb, unsigned long action, void *data) { struct device *dev = data; struct serio *serio = to_serio_port(dev); struct i8042_port *port = serio->port_data; if (serio != i8042_ports[I8042_KBD_PORT_NO].serio) return 0; switch (action) { case BUS_NOTIFY_BOUND_DRIVER: port->driver_bound = true; break; case BUS_NOTIFY_UNBIND_DRIVER: port->driver_bound = false; break; } return 0; } static int __init i8042_probe(struct platform_device *dev) { int error; i8042_platform_device = dev; if (i8042_reset == I8042_RESET_ALWAYS) { error = i8042_controller_selftest(); if (error) return error; } error = i8042_controller_init(); if (error) return error; #ifdef CONFIG_X86 if (i8042_dritek) i8042_dritek_enable(); #endif if (!i8042_noaux) { error = i8042_setup_aux(); if (error && error != -ENODEV && error != -EBUSY) goto out_fail; } if (!i8042_nokbd) { error = i8042_setup_kbd(); if (error) goto out_fail; } /* * Ok, everything is ready, let's register all serio ports */ i8042_register_ports(); return 0; out_fail: i8042_free_aux_ports(); /* in case KBD failed but AUX not */ i8042_free_irqs(); i8042_controller_reset(false); i8042_platform_device = NULL; return error; } static int i8042_remove(struct platform_device *dev) { i8042_unregister_ports(); i8042_free_irqs(); i8042_controller_reset(false); i8042_platform_device = NULL; return 0; } static struct platform_driver i8042_driver = { .driver = { .name = "i8042", #ifdef CONFIG_PM .pm = &i8042_pm_ops, #endif }, .remove = i8042_remove, .shutdown = i8042_shutdown, }; static struct notifier_block i8042_kbd_bind_notifier_block = { .notifier_call = i8042_kbd_bind_notifier, }; static int __init i8042_init(void) { struct platform_device *pdev; int err; dbg_init(); err = i8042_platform_init(); if (err) return err; err = i8042_controller_check(); if (err) goto err_platform_exit; pdev = platform_create_bundle(&i8042_driver, i8042_probe, NULL, 0, NULL, 0); if (IS_ERR(pdev)) { err = PTR_ERR(pdev); goto err_platform_exit; } bus_register_notifier(&serio_bus, &i8042_kbd_bind_notifier_block); panic_blink = i8042_panic_blink; return 0; err_platform_exit: i8042_platform_exit(); return err; } static void __exit i8042_exit(void) { platform_device_unregister(i8042_platform_device); platform_driver_unregister(&i8042_driver); i8042_platform_exit(); bus_unregister_notifier(&serio_bus, &i8042_kbd_bind_notifier_block); panic_blink = NULL; } module_init(i8042_init); module_exit(i8042_exit);
./CrossVul/dataset_final_sorted/CWE-476/c/bad_3000_0
crossvul-cpp_data_bad_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) { 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/bad_1211_0
crossvul-cpp_data_good_5485_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #ifdef __VMS #define JPEG_SUPPORT 1 #endif /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/profile.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread_.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *), WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *), WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(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 IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 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 ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged 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 ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(image,q)+0.5; if (b > 1.0) b-=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length,ExceptionInfo *exception) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,MagickBooleanType ping, ExceptionInfo *exception) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length,exception); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length, exception); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception); } static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:artist",text,exception); if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:copyright",text,exception); if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:document",text,exception); if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"comment",text,exception); if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:make",text,exception); if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:model",text,exception); if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"label",text,exception); if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:software",text,exception); if ((TIFFGetField(tiff,33423,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if ((TIFFGetField(tiff,36867,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if ((TIFFGetField(tiff,37706,&length,&tietz) == 1) && (tietz != (unsigned long *) NULL)) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MagickPathExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MagickPathExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value,exception); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif **value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* only support 8 bit for now */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG Marker */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; info.channels=(unsigned short) layers->number_channels; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown",exception); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric", exception)); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,image_info->ping,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,"tiff:exif-properties"); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MagickPathExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, "%dx%d",horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor,exception); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated", exception); } } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MagickPathExtent,"%u", (unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=(unsigned char *) GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image=DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties 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 RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MagickPathExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; entry->format_type=ImplicitFormatType; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags|=CoderStealthFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); RelinquishSemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image,ExceptionInfo *) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType,exception); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1,exception); (void) SetImageType(image,BilevelType,exception); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image,exception); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution=next->resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2; resolution.y/=2; pyramid_image=ResizeImage(next,columns,rows,image->filter,exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->resolution=resolution; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE", exception); AppendImageToList(&images,pyramid_image); } } images=GetFirstImageInList(images); /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent); (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent); status=WriteTIFFImage(write_info,images,exception); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(image,q)-0.5; if (b < 0.0) b+=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info, TIFF *tiff,TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { uint32 rows_per_strip; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); else if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0) rows_per_strip=0; /* use default */ rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } /* Create tiled TIFF, ignore "tiff:rows-per-strip". */ flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) ( tiff_info->tile_geometry.height*tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property,exception); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-476/c/good_5485_1
crossvul-cpp_data_bad_1327_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 only if bFree is true. */ 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); } /* ** 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 ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); 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 } /* 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 if( sqlite3WindowRewrite(pParse, p) ){ 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-476/c/bad_1327_2
crossvul-cpp_data_bad_5370_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2002 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Sequence/Matrix Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdlib.h> #include <assert.h> #include <math.h> #include "jasper/jas_seq.h" #include "jasper/jas_malloc.h" #include "jasper/jas_math.h" /******************************************************************************\ * Constructors and destructors. \******************************************************************************/ jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend) { jas_matrix_t *matrix; assert(xstart <= xend && ystart <= yend); if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) { return 0; } matrix->xstart_ = xstart; matrix->ystart_ = ystart; matrix->xend_ = xend; matrix->yend_ = yend; return matrix; } jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; } void jas_matrix_destroy(jas_matrix_t *matrix) { if (matrix->data_) { assert(!(matrix->flags_ & JAS_MATRIX_REF)); jas_free(matrix->data_); matrix->data_ = 0; } if (matrix->rows_) { jas_free(matrix->rows_); matrix->rows_ = 0; } jas_free(matrix); } jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x) { jas_matrix_t *y; int i; int j; y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x)); assert(y); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; } jas_matrix_t *jas_matrix_copy(jas_matrix_t *x) { jas_matrix_t *y; int i; int j; y = jas_matrix_create(x->numrows_, x->numcols_); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; } /******************************************************************************\ * Bind operations. \******************************************************************************/ void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart, int ystart, int xend, int yend) { jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_, yend - s1->ystart_ - 1, xend - s1->xstart_ - 1); } void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0, int r1, int c1) { int i; if (mat0->data_) { if (!(mat0->flags_ & JAS_MATRIX_REF)) { jas_free(mat0->data_); } mat0->data_ = 0; mat0->datasize_ = 0; } if (mat0->rows_) { jas_free(mat0->rows_); mat0->rows_ = 0; } mat0->flags_ |= JAS_MATRIX_REF; mat0->numrows_ = r1 - r0 + 1; mat0->numcols_ = c1 - c0 + 1; mat0->maxrows_ = mat0->numrows_; if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) { /* There is no way to indicate failure to the caller. So, we have no choice but to abort. Ideally, this function should have a non-void return type. In practice, a non-void return type probably would not help much anyways as the caller would just have to terminate anyways. */ abort(); } for (i = 0; i < mat0->numrows_; ++i) { mat0->rows_[i] = mat1->rows_[r0 + i] + c0; } mat0->xstart_ = mat1->xstart_ + c0; mat0->ystart_ = mat1->ystart_ + r0; mat0->xend_ = mat0->xstart_ + mat0->numcols_; mat0->yend_ = mat0->ystart_ + mat0->numrows_; } /******************************************************************************\ * Arithmetic operations. \******************************************************************************/ int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1) { int i; int j; if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ != mat1->numcols_) { return 1; } for (i = 0; i < mat0->numrows_; i++) { for (j = 0; j < mat0->numcols_; j++) { if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) { return 1; } } } return 0; } void jas_matrix_divpow2(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = (*data >= 0) ? ((*data) >> n) : (-((-(*data)) >> n)); } } } } void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval) { int i; int j; jas_seqent_t v; jas_seqent_t *rowstart; jas_seqent_t *data; int rowstep; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { data = rowstart; for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { v = *data; if (v < minval) { *data = minval; } else if (v > maxval) { *data = maxval; } } } } } void jas_matrix_asr(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; assert(n >= 0); if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { //*data >>= n; *data = jas_seqent_asr(*data, n); } } } } void jas_matrix_asl(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { //*data <<= n; *data = jas_seqent_asl(*data, n); } } } } /******************************************************************************\ * Code. \******************************************************************************/ int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols) { int size; int i; size = numrows * numcols; if (size > matrix->datasize_ || numrows > matrix->maxrows_) { return -1; } matrix->numrows_ = numrows; matrix->numcols_ = numcols; for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[numcols * i]; } return 0; } void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = val; } } } } jas_matrix_t *jas_seq2d_input(FILE *in) { jas_matrix_t *matrix; int i; int j; long x; int numrows; int numcols; int xoff; int yoff; if (fscanf(in, "%d %d", &xoff, &yoff) != 2) return 0; if (fscanf(in, "%d %d", &numcols, &numrows) != 2) return 0; if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows))) return 0; if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) { abort(); } /* Get matrix data. */ for (i = 0; i < jas_matrix_numrows(matrix); i++) { for (j = 0; j < jas_matrix_numcols(matrix); j++) { if (fscanf(in, "%ld", &x) != 1) { jas_matrix_destroy(matrix); return 0; } jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); } } return matrix; } int jas_seq2d_output(jas_matrix_t *matrix, FILE *out) { #define MAXLINELEN 80 int i; int j; jas_seqent_t x; char buf[MAXLINELEN + 1]; char sbuf[MAXLINELEN + 1]; int n; fprintf(out, "%d %d\n", jas_seq2d_xstart(matrix), jas_seq2d_ystart(matrix)); fprintf(out, "%d %d\n", jas_matrix_numcols(matrix), jas_matrix_numrows(matrix)); buf[0] = '\0'; for (i = 0; i < jas_matrix_numrows(matrix); ++i) { for (j = 0; j < jas_matrix_numcols(matrix); ++j) { x = jas_matrix_get(matrix, i, j); sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "", JAS_CAST(long, x)); n = strlen(buf); if (n + strlen(sbuf) > MAXLINELEN) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } strcat(buf, sbuf); if (j == jas_matrix_numcols(matrix) - 1) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } } } fputs(buf, out); return 0; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5370_0
crossvul-cpp_data_bad_325_0
/************************************************************ * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting * documentation, and that the name of Silicon Graphics not be * used in advertising or publicity pertaining to distribution * of the software without specific prior written permission. * Silicon Graphics makes no representation about the suitability * of this software for any purpose. It is provided "as is" * without any express or implied warranty. * * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH * THE USE OR PERFORMANCE OF THIS SOFTWARE. * ********************************************************/ /* * Copyright © 2012 Ran Benita <ran234@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * 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 "xkbcomp-priv.h" #include "text.h" #include "expr.h" #include "action.h" #include "vmod.h" #include "include.h" enum si_field { SI_FIELD_VIRTUAL_MOD = (1 << 0), SI_FIELD_ACTION = (1 << 1), SI_FIELD_AUTO_REPEAT = (1 << 2), SI_FIELD_LEVEL_ONE_ONLY = (1 << 3), }; typedef struct { enum si_field defined; enum merge_mode merge; struct xkb_sym_interpret interp; } SymInterpInfo; enum led_field { LED_FIELD_MODS = (1 << 0), LED_FIELD_GROUPS = (1 << 1), LED_FIELD_CTRLS = (1 << 2), }; typedef struct { enum led_field defined; enum merge_mode merge; struct xkb_led led; } LedInfo; typedef struct { char *name; int errorCount; SymInterpInfo default_interp; darray(SymInterpInfo) interps; LedInfo default_led; LedInfo leds[XKB_MAX_LEDS]; unsigned int num_leds; ActionsInfo *actions; struct xkb_mod_set mods; struct xkb_context *ctx; } CompatInfo; static const char * siText(SymInterpInfo *si, CompatInfo *info) { char *buf = xkb_context_get_buffer(info->ctx, 128); if (si == &info->default_interp) return "default"; snprintf(buf, 128, "%s+%s(%s)", KeysymText(info->ctx, si->interp.sym), SIMatchText(si->interp.match), ModMaskText(info->ctx, &info->mods, si->interp.mods)); return buf; } static inline bool ReportSINotArray(CompatInfo *info, SymInterpInfo *si, const char *field) { return ReportNotArray(info->ctx, "symbol interpretation", field, siText(si, info)); } static inline bool ReportSIBadType(CompatInfo *info, SymInterpInfo *si, const char *field, const char *wanted) { return ReportBadType(info->ctx, "symbol interpretation", field, siText(si, info), wanted); } static inline bool ReportLedBadType(CompatInfo *info, LedInfo *ledi, const char *field, const char *wanted) { return ReportBadType(info->ctx, "indicator map", field, xkb_atom_text(info->ctx, ledi->led.name), wanted); } static inline bool ReportLedNotArray(CompatInfo *info, LedInfo *ledi, const char *field) { return ReportNotArray(info->ctx, "indicator map", field, xkb_atom_text(info->ctx, ledi->led.name)); } static void InitCompatInfo(CompatInfo *info, struct xkb_context *ctx, ActionsInfo *actions, const struct xkb_mod_set *mods) { memset(info, 0, sizeof(*info)); info->ctx = ctx; info->actions = actions; info->mods = *mods; info->default_interp.merge = MERGE_OVERRIDE; info->default_interp.interp.virtual_mod = XKB_MOD_INVALID; info->default_led.merge = MERGE_OVERRIDE; } static void ClearCompatInfo(CompatInfo *info) { free(info->name); darray_free(info->interps); } static SymInterpInfo * FindMatchingInterp(CompatInfo *info, SymInterpInfo *new) { SymInterpInfo *old; darray_foreach(old, info->interps) if (old->interp.sym == new->interp.sym && old->interp.mods == new->interp.mods && old->interp.match == new->interp.match) return old; return NULL; } static bool UseNewInterpField(enum si_field field, SymInterpInfo *old, SymInterpInfo *new, bool report, enum si_field *collide) { if (!(old->defined & field)) return true; if (new->defined & field) { if (report) *collide |= field; if (new->merge != MERGE_AUGMENT) return true; } return false; } static bool AddInterp(CompatInfo *info, SymInterpInfo *new, bool same_file) { SymInterpInfo *old = FindMatchingInterp(info, new); if (old) { const int verbosity = xkb_context_get_log_verbosity(info->ctx); const bool report = (same_file && verbosity > 0) || verbosity > 9; enum si_field collide = 0; if (new->merge == MERGE_REPLACE) { if (report) log_warn(info->ctx, "Multiple definitions for \"%s\"; " "Earlier interpretation ignored\n", siText(new, info)); *old = *new; return true; } if (UseNewInterpField(SI_FIELD_VIRTUAL_MOD, old, new, report, &collide)) { old->interp.virtual_mod = new->interp.virtual_mod; old->defined |= SI_FIELD_VIRTUAL_MOD; } if (UseNewInterpField(SI_FIELD_ACTION, old, new, report, &collide)) { old->interp.action = new->interp.action; old->defined |= SI_FIELD_ACTION; } if (UseNewInterpField(SI_FIELD_AUTO_REPEAT, old, new, report, &collide)) { old->interp.repeat = new->interp.repeat; old->defined |= SI_FIELD_AUTO_REPEAT; } if (UseNewInterpField(SI_FIELD_LEVEL_ONE_ONLY, old, new, report, &collide)) { old->interp.level_one_only = new->interp.level_one_only; old->defined |= SI_FIELD_LEVEL_ONE_ONLY; } if (collide) { log_warn(info->ctx, "Multiple interpretations of \"%s\"; " "Using %s definition for duplicate fields\n", siText(new, info), (new->merge != MERGE_AUGMENT ? "last" : "first")); } return true; } darray_append(info->interps, *new); return true; } /***====================================================================***/ static bool ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) { log_err(info->ctx, "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, "any")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); } /***====================================================================***/ static bool UseNewLEDField(enum led_field field, LedInfo *old, LedInfo *new, bool report, enum led_field *collide) { if (!(old->defined & field)) return true; if (new->defined & field) { if (report) *collide |= field; if (new->merge != MERGE_AUGMENT) return true; } return false; } static bool AddLedMap(CompatInfo *info, LedInfo *new, bool same_file) { enum led_field collide; const int verbosity = xkb_context_get_log_verbosity(info->ctx); const bool report = (same_file && verbosity > 0) || verbosity > 9; for (xkb_led_index_t i = 0; i < info->num_leds; i++) { LedInfo *old = &info->leds[i]; if (old->led.name != new->led.name) continue; if (old->led.mods.mods == new->led.mods.mods && old->led.groups == new->led.groups && old->led.ctrls == new->led.ctrls && old->led.which_mods == new->led.which_mods && old->led.which_groups == new->led.which_groups) { old->defined |= new->defined; return true; } if (new->merge == MERGE_REPLACE) { if (report) log_warn(info->ctx, "Map for indicator %s redefined; " "Earlier definition ignored\n", xkb_atom_text(info->ctx, old->led.name)); *old = *new; return true; } collide = 0; if (UseNewLEDField(LED_FIELD_MODS, old, new, report, &collide)) { old->led.which_mods = new->led.which_mods; old->led.mods = new->led.mods; old->defined |= LED_FIELD_MODS; } if (UseNewLEDField(LED_FIELD_GROUPS, old, new, report, &collide)) { old->led.which_groups = new->led.which_groups; old->led.groups = new->led.groups; old->defined |= LED_FIELD_GROUPS; } if (UseNewLEDField(LED_FIELD_CTRLS, old, new, report, &collide)) { old->led.ctrls = new->led.ctrls; old->defined |= LED_FIELD_CTRLS; } if (collide) { log_warn(info->ctx, "Map for indicator %s redefined; " "Using %s definition for duplicate fields\n", xkb_atom_text(info->ctx, old->led.name), (new->merge == MERGE_AUGMENT ? "first" : "last")); } return true; } if (info->num_leds >= XKB_MAX_LEDS) { log_err(info->ctx, "Too many LEDs defined (maximum %d)\n", XKB_MAX_LEDS); return false; } info->leds[info->num_leds++] = *new; return true; } static void MergeIncludedCompatMaps(CompatInfo *into, CompatInfo *from, enum merge_mode merge) { if (from->errorCount > 0) { into->errorCount += from->errorCount; return; } into->mods = from->mods; if (into->name == NULL) { into->name = from->name; from->name = NULL; } if (darray_empty(into->interps)) { into->interps = from->interps; darray_init(from->interps); } else { SymInterpInfo *si; darray_foreach(si, from->interps) { si->merge = (merge == MERGE_DEFAULT ? si->merge : merge); if (!AddInterp(into, si, false)) into->errorCount++; } } if (into->num_leds == 0) { memcpy(into->leds, from->leds, sizeof(*from->leds) * from->num_leds); into->num_leds = from->num_leds; from->num_leds = 0; } else { for (xkb_led_index_t i = 0; i < from->num_leds; i++) { LedInfo *ledi = &from->leds[i]; ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge); if (!AddLedMap(into, ledi, false)) into->errorCount++; } } } static void HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge); static bool HandleIncludeCompatMap(CompatInfo *info, IncludeStmt *include) { CompatInfo included; InitCompatInfo(&included, info->ctx, info->actions, &info->mods); included.name = include->stmt; include->stmt = NULL; for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) { CompatInfo next_incl; XkbFile *file; file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_COMPAT); if (!file) { info->errorCount += 10; ClearCompatInfo(&included); return false; } InitCompatInfo(&next_incl, info->ctx, info->actions, &included.mods); next_incl.default_interp = info->default_interp; next_incl.default_interp.merge = stmt->merge; next_incl.default_led = info->default_led; next_incl.default_led.merge = stmt->merge; HandleCompatMapFile(&next_incl, file, MERGE_OVERRIDE); MergeIncludedCompatMaps(&included, &next_incl, stmt->merge); ClearCompatInfo(&next_incl); FreeXkbFile(file); } MergeIncludedCompatMaps(info, &included, include->merge); ClearCompatInfo(&included); return (info->errorCount == 0); } static bool SetInterpField(CompatInfo *info, SymInterpInfo *si, const char *field, ExprDef *arrayNdx, ExprDef *value) { xkb_mod_index_t ndx; if (istreq(field, "action")) { if (arrayNdx) return ReportSINotArray(info, si, field); if (!HandleActionDef(info->ctx, info->actions, &info->mods, value, &si->interp.action)) return false; si->defined |= SI_FIELD_ACTION; } else if (istreq(field, "virtualmodifier") || istreq(field, "virtualmod")) { if (arrayNdx) return ReportSINotArray(info, si, field); if (!ExprResolveMod(info->ctx, value, MOD_VIRT, &info->mods, &ndx)) return ReportSIBadType(info, si, field, "virtual modifier"); si->interp.virtual_mod = ndx; si->defined |= SI_FIELD_VIRTUAL_MOD; } else if (istreq(field, "repeat")) { bool set; if (arrayNdx) return ReportSINotArray(info, si, field); if (!ExprResolveBoolean(info->ctx, value, &set)) return ReportSIBadType(info, si, field, "boolean"); si->interp.repeat = set; si->defined |= SI_FIELD_AUTO_REPEAT; } else if (istreq(field, "locking")) { log_dbg(info->ctx, "The \"locking\" field in symbol interpretation is unsupported; " "Ignored\n"); } else if (istreq(field, "usemodmap") || istreq(field, "usemodmapmods")) { unsigned int val; if (arrayNdx) return ReportSINotArray(info, si, field); if (!ExprResolveEnum(info->ctx, value, &val, useModMapValueNames)) return ReportSIBadType(info, si, field, "level specification"); si->interp.level_one_only = val; si->defined |= SI_FIELD_LEVEL_ONE_ONLY; } else { return ReportBadField(info->ctx, "symbol interpretation", field, siText(si, info)); } return true; } static bool SetLedMapField(CompatInfo *info, LedInfo *ledi, const char *field, ExprDef *arrayNdx, ExprDef *value) { bool ok = true; if (istreq(field, "modifiers") || istreq(field, "mods")) { if (arrayNdx) return ReportLedNotArray(info, ledi, field); if (!ExprResolveModMask(info->ctx, value, MOD_BOTH, &info->mods, &ledi->led.mods.mods)) return ReportLedBadType(info, ledi, field, "modifier mask"); ledi->defined |= LED_FIELD_MODS; } else if (istreq(field, "groups")) { unsigned int mask; if (arrayNdx) return ReportLedNotArray(info, ledi, field); if (!ExprResolveMask(info->ctx, value, &mask, groupMaskNames)) return ReportLedBadType(info, ledi, field, "group mask"); ledi->led.groups = mask; ledi->defined |= LED_FIELD_GROUPS; } else if (istreq(field, "controls") || istreq(field, "ctrls")) { unsigned int mask; if (arrayNdx) return ReportLedNotArray(info, ledi, field); if (!ExprResolveMask(info->ctx, value, &mask, ctrlMaskNames)) return ReportLedBadType(info, ledi, field, "controls mask"); ledi->led.ctrls = mask; ledi->defined |= LED_FIELD_CTRLS; } else if (istreq(field, "allowexplicit")) { log_dbg(info->ctx, "The \"allowExplicit\" field in indicator statements is unsupported; " "Ignored\n"); } else if (istreq(field, "whichmodstate") || istreq(field, "whichmodifierstate")) { unsigned int mask; if (arrayNdx) return ReportLedNotArray(info, ledi, field); if (!ExprResolveMask(info->ctx, value, &mask, modComponentMaskNames)) return ReportLedBadType(info, ledi, field, "mask of modifier state components"); ledi->led.which_mods = mask; } else if (istreq(field, "whichgroupstate")) { unsigned mask; if (arrayNdx) return ReportLedNotArray(info, ledi, field); if (!ExprResolveMask(info->ctx, value, &mask, groupComponentMaskNames)) return ReportLedBadType(info, ledi, field, "mask of group state components"); ledi->led.which_groups = mask; } else if (istreq(field, "driveskbd") || istreq(field, "driveskeyboard") || istreq(field, "leddriveskbd") || istreq(field, "leddriveskeyboard") || istreq(field, "indicatordriveskbd") || istreq(field, "indicatordriveskeyboard")) { log_dbg(info->ctx, "The \"%s\" field in indicator statements is unsupported; " "Ignored\n", field); } else if (istreq(field, "index")) { /* Users should see this, it might cause unexpected behavior. */ log_err(info->ctx, "The \"index\" field in indicator statements is unsupported; " "Ignored\n"); } else { log_err(info->ctx, "Unknown field %s in map for %s indicator; " "Definition ignored\n", field, xkb_atom_text(info->ctx, ledi->led.name)); ok = false; } return ok; } static bool HandleGlobalVar(CompatInfo *info, VarDef *stmt) { const char *elem, *field; ExprDef *ndx; bool ret; if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &ndx)) ret = false; else if (elem && istreq(elem, "interpret")) ret = SetInterpField(info, &info->default_interp, field, ndx, stmt->value); else if (elem && istreq(elem, "indicator")) ret = SetLedMapField(info, &info->default_led, field, ndx, stmt->value); else ret = SetActionField(info->ctx, info->actions, &info->mods, elem, field, ndx, stmt->value); return ret; } static bool HandleInterpBody(CompatInfo *info, VarDef *def, SymInterpInfo *si) { bool ok = true; const char *elem, *field; ExprDef *arrayNdx; for (; def; def = (VarDef *) def->common.next) { if (def->name && def->name->expr.op == EXPR_FIELD_REF) { log_err(info->ctx, "Cannot set a global default value from within an interpret statement; " "Move statements to the global file scope\n"); ok = false; continue; } ok = ExprResolveLhs(info->ctx, def->name, &elem, &field, &arrayNdx); if (!ok) continue; ok = SetInterpField(info, si, field, arrayNdx, def->value); } return ok; } static bool HandleInterpDef(CompatInfo *info, InterpDef *def, enum merge_mode merge) { enum xkb_match_operation pred; xkb_mod_mask_t mods; SymInterpInfo si; if (!ResolveStateAndPredicate(def->match, &pred, &mods, info)) { log_err(info->ctx, "Couldn't determine matching modifiers; " "Symbol interpretation ignored\n"); return false; } si = info->default_interp; si.merge = merge = (def->merge == MERGE_DEFAULT ? merge : def->merge); si.interp.sym = def->sym; si.interp.match = pred; si.interp.mods = mods; if (!HandleInterpBody(info, def->def, &si)) { info->errorCount++; return false; } if (!AddInterp(info, &si, true)) { info->errorCount++; return false; } return true; } static bool HandleLedMapDef(CompatInfo *info, LedMapDef *def, enum merge_mode merge) { LedInfo ledi; VarDef *var; bool ok; if (def->merge != MERGE_DEFAULT) merge = def->merge; ledi = info->default_led; ledi.merge = merge; ledi.led.name = def->name; ok = true; for (var = def->body; var != NULL; var = (VarDef *) var->common.next) { const char *elem, *field; ExprDef *arrayNdx; if (!ExprResolveLhs(info->ctx, var->name, &elem, &field, &arrayNdx)) { ok = false; continue; } if (elem) { log_err(info->ctx, "Cannot set defaults for \"%s\" element in indicator map; " "Assignment to %s.%s ignored\n", elem, elem, field); ok = false; } else { ok = SetLedMapField(info, &ledi, field, arrayNdx, var->value) && ok; } } if (ok) return AddLedMap(info, &ledi, true); return false; } static void HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge) { bool ok; merge = (merge == MERGE_DEFAULT ? MERGE_AUGMENT : merge); free(info->name); info->name = strdup_safe(file->name); for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) { switch (stmt->type) { case STMT_INCLUDE: ok = HandleIncludeCompatMap(info, (IncludeStmt *) stmt); break; case STMT_INTERP: ok = HandleInterpDef(info, (InterpDef *) stmt, merge); break; case STMT_GROUP_COMPAT: log_dbg(info->ctx, "The \"group\" statement in compat is unsupported; " "Ignored\n"); ok = true; break; case STMT_LED_MAP: ok = HandleLedMapDef(info, (LedMapDef *) stmt, merge); break; case STMT_VAR: ok = HandleGlobalVar(info, (VarDef *) stmt); break; case STMT_VMOD: ok = HandleVModDef(info->ctx, &info->mods, (VModDef *) stmt, merge); break; default: log_err(info->ctx, "Compat files may not include other types; " "Ignoring %s\n", stmt_type_to_string(stmt->type)); ok = false; break; } if (!ok) info->errorCount++; if (info->errorCount > 10) { log_err(info->ctx, "Abandoning compatibility map \"%s\"\n", file->name); break; } } } /* Temporary struct for CopyInterps. */ struct collect { darray(struct xkb_sym_interpret) sym_interprets; }; static void CopyInterps(CompatInfo *info, bool needSymbol, enum xkb_match_operation pred, struct collect *collect) { SymInterpInfo *si; darray_foreach(si, info->interps) if (si->interp.match == pred && (si->interp.sym != XKB_KEY_NoSymbol) == needSymbol) darray_append(collect->sym_interprets, si->interp); } static void CopyLedMapDefsToKeymap(struct xkb_keymap *keymap, CompatInfo *info) { for (xkb_led_index_t idx = 0; idx < info->num_leds; idx++) { LedInfo *ledi = &info->leds[idx]; xkb_led_index_t i; struct xkb_led *led; /* * Find the LED with the given name, if it was already declared * in keycodes. */ xkb_leds_enumerate(i, led, keymap) if (led->name == ledi->led.name) break; /* Not previously declared; create it with next free index. */ if (i >= keymap->num_leds) { log_dbg(keymap->ctx, "Indicator name \"%s\" was not declared in the keycodes section; " "Adding new indicator\n", xkb_atom_text(keymap->ctx, ledi->led.name)); xkb_leds_enumerate(i, led, keymap) if (led->name == XKB_ATOM_NONE) break; if (i >= keymap->num_leds) { /* Not place to put it; ignore. */ if (i >= XKB_MAX_LEDS) { log_err(keymap->ctx, "Too many indicators (maximum is %d); " "Indicator name \"%s\" ignored\n", XKB_MAX_LEDS, xkb_atom_text(keymap->ctx, ledi->led.name)); continue; } /* Add a new LED. */ led = &keymap->leds[keymap->num_leds++]; } } *led = ledi->led; if (led->groups != 0 && led->which_groups == 0) led->which_groups = XKB_STATE_LAYOUT_EFFECTIVE; if (led->mods.mods != 0 && led->which_mods == 0) led->which_mods = XKB_STATE_MODS_EFFECTIVE; } } static bool CopyCompatToKeymap(struct xkb_keymap *keymap, CompatInfo *info) { keymap->compat_section_name = strdup_safe(info->name); XkbEscapeMapName(keymap->compat_section_name); keymap->mods = info->mods; if (!darray_empty(info->interps)) { struct collect collect; darray_init(collect.sym_interprets); /* Most specific to least specific. */ CopyInterps(info, true, MATCH_EXACTLY, &collect); CopyInterps(info, true, MATCH_ALL, &collect); CopyInterps(info, true, MATCH_NONE, &collect); CopyInterps(info, true, MATCH_ANY, &collect); CopyInterps(info, true, MATCH_ANY_OR_NONE, &collect); CopyInterps(info, false, MATCH_EXACTLY, &collect); CopyInterps(info, false, MATCH_ALL, &collect); CopyInterps(info, false, MATCH_NONE, &collect); CopyInterps(info, false, MATCH_ANY, &collect); CopyInterps(info, false, MATCH_ANY_OR_NONE, &collect); darray_steal(collect.sym_interprets, &keymap->sym_interprets, &keymap->num_sym_interprets); } CopyLedMapDefsToKeymap(keymap, info); return true; } bool CompileCompatMap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { CompatInfo info; ActionsInfo *actions; actions = NewActionsInfo(); if (!actions) return false; InitCompatInfo(&info, keymap->ctx, actions, &keymap->mods); info.default_interp.merge = merge; info.default_led.merge = merge; HandleCompatMapFile(&info, file, merge); if (info.errorCount != 0) goto err_info; if (!CopyCompatToKeymap(keymap, &info)) goto err_info; ClearCompatInfo(&info); FreeActionsInfo(actions); return true; err_info: ClearCompatInfo(&info); FreeActionsInfo(actions); return false; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_325_0
crossvul-cpp_data_good_4986_0
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/backing-dev.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); if (unlikely(isolated_balloon_page(page))) balloon_page_putback(page); else putback_lru_page(page); } } /* * Restore a potential migration pte to a working pte entry */ static int remove_migration_pte(struct page *new, struct vm_area_struct *vma, unsigned long addr, void *old) { struct mm_struct *mm = vma->vm_mm; swp_entry_t entry; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; if (unlikely(PageHuge(new))) { ptep = huge_pte_offset(mm, addr); if (!ptep) goto out; ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep); } else { pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; ptep = pte_offset_map(pmd, addr); /* * Peek to check is_swap_pte() before taking ptlock? No, we * can race mremap's move_ptes(), which skips anon_vma lock. */ ptl = pte_lockptr(mm, pmd); } spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto unlock; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry) || migration_entry_to_page(entry) != old) goto unlock; get_page(new); pte = pte_mkold(mk_pte(new, vma->vm_page_prot)); if (pte_swp_soft_dirty(*ptep)) pte = pte_mksoft_dirty(pte); /* Recheck VMA as permissions can change since migration started */ if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); } #endif flush_dcache_page(new); set_pte_at(mm, addr, ptep, pte); if (PageHuge(new)) { if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, addr); else page_dup_rmap(new); } else if (PageAnon(new)) page_add_anon_rmap(new, vma, addr); else page_add_file_rmap(new); if (vma->vm_flags & VM_LOCKED) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, addr, ptep); unlock: pte_unmap_unlock(ptep, ptl); out: return SWAP_AGAIN; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ static void remove_migration_ptes(struct page *old, struct page *new) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { struct zone *oldzone, *newzone; int dirty; int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } oldzone = page_zone(page); newzone = page_zone(newpage); spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } /* Move dirty while page refs frozen and newpage not yet exposed */ dirty = PageDirty(page); if (dirty) { ClearPageDirty(page); SetPageDirty(newpage); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); spin_unlock(&mapping->tree_lock); /* Leave irq disabled to prevent preemption while updating stats */ /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ if (newzone != oldzone) { __dec_zone_state(oldzone, NR_FILE_PAGES); __inc_zone_state(newzone, NR_FILE_PAGES); if (PageSwapBacked(page) && !PageSwapCache(page)) { __dec_zone_state(oldzone, NR_SHMEM); __inc_zone_state(newzone, NR_SHMEM); } if (dirty && mapping_cap_account_dirty(mapping)) { __dec_zone_state(oldzone, NR_FILE_DIRTY); __inc_zone_state(newzone, NR_FILE_DIRTY); } } local_irq_enable(); return MIGRATEPAGE_SUCCESS; } /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(pslot, newpage); page_unfreeze_refs(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); /* Move dirty on pages not done by migrate_page_move_mapping() */ if (PageDirty(page)) SetPageDirty(newpage); if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems provide a * migratepage callback. Anonymous pages are part of swap * space which also has its own migratepage callback. This * is the most common path for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { set_page_memcg(page, NULL); if (!PageAnon(page)) page->mapping = NULL; } return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(isolated_balloon_page(page))) { /* * A ballooned page does not need any special attention from * physical to virtual reverse mapping procedures. * Skip any attempt to unmap PTEs or to remap swap cache, * in order to avoid burning cycles at rmap level, and perform * the page migration right away (proteced by page lock). */ rc = balloon_page_migrate(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ goto out; } if (unlikely(PageTransHuge(page))) if (unlikely(split_huge_page(page))) goto out; rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) put_new_page = NULL; out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); /* Soft-offlined page shouldn't go through lru cache list */ if (reason == MR_MEMORY_FAILURE) { put_page(page); if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } else putback_lru_page(page); } /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, putback_lru_page() will drop the reference grabbed * during isolation. */ if (put_new_page) put_new_page(newpage, private); else if (unlikely(__is_movable_balloon_page(newpage))) { /* drop our reference, page already in the balloon */ put_page(newpage); } else putback_lru_page(newpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; if (!zone_reclaimable(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~GFP_IOFS, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; pmd_t orig_entry; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER); if (!new_page) goto out_fail; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } if (mm_tlb_flush_pending(mm)) flush_tlb_range(vma, mmun_start, mmun_end); /* Prepare a page as a migration target */ __set_page_locked(new_page); SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) { fail_putback: spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } orig_entry = *pmd; entry = mk_pmd(new_page, vma->vm_page_prot); entry = pmd_mkhuge(entry); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); flush_tlb_range(vma, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); if (page_count(page) != 2) { set_pmd_at(mm, mmun_start, pmd, orig_entry); flush_tlb_range(vma, mmun_start, mmun_end); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); page_remove_rmap(new_page); goto fail_putback; } mlock_migrate_page(new_page, page); set_page_memcg(new_page, page_memcg(page)); set_page_memcg(page, NULL); page_remove_rmap(page); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
./CrossVul/dataset_final_sorted/CWE-476/c/good_4986_0
crossvul-cpp_data_bad_588_0
/* $Id: form.c,v 1.35 2010/07/18 13:48:48 htrb Exp $ */ /* * HTML forms */ #include "fm.h" #include "parsetag.h" #include "parsetagx.h" #include "myctype.h" #include "local.h" #include "regex.h" extern Str *textarea_str; extern int max_textarea; #ifdef MENU_SELECT extern FormSelectOption *select_option; extern int max_select; #include "menu.h" #endif /* MENU_SELECT */ /* *INDENT-OFF* */ struct { char *action; void (*rout)(struct parsed_tagarg *); } internal_action[] = { {"map", follow_map}, {"option", panel_set_option}, #ifdef USE_COOKIE {"cookie", set_cookie_flag}, #endif /* USE_COOKIE */ {"download", download_action}, #ifdef USE_M17N { "charset", change_charset }, #endif {"none", NULL}, {NULL, NULL}, }; /* *INDENT-ON* */ struct form_list * newFormList(char *action, char *method, char *charset, char *enctype, char *target, char *name, struct form_list *_next) { struct form_list *l; Str a = Strnew_charp(action); int m = FORM_METHOD_GET; int e = FORM_ENCTYPE_URLENCODED; #ifdef USE_M17N wc_ces c = 0; #endif if (method == NULL || !strcasecmp(method, "get")) m = FORM_METHOD_GET; else if (!strcasecmp(method, "post")) m = FORM_METHOD_POST; else if (!strcasecmp(method, "internal")) m = FORM_METHOD_INTERNAL; /* unknown method is regarded as 'get' */ if (m != FORM_METHOD_GET && enctype != NULL && !strcasecmp(enctype, "multipart/form-data")) { e = FORM_ENCTYPE_MULTIPART; } #ifdef USE_M17N if (charset != NULL) c = wc_guess_charset(charset, 0); #endif l = New(struct form_list); l->item = l->lastitem = NULL; l->action = a; l->method = m; #ifdef USE_M17N l->charset = c; #endif l->enctype = e; l->target = target; l->name = name; l->next = _next; l->nitems = 0; l->body = NULL; l->length = 0; return l; } /* * add <input> element to form_list */ struct form_item_list * formList_addInput(struct form_list *fl, struct parsed_tag *tag) { struct form_item_list *item; char *p; int i; /* if not in <form>..</form> environment, just ignore <input> tag */ if (fl == NULL) return NULL; item = New(struct form_item_list); item->type = FORM_UNKNOWN; item->size = -1; item->rows = 0; item->checked = item->init_checked = 0; item->accept = 0; item->name = NULL; item->value = item->init_value = NULL; item->readonly = 0; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { item->type = formtype(p); if (item->size < 0 && (item->type == FORM_INPUT_TEXT || item->type == FORM_INPUT_FILE || item->type == FORM_INPUT_PASSWORD)) item->size = FORM_I_TEXT_DEFAULT_SIZE; } if (parsedtag_get_value(tag, ATTR_NAME, &p)) item->name = Strnew_charp(p); if (parsedtag_get_value(tag, ATTR_VALUE, &p)) item->value = item->init_value = Strnew_charp(p); item->checked = item->init_checked = parsedtag_exists(tag, ATTR_CHECKED); item->accept = parsedtag_exists(tag, ATTR_ACCEPT); parsedtag_get_value(tag, ATTR_SIZE, &item->size); parsedtag_get_value(tag, ATTR_MAXLENGTH, &item->maxlength); item->readonly = parsedtag_exists(tag, ATTR_READONLY); if (parsedtag_get_value(tag, ATTR_TEXTAREANUMBER, &i) && i >= 0 && i < max_textarea) item->value = item->init_value = textarea_str[i]; #ifdef MENU_SELECT if (parsedtag_get_value(tag, ATTR_SELECTNUMBER, &i) && i >= 0 && i < max_select) item->select_option = select_option[i].first; #endif /* MENU_SELECT */ if (parsedtag_get_value(tag, ATTR_ROWS, &p)) item->rows = atoi(p); if (item->type == FORM_UNKNOWN) { /* type attribute is missing. Ignore the tag. */ return NULL; } #ifdef MENU_SELECT if (item->type == FORM_SELECT) { chooseSelectOption(item, item->select_option); item->init_selected = item->selected; item->init_value = item->value; item->init_label = item->label; } #endif /* MENU_SELECT */ if (item->type == FORM_INPUT_FILE && item->value && item->value->length) { /* security hole ! */ return NULL; } item->parent = fl; item->next = NULL; if (fl->item == NULL) { fl->item = fl->lastitem = item; } else { fl->lastitem->next = item; fl->lastitem = item; } if (item->type == FORM_INPUT_HIDDEN) return NULL; fl->nitems++; return item; } static char *_formtypetbl[] = { "text", "password", "checkbox", "radio", "submit", "reset", "hidden", "image", "select", "textarea", "button", "file", NULL }; static char *_formmethodtbl[] = { "GET", "POST", "INTERNAL", "HEAD" }; char * form2str(FormItemList *fi) { Str tmp = Strnew(); if (fi->type != FORM_SELECT && fi->type != FORM_TEXTAREA) Strcat_charp(tmp, "input type="); Strcat_charp(tmp, _formtypetbl[fi->type]); if (fi->name && fi->name->length) Strcat_m_charp(tmp, " name=\"", fi->name->ptr, "\"", NULL); if ((fi->type == FORM_INPUT_RADIO || fi->type == FORM_INPUT_CHECKBOX || fi->type == FORM_SELECT) && fi->value) Strcat_m_charp(tmp, " value=\"", fi->value->ptr, "\"", NULL); Strcat_m_charp(tmp, " (", _formmethodtbl[fi->parent->method], " ", fi->parent->action->ptr, ")", NULL); return tmp->ptr; } int formtype(char *typestr) { int i; for (i = 0; _formtypetbl[i]; i++) { if (!strcasecmp(typestr, _formtypetbl[i])) return i; } return FORM_INPUT_TEXT; } void formRecheckRadio(Anchor *a, Buffer *buf, FormItemList *fi) { int i; Anchor *a2; FormItemList *f2; for (i = 0; i < buf->formitem->nanchor; i++) { a2 = &buf->formitem->anchors[i]; f2 = (FormItemList *)a2->url; if (f2->parent == fi->parent && f2 != fi && f2->type == FORM_INPUT_RADIO && Strcmp(f2->name, fi->name) == 0) { f2->checked = 0; formUpdateBuffer(a2, buf, f2); } } fi->checked = 1; formUpdateBuffer(a, buf, fi); } void formResetBuffer(Buffer *buf, AnchorList *formitem) { int i; Anchor *a; FormItemList *f1, *f2; if (buf == NULL || buf->formitem == NULL || formitem == NULL) return; for (i = 0; i < buf->formitem->nanchor && i < formitem->nanchor; i++) { a = &buf->formitem->anchors[i]; if (a->y != a->start.line) continue; f1 = (FormItemList *)a->url; f2 = (FormItemList *)formitem->anchors[i].url; if (f1->type != f2->type || strcmp(((f1->name == NULL) ? "" : f1->name->ptr), ((f2->name == NULL) ? "" : f2->name->ptr))) break; /* What's happening */ switch (f1->type) { case FORM_INPUT_TEXT: case FORM_INPUT_PASSWORD: case FORM_INPUT_FILE: case FORM_TEXTAREA: f1->value = f2->value; f1->init_value = f2->init_value; break; case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: f1->checked = f2->checked; f1->init_checked = f2->init_checked; break; case FORM_SELECT: #ifdef MENU_SELECT f1->select_option = f2->select_option; f1->value = f2->value; f1->label = f2->label; f1->selected = f2->selected; f1->init_value = f2->init_value; f1->init_label = f2->init_label; f1->init_selected = f2->init_selected; #endif /* MENU_SELECT */ break; default: continue; } formUpdateBuffer(a, buf, f1); } } static int form_update_line(Line *line, char **str, int spos, int epos, int width, int newline, int password) { int c_len = 1, c_width = 1, w, i, len, pos; char *p, *buf; Lineprop c_type, effect, *prop; for (p = *str, w = 0, pos = 0; *p && w < width;) { c_type = get_mctype((unsigned char *)p); #ifdef USE_M17N c_len = get_mclen(p); c_width = get_mcwidth(p); #endif if (c_type == PC_CTRL) { if (newline && *p == '\n') break; if (*p != '\r') { w++; pos++; } } else if (password) { #ifdef USE_M17N if (w + c_width > width) break; #endif w += c_width; pos += c_width; #ifdef USE_M17N } else if (c_type & PC_UNKNOWN) { w++; pos++; } else { if (w + c_width > width) break; #endif w += c_width; pos += c_len; } p += c_len; } pos += width - w; len = line->len + pos + spos - epos; buf = New_N(char, len + 1); buf[len] = '\0'; prop = New_N(Lineprop, len); bcopy((void *)line->lineBuf, (void *)buf, spos * sizeof(char)); bcopy((void *)line->propBuf, (void *)prop, spos * sizeof(Lineprop)); effect = CharEffect(line->propBuf[spos]); for (p = *str, w = 0, pos = spos; *p && w < width;) { c_type = get_mctype((unsigned char *)p); #ifdef USE_M17N c_len = get_mclen(p); c_width = get_mcwidth(p); #endif if (c_type == PC_CTRL) { if (newline && *p == '\n') break; if (*p != '\r') { buf[pos] = password ? '*' : ' '; prop[pos] = effect | PC_ASCII; pos++; w++; } } else if (password) { #ifdef USE_M17N if (w + c_width > width) break; #endif for (i = 0; i < c_width; i++) { buf[pos] = '*'; prop[pos] = effect | PC_ASCII; pos++; w++; } #ifdef USE_M17N } else if (c_type & PC_UNKNOWN) { buf[pos] = ' '; prop[pos] = effect | PC_ASCII; pos++; w++; } else { if (w + c_width > width) break; #else } else { #endif buf[pos] = *p; prop[pos] = effect | c_type; pos++; #ifdef USE_M17N c_type = (c_type & ~PC_WCHAR1) | PC_WCHAR2; for (i = 1; i < c_len; i++) { buf[pos] = p[i]; prop[pos] = effect | c_type; pos++; } #endif w += c_width; } p += c_len; } for (; w < width; w++) { buf[pos] = ' '; prop[pos] = effect | PC_ASCII; pos++; } if (newline) { if (!FoldTextarea) { while (*p && *p != '\r' && *p != '\n') p++; } if (*p == '\r') p++; if (*p == '\n') p++; } *str = p; bcopy((void *)&line->lineBuf[epos], (void *)&buf[pos], (line->len - epos) * sizeof(char)); bcopy((void *)&line->propBuf[epos], (void *)&prop[pos], (line->len - epos) * sizeof(Lineprop)); line->lineBuf = buf; line->propBuf = prop; line->len = len; line->size = len; return pos; } void formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (buf->currentLine == NULL || spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ { if (!form->value) break; p = form->value->ptr; } l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0 || COLPOS(l, epos) < col) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); } Str textfieldrep(Str s, int width) { Lineprop c_type; Str n = Strnew_size(width + 2); int i, j, k, c_len; j = 0; for (i = 0; i < s->length; i += c_len) { c_type = get_mctype((unsigned char *)&s->ptr[i]); c_len = get_mclen(&s->ptr[i]); if (s->ptr[i] == '\r') continue; k = j + get_mcwidth(&s->ptr[i]); if (k > width) break; if (c_type == PC_CTRL) Strcat_char(n, ' '); #ifdef USE_M17N else if (c_type & PC_UNKNOWN) Strcat_char(n, ' '); #endif else if (s->ptr[i] == '&') Strcat_charp(n, "&amp;"); else if (s->ptr[i] == '<') Strcat_charp(n, "&lt;"); else if (s->ptr[i] == '>') Strcat_charp(n, "&gt;"); else Strcat_charp_n(n, &s->ptr[i], c_len); j = k; } for (; j < width; j++) Strcat_char(n, ' '); return n; } static void form_fputs_decode(Str s, FILE * f) { char *p; Str z = Strnew(); for (p = s->ptr; *p;) { switch (*p) { #if !defined( __CYGWIN__ ) && !defined( __EMX__ ) case '\r': if (*(p + 1) == '\n') p++; /* continue to the next label */ #endif /* !defined( __CYGWIN__ ) && !defined( __EMX__ * ) */ default: Strcat_char(z, *p); p++; break; } } #ifdef USE_M17N z = wc_Str_conv_strict(z, InnerCharset, DisplayCharset); #endif Strfputs(z, f); } void input_textarea(FormItemList *fi) { char *tmpf = tmpfname(TMPF_DFL, NULL)->ptr; Str tmp; FILE *f; #ifdef USE_M17N wc_ces charset = DisplayCharset; wc_uint8 auto_detect; #endif f = fopen(tmpf, "w"); if (f == NULL) { /* FIXME: gettextize? */ disp_err_message("Can't open temporary file", FALSE); return; } if (fi->value) form_fputs_decode(fi->value, f); fclose(f); fmTerm(); system(myEditor(Editor, tmpf, 1)->ptr); fmInit(); if (fi->readonly) goto input_end; f = fopen(tmpf, "r"); if (f == NULL) { /* FIXME: gettextize? */ disp_err_message("Can't open temporary file", FALSE); goto input_end; } fi->value = Strnew(); #ifdef USE_M17N auto_detect = WcOption.auto_detect; WcOption.auto_detect = WC_OPT_DETECT_ON; #endif while (tmp = Strfgets(f), tmp->length > 0) { if (tmp->length == 1 && tmp->ptr[tmp->length - 1] == '\n') { /* null line with bare LF */ tmp = Strnew_charp("\r\n"); } else if (tmp->length > 1 && tmp->ptr[tmp->length - 1] == '\n' && tmp->ptr[tmp->length - 2] != '\r') { Strshrink(tmp, 1); Strcat_charp(tmp, "\r\n"); } tmp = convertLine(NULL, tmp, RAW_MODE, &charset, DisplayCharset); Strcat(fi->value, tmp); } #ifdef USE_M17N WcOption.auto_detect = auto_detect; #endif fclose(f); input_end: unlink(tmpf); } void do_internal(char *action, char *data) { int i; for (i = 0; internal_action[i].action; i++) { if (strcasecmp(internal_action[i].action, action) == 0) { if (internal_action[i].rout) internal_action[i].rout(cgistr2tagarg(data)); return; } } } #ifdef MENU_SELECT void addSelectOption(FormSelectOption *fso, Str value, Str label, int chk) { FormSelectOptionItem *o; o = New(FormSelectOptionItem); if (value == NULL) value = label; o->value = value; Strremovefirstspaces(label); Strremovetrailingspaces(label); o->label = label; o->checked = chk; o->next = NULL; if (fso->first == NULL) fso->first = fso->last = o; else { fso->last->next = o; fso->last = o; } } void chooseSelectOption(FormItemList *fi, FormSelectOptionItem *item) { FormSelectOptionItem *opt; int i; fi->selected = 0; if (item == NULL) { fi->value = Strnew_size(0); fi->label = Strnew_size(0); return; } fi->value = item->value; fi->label = item->label; for (i = 0, opt = item; opt != NULL; i++, opt = opt->next) { if (opt->checked) { fi->value = opt->value; fi->label = opt->label; fi->selected = i; break; } } updateSelectOption(fi, item); } void updateSelectOption(FormItemList *fi, FormSelectOptionItem *item) { int i; if (fi == NULL || item == NULL) return; for (i = 0; item != NULL; i++, item = item->next) { if (i == fi->selected) item->checked = TRUE; else item->checked = FALSE; } } int formChooseOptionByMenu(struct form_item_list *fi, int x, int y) { int i, n, selected = -1, init_select = fi->selected; FormSelectOptionItem *opt; char **label; for (n = 0, opt = fi->select_option; opt != NULL; n++, opt = opt->next) ; label = New_N(char *, n + 1); for (i = 0, opt = fi->select_option; opt != NULL; i++, opt = opt->next) label[i] = opt->label->ptr; label[n] = NULL; optionMenu(x, y, label, &selected, init_select, NULL); if (selected < 0) return 0; for (i = 0, opt = fi->select_option; opt != NULL; i++, opt = opt->next) { if (i == selected) { fi->selected = selected; fi->value = opt->value; fi->label = opt->label; break; } } updateSelectOption(fi, fi->select_option); return 1; } #endif /* MENU_SELECT */ void form_write_data(FILE * f, char *boundary, char *name, char *value) { fprintf(f, "--%s\r\n", boundary); fprintf(f, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n", name); fprintf(f, "%s\r\n", value); } void form_write_from_file(FILE * f, char *boundary, char *name, char *filename, char *file) { FILE *fd; struct stat st; int c; char *type; fprintf(f, "--%s\r\n", boundary); fprintf(f, "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n", name, mybasename(filename)); type = guessContentType(file); fprintf(f, "Content-Type: %s\r\n\r\n", type ? type : "application/octet-stream"); if (lstat(file, &st) < 0) goto write_end; if (S_ISDIR(st.st_mode)) goto write_end; fd = fopen(file, "r"); if (fd != NULL) { while ((c = fgetc(fd)) != EOF) fputc(c, f); fclose(fd); } write_end: fprintf(f, "\r\n"); } struct pre_form_item { int type; char *name; char *value; int checked; struct pre_form_item *next; }; struct pre_form { char *url; Regex *re_url; char *name; char *action; struct pre_form_item *item; struct pre_form *next; }; static struct pre_form *PreForm = NULL; static struct pre_form * add_pre_form(struct pre_form *prev, char *url, Regex *re_url, char *name, char *action) { ParsedURL pu; struct pre_form *new; if (prev) new = prev->next = New(struct pre_form); else new = PreForm = New(struct pre_form); if (url && !re_url) { parseURL2(url, &pu, NULL); new->url = parsedURL2Str(&pu)->ptr; } else new->url = url; new->re_url = re_url; new->name = (name && *name) ? name : NULL; new->action = (action && *action) ? action : NULL; new->item = NULL; new->next = NULL; return new; } static struct pre_form_item * add_pre_form_item(struct pre_form *pf, struct pre_form_item *prev, int type, char *name, char *value, char *checked) { struct pre_form_item *new; if (!pf) return NULL; if (prev) new = prev->next = New(struct pre_form_item); else new = pf->item = New(struct pre_form_item); new->type = type; new->name = name; new->value = value; if (checked && *checked && (!strcmp(checked, "0") || !strcasecmp(checked, "off") || !strcasecmp(checked, "no"))) new->checked = 0; else new->checked = 1; new->next = NULL; return new; } /* * url <url>|/<re-url>/ * form [<name>] <action> * text <name> <value> * file <name> <value> * passwd <name> <value> * checkbox <name> <value> [<checked>] * radio <name> <value> * select <name> <value> * submit [<name> [<value>]] * image [<name> [<value>]] * textarea <name> * <value> * /textarea */ void loadPreForm(void) { FILE *fp; Str line = NULL, textarea = NULL; struct pre_form *pf = NULL; struct pre_form_item *pi = NULL; int type = -1; char *name = NULL; PreForm = NULL; fp = openSecretFile(pre_form_file); if (fp == NULL) return; while (1) { char *p, *s, *arg; Regex *re_arg; line = Strfgets(fp); if (line->length == 0) break; if (textarea && !(!strncmp(line->ptr, "/textarea", 9) && IS_SPACE(line->ptr[9]))) { Strcat(textarea, line); continue; } Strchop(line); Strremovefirstspaces(line); p = line->ptr; if (*p == '#' || *p == '\0') continue; /* comment or empty line */ s = getWord(&p); if (!strcmp(s, "url")) { arg = getRegexWord((const char **)&p, &re_arg); if (!arg || !*arg) continue; p = getQWord(&p); pf = add_pre_form(pf, arg, re_arg, NULL, p); pi = pf->item; continue; } if (!pf) continue; arg = getWord(&p); if (!strcmp(s, "form")) { if (!arg || !*arg) continue; s = getQWord(&p); p = getQWord(&p); if (!p || !*p) { p = s; s = NULL; } if (pf->item) { struct pre_form *prev = pf; pf = add_pre_form(prev, "", NULL, s, p); /* copy previous URL */ pf->url = prev->url; pf->re_url = prev->re_url; } else { pf->name = s; pf->action = (p && *p) ? p : NULL; } pi = pf->item; continue; } if (!strcmp(s, "text")) type = FORM_INPUT_TEXT; else if (!strcmp(s, "file")) type = FORM_INPUT_FILE; else if (!strcmp(s, "passwd") || !strcmp(s, "password")) type = FORM_INPUT_PASSWORD; else if (!strcmp(s, "checkbox")) type = FORM_INPUT_CHECKBOX; else if (!strcmp(s, "radio")) type = FORM_INPUT_RADIO; else if (!strcmp(s, "submit")) type = FORM_INPUT_SUBMIT; else if (!strcmp(s, "image")) type = FORM_INPUT_IMAGE; else if (!strcmp(s, "select")) type = FORM_SELECT; else if (!strcmp(s, "textarea")) { type = FORM_TEXTAREA; name = Strnew_charp(arg)->ptr; textarea = Strnew(); continue; } else if (textarea && name && !strcmp(s, "/textarea")) { pi = add_pre_form_item(pf, pi, type, name, textarea->ptr, NULL); textarea = NULL; name = NULL; continue; } else continue; s = getQWord(&p); pi = add_pre_form_item(pf, pi, type, arg, s, getQWord(&p)); } fclose(fp); } void preFormUpdateBuffer(Buffer *buf) { struct pre_form *pf; struct pre_form_item *pi; int i; Anchor *a; FormList *fl; FormItemList *fi; #ifdef MENU_SELECT FormSelectOptionItem *opt; int j; #endif if (!buf || !buf->formitem || !PreForm) return; for (pf = PreForm; pf; pf = pf->next) { if (pf->re_url) { Str url = parsedURL2Str(&buf->currentURL); if (!RegexMatch(pf->re_url, url->ptr, url->length, 1)) continue; } else if (pf->url) { if (Strcmp_charp(parsedURL2Str(&buf->currentURL), pf->url)) continue; } else continue; for (i = 0; i < buf->formitem->nanchor; i++) { a = &buf->formitem->anchors[i]; fi = (FormItemList *)a->url; fl = fi->parent; if (pf->name && (!fl->name || strcmp(fl->name, pf->name))) continue; if (pf->action && (!fl->action || Strcmp_charp(fl->action, pf->action))) continue; for (pi = pf->item; pi; pi = pi->next) { if (pi->type != fi->type) continue; if (pi->type == FORM_INPUT_SUBMIT || pi->type == FORM_INPUT_IMAGE) { if ((!pi->name || !*pi->name || (fi->name && !Strcmp_charp(fi->name, pi->name))) && (!pi->value || !*pi->value || (fi->value && !Strcmp_charp(fi->value, pi->value)))) buf->submit = a; continue; } if (!pi->name || !fi->name || Strcmp_charp(fi->name, pi->name)) continue; switch (pi->type) { case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: fi->value = Strnew_charp(pi->value); formUpdateBuffer(a, buf, fi); break; case FORM_INPUT_CHECKBOX: if (pi->value && fi->value && !Strcmp_charp(fi->value, pi->value)) { fi->checked = pi->checked; formUpdateBuffer(a, buf, fi); } break; case FORM_INPUT_RADIO: if (pi->value && fi->value && !Strcmp_charp(fi->value, pi->value)) formRecheckRadio(a, buf, fi); break; #ifdef MENU_SELECT case FORM_SELECT: for (j = 0, opt = fi->select_option; opt != NULL; j++, opt = opt->next) { if (pi->value && opt->value && !Strcmp_charp(opt->value, pi->value)) { fi->selected = j; fi->value = opt->value; fi->label = opt->label; updateSelectOption(fi, fi->select_option); formUpdateBuffer(a, buf, fi); break; } } break; #endif } } } } }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_588_0
crossvul-cpp_data_bad_4826_1
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | 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 "zend_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(Z_STRVAL_P(a), Z_STRLEN_P(a), (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), PHP_WDDX_VERSION, 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 (Z_TYPE(((st_entry *)stack->elements[i])->data) != IS_UNDEF && ((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_resource *rsrc) { 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; zend_string *str; 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); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); smart_str_0(packet); str = zend_string_copy(packet->s); php_wddx_destructor(packet); return str; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval retval; zval *ent; zend_string *key; zend_ulong idx; int ret; if (vallen == 0) { return SUCCESS; } ZVAL_UNDEF(&retval); if ((ret = php_wddx_deserialize_ex(val, vallen, &retval)) == SUCCESS) { if (Z_TYPE(retval) != IS_ARRAY) { zval_dtor(&retval); return FAILURE; } ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(retval), idx, key, ent) { if (key == NULL) { key = zend_long_to_str(idx); } else { zend_string_addref(key); } if (php_set_session_var(key, ent, NULL)) { if (Z_REFCOUNTED_P(ent)) Z_ADDREF_P(ent); } PS_ADD_VAR(key); zend_string_release(key); } ZEND_HASH_FOREACH_END(); } 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, size_t comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { zend_string *escaped = php_escape_html_entities( comment, comment_len, 0, ENT_QUOTES, NULL); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, ZSTR_VAL(escaped), ZSTR_LEN(escaped)); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); zend_string_release(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) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { zend_string *buf = php_escape_html_entities( (unsigned char *) Z_STRVAL_P(var), Z_STRLEN_P(var), 0, ENT_QUOTES, NULL); php_wddx_add_chunk_ex(packet, ZSTR_VAL(buf), ZSTR_LEN(buf)); zend_string_release(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]; zend_string *str = zval_get_string(var); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, ZSTR_VAL(str)); zend_string_release(str); 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_TYPE_P(var) == IS_TRUE ? 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; zend_string *key; zend_ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; zend_class_entry *ce; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); ce = Z_OBJCE_P(obj); if (!ce || ce->serialize || ce->unserialize) { php_error_docref(NULL, E_WARNING, "Class %s can not be serialized", ZSTR_VAL(class_name)); PHP_CLEANUP_CLASS_ATTRIBUTES(); return; } ZVAL_STRING(&fname, "__sleep"); /* * 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) == SUCCESS) { if (!Z_ISUNDEF(retval) && (sleephash = HASH_OF(&retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); 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, ZSTR_VAL(class_name), ZSTR_LEN(class_name)); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = Z_OBJPROP_P(obj); ZEND_HASH_FOREACH_VAL(sleephash, varname) { if (Z_TYPE_P(varname) != IS_STRING) { php_error_docref(NULL, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if ((ent = zend_hash_find(objhash, Z_STR_P(varname))) != NULL) { php_wddx_serialize_var(packet, ent, Z_STR_P(varname)); } } ZEND_HASH_FOREACH_END(); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { 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, ZSTR_VAL(class_name), ZSTR_LEN(class_name)); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = Z_OBJPROP_P(obj); ZEND_HASH_FOREACH_KEY_VAL(objhash, idx, key, ent) { if (ent == obj) { continue; } if (key) { const char *class_name, *prop_name; size_t prop_name_len; zend_string *tmp; zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len); tmp = zend_string_init(prop_name, prop_name_len, 0); php_wddx_serialize_var(packet, ent, tmp); zend_string_release(tmp); } else { key = zend_long_to_str(idx); php_wddx_serialize_var(packet, ent, key); zend_string_release(key); } } ZEND_HASH_FOREACH_END(); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } PHP_CLEANUP_CLASS_ATTRIBUTES(); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval *ent; zend_string *key; int is_struct = 0; zend_ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; zend_ulong ind = 0; target_hash = Z_ARRVAL_P(arr); ZEND_HASH_FOREACH_KEY(target_hash, idx, key) { if (key) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } ZEND_HASH_FOREACH_END(); 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); } ZEND_HASH_FOREACH_KEY_VAL(target_hash, idx, key, ent) { if (ent == arr) { continue; } if (is_struct) { if (key) { php_wddx_serialize_var(packet, ent, key); } else { key = zend_long_to_str(idx); php_wddx_serialize_var(packet, ent, key); zend_string_release(key); } } else { php_wddx_serialize_var(packet, ent, NULL); } } ZEND_HASH_FOREACH_END(); 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, zend_string *name) { HashTable *ht; if (name) { char *tmp_buf; zend_string *name_esc = php_escape_html_entities((unsigned char *) ZSTR_VAL(name), ZSTR_LEN(name), 0, ENT_QUOTES, NULL); tmp_buf = emalloc(ZSTR_LEN(name_esc) + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, ZSTR_LEN(name_esc) + sizeof(WDDX_VAR_S), WDDX_VAR_S, ZSTR_VAL(name_esc)); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); zend_string_release(name_esc); } if (Z_TYPE_P(var) == IS_INDIRECT) { var = Z_INDIRECT_P(var); } ZVAL_DEREF(var); switch (Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_TRUE: case IS_FALSE: 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->u.v.nApplyCount > 1) { php_error_docref(NULL, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } if (ZEND_HASH_APPLY_PROTECTION(ht)) { ht->u.v.nApplyCount++; } php_wddx_serialize_array(packet, var); if (ZEND_HASH_APPLY_PROTECTION(ht)) { ht->u.v.nApplyCount--; } break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->u.v.nApplyCount > 1) { php_error_docref(NULL, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->u.v.nApplyCount++; php_wddx_serialize_object(packet, var); ht->u.v.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; if (Z_TYPE_P(name_var) == IS_STRING) { zend_array *symbol_table = zend_rebuild_symbol_table(); if ((val = zend_hash_find(symbol_table, Z_STR_P(name_var))) != NULL) { if (Z_TYPE_P(val) == IS_INDIRECT) { val = Z_INDIRECT_P(val); } php_wddx_serialize_var(packet, val, Z_STR_P(name_var)); } } 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->u.v.nApplyCount > 1) { php_error_docref(NULL, E_WARNING, "recursion detected"); return; } if (Z_IMMUTABLE_P(name_var)) { ZEND_HASH_FOREACH_VAL(target_hash, val) { php_wddx_add_var(packet, val); } ZEND_HASH_FOREACH_END(); } else { ZEND_HASH_FOREACH_VAL(target_hash, val) { if (is_array) { target_hash->u.v.nApplyCount++; } ZVAL_DEREF(val); php_wddx_add_var(packet, val); if (is_array) { target_hash->u.v.nApplyCount--; } } ZEND_HASH_FOREACH_END(); } } } /* }}} */ /* {{{ 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((char *)name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp((char *)atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp((char *)name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ZVAL_STR(&ent.data, ZSTR_EMPTY_ALLOC()); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ZVAL_STR(&ent.data, ZSTR_EMPTY_ALLOC()); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)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((char *)atts[i+1], NULL, 16)); php_wddx_process_data(user_data, (XML_Char *) tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp((char *)name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ZVAL_LONG(&ent.data, 0); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_TRUE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen((char *)atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp((char *)name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ZVAL_NULL(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; array_init(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; array_init(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup((char *)atts[i+1]); break; } } } else if (!strcmp((char *)name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; array_init(&ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval tmp; char *key; const char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen((char *)atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); array_init(&tmp); add_assoc_zval_ex(&ent.data, key, p2 - p1, &tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { array_init(&tmp); add_assoc_zval_ex(&ent.data, p1, endp - p1, &tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ZVAL_UNDEF(&ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp((char *)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 && (field = zend_hash_str_find(Z_ARRVAL(recordset->data), (char*)atts[i+1], strlen((char *)atts[i+1]))) != NULL) { ZVAL_COPY_VALUE(&ent.data, field); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp((char *)name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ZVAL_LONG(&ent.data, 0); 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; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ object_init_ex(&obj, pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)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; if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_BINARY: case ST_STRING: if (Z_STRLEN(ent->data) == 0) { zval_ptr_dtor(&ent->data); ZVAL_STRINGL(&ent->data, (char *)s, len); } else { Z_STR(ent->data) = zend_string_extend(Z_STR(ent->data), Z_STRLEN(ent->data) + len, 0); memcpy(Z_STRVAL(ent->data) + Z_STRLEN(ent->data) - len, (char *)s, len); Z_STRVAL(ent->data)[Z_STRLEN(ent->data)] = '\0'; } break; case ST_NUMBER: ZVAL_STRINGL(&ent->data, (char *)s, len); convert_scalar_to_number(&ent->data); break; case ST_BOOLEAN: if (!strcmp((char *)s, "true")) { ZVAL_TRUE(&ent->data); } else if (!strcmp((char *)s, "false")) { ZVAL_FALSE(&ent->data); } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ZVAL_UNDEF(&ent->data); } break; case ST_DATETIME: { zend_string *str; if (Z_TYPE(ent->data) == IS_STRING) { str = zend_string_safe_alloc(Z_STRLEN(ent->data), 1, len, 0); memcpy(ZSTR_VAL(str), Z_STRVAL(ent->data), Z_STRLEN(ent->data)); memcpy(ZSTR_VAL(str) + Z_STRLEN(ent->data), s, len); ZSTR_VAL(str)[ZSTR_LEN(str)] = '\0'; zval_dtor(&ent->data); } else { str = zend_string_init((char *)s, len, 0); } ZVAL_LONG(&ent->data, php_parse_date(ZSTR_VAL(str), NULL)); /* date out of range < 1969 or > 2038 */ if (Z_LVAL(ent->data) == -1) { ZVAL_STR_COPY(&ent->data, str); } zend_string_release(str); } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(const char *value, size_t vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate((XML_Char *) "UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); /* XXX value should be parsed in the loop to exhaust size_t */ XML_Parse(parser, (const XML_Char *) value, (int)vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if (Z_ISUNDEF(ent->data)) { retval = FAILURE; } else { ZVAL_COPY(return_value, &ent->data); 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; size_t comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS(), "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); php_wddx_packet_end(packet); smart_str_0(packet); RETVAL_STR_COPY(packet->s); php_wddx_destructor(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(), "+", &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++) { zval *arg; if (!Z_ISREF(args[i])) { arg = &args[i]; } else { arg = Z_REFVAL(args[i]); } if (Z_TYPE_P(arg) != IS_ARRAY && Z_TYPE_P(arg) != IS_OBJECT) { convert_to_string_ex(arg); } php_wddx_add_var(packet, arg); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); smart_str_0(packet); RETVAL_STR_COPY(packet->s); php_wddx_destructor(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = ecalloc(1, sizeof(smart_str)); 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; size_t comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|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); RETURN_RES(zend_register_resource(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(), "r", &packet_id) == FAILURE) { return; } if ((packet = (wddx_packet *)zend_fetch_resource(Z_RES_P(packet_id), "WDDX packet ID", le_wddx)) == NULL) { RETURN_FALSE; } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); smart_str_0(packet); RETVAL_STR_COPY(packet->s); zend_list_close(Z_RES_P(packet_id)); } /* }}} */ /* {{{ proto bool 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(), "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if ((packet = (wddx_packet *)zend_fetch_resource(Z_RES_P(packet_id), "WDDX packet ID", le_wddx)) == NULL) { RETURN_FALSE; } for (i=0; i<num_args; i++) { zval *arg; if (!Z_ISREF(args[i])) { arg = &args[i]; } else { arg = Z_REFVAL(args[i]); } if (Z_TYPE_P(arg) != IS_ARRAY && Z_TYPE_P(arg) != IS_OBJECT) { convert_to_string_ex(arg); } php_wddx_add_var(packet, arg); } RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; php_stream *stream = NULL; zend_string *payload = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STR_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, packet); if (stream) { payload = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload == NULL) { return; } php_wddx_deserialize_ex(ZSTR_VAL(payload), ZSTR_LEN(payload), return_value); if (stream) { efree(payload); } } /* }}} */ #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/bad_4826_1
crossvul-cpp_data_bad_99_2
/* * Packet matching code. * * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org> * Copyright (c) 2006-2010 Patrick McHardy <kaber@trash.net> * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/capability.h> #include <linux/in.h> #include <linux/skbuff.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/netdevice.h> #include <linux/module.h> #include <linux/poison.h> #include <linux/icmpv6.h> #include <net/ipv6.h> #include <net/compat.h> #include <linux/uaccess.h> #include <linux/mutex.h> #include <linux/proc_fs.h> #include <linux/err.h> #include <linux/cpumask.h> #include <linux/netfilter_ipv6/ip6_tables.h> #include <linux/netfilter/x_tables.h> #include <net/netfilter/nf_log.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>"); MODULE_DESCRIPTION("IPv6 packet filter"); void *ip6t_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(ip6t, IP6T); } EXPORT_SYMBOL_GPL(ip6t_alloc_initial_table); /* Returns whether matches rule or not. */ /* Performance critical - called for every packet */ static inline bool ip6_packet_match(const struct sk_buff *skb, const char *indev, const char *outdev, const struct ip6t_ip6 *ip6info, unsigned int *protoff, int *fragoff, bool *hotdrop) { unsigned long ret; const struct ipv6hdr *ipv6 = ipv6_hdr(skb); if (NF_INVF(ip6info, IP6T_INV_SRCIP, ipv6_masked_addr_cmp(&ipv6->saddr, &ip6info->smsk, &ip6info->src)) || NF_INVF(ip6info, IP6T_INV_DSTIP, ipv6_masked_addr_cmp(&ipv6->daddr, &ip6info->dmsk, &ip6info->dst))) return false; ret = ifname_compare_aligned(indev, ip6info->iniface, ip6info->iniface_mask); if (NF_INVF(ip6info, IP6T_INV_VIA_IN, ret != 0)) return false; ret = ifname_compare_aligned(outdev, ip6info->outiface, ip6info->outiface_mask); if (NF_INVF(ip6info, IP6T_INV_VIA_OUT, ret != 0)) return false; /* ... might want to do something with class and flowlabel here ... */ /* look for the desired protocol header */ if (ip6info->flags & IP6T_F_PROTO) { int protohdr; unsigned short _frag_off; protohdr = ipv6_find_hdr(skb, protoff, -1, &_frag_off, NULL); if (protohdr < 0) { if (_frag_off == 0) *hotdrop = true; return false; } *fragoff = _frag_off; if (ip6info->proto == protohdr) { if (ip6info->invflags & IP6T_INV_PROTO) return false; return true; } /* We need match for the '-p all', too! */ if ((ip6info->proto != 0) && !(ip6info->invflags & IP6T_INV_PROTO)) return false; } return true; } /* should be ip6 safe */ static bool ip6_checkentry(const struct ip6t_ip6 *ipv6) { if (ipv6->flags & ~IP6T_F_MASK) return false; if (ipv6->invflags & ~IP6T_INV_MASK) return false; return true; } static unsigned int ip6t_error(struct sk_buff *skb, const struct xt_action_param *par) { net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline struct ip6t_entry * get_entry(const void *base, unsigned int offset) { return (struct ip6t_entry *)(base + offset); } /* All zeroes == unconditional rule. */ /* Mildly perf critical (only if packet tracing is on) */ static inline bool unconditional(const struct ip6t_entry *e) { static const struct ip6t_ip6 uncond; return e->target_offset == sizeof(struct ip6t_entry) && memcmp(&e->ipv6, &uncond, sizeof(uncond)) == 0; } static inline const struct xt_entry_target * ip6t_get_target_c(const struct ip6t_entry *e) { return ip6t_get_target((struct ip6t_entry *)e); } #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* This cries for unification! */ static const char *const hooknames[] = { [NF_INET_PRE_ROUTING] = "PREROUTING", [NF_INET_LOCAL_IN] = "INPUT", [NF_INET_FORWARD] = "FORWARD", [NF_INET_LOCAL_OUT] = "OUTPUT", [NF_INET_POST_ROUTING] = "POSTROUTING", }; enum nf_ip_trace_comments { NF_IP6_TRACE_COMMENT_RULE, NF_IP6_TRACE_COMMENT_RETURN, NF_IP6_TRACE_COMMENT_POLICY, }; static const char *const comments[] = { [NF_IP6_TRACE_COMMENT_RULE] = "rule", [NF_IP6_TRACE_COMMENT_RETURN] = "return", [NF_IP6_TRACE_COMMENT_POLICY] = "policy", }; static const struct nf_loginfo trace_loginfo = { .type = NF_LOG_TYPE_LOG, .u = { .log = { .level = LOGLEVEL_WARNING, .logflags = NF_LOG_DEFAULT_MASK, }, }, }; /* Mildly perf critical (only if packet tracing is on) */ static inline int get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e, const char *hookname, const char **chainname, const char **comment, unsigned int *rulenum) { const struct xt_standard_target *t = (void *)ip6t_get_target_c(s); if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) { /* Head of user chain: ERROR target with chainname */ *chainname = t->target.data; (*rulenum) = 0; } else if (s == e) { (*rulenum)++; if (unconditional(s) && strcmp(t->target.u.kernel.target->name, XT_STANDARD_TARGET) == 0 && t->verdict < 0) { /* Tail of chains: STANDARD target (return/policy) */ *comment = *chainname == hookname ? comments[NF_IP6_TRACE_COMMENT_POLICY] : comments[NF_IP6_TRACE_COMMENT_RETURN]; } return 1; } else (*rulenum)++; return 0; } static void trace_packet(struct net *net, const struct sk_buff *skb, unsigned int hook, const struct net_device *in, const struct net_device *out, const char *tablename, const struct xt_table_info *private, const struct ip6t_entry *e) { const struct ip6t_entry *root; const char *hookname, *chainname, *comment; const struct ip6t_entry *iter; unsigned int rulenum = 0; root = get_entry(private->entries, private->hook_entry[hook]); hookname = chainname = hooknames[hook]; comment = comments[NF_IP6_TRACE_COMMENT_RULE]; xt_entry_foreach(iter, root, private->size - private->hook_entry[hook]) if (get_chainname_rulenum(iter, e, hookname, &chainname, &comment, &rulenum) != 0) break; nf_log_trace(net, AF_INET6, hook, skb, in, out, &trace_loginfo, "TRACE: %s:%s:%s:%u ", tablename, chainname, comment, rulenum); } #endif static inline struct ip6t_entry * ip6t_next_entry(const struct ip6t_entry *entry) { return (void *)entry + entry->next_offset; } /* Returns one of the generic firewall policies, like NF_ACCEPT. */ unsigned int ip6t_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)))); /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; const void *table_base; struct ip6t_entry *e, **jumpstack; unsigned int stackidx, cpu; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; /* Initialization */ stackidx = 0; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ acpar.hotdrop = false; acpar.state = state; WARN_ON(!(table->valid_hooks & (1 << hook))); 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 ip6t_entry **)private->jumpstack[cpu]; /* Switch to alternate jumpstack if we're being invoked via TEE. * TEE issues XT_CONTINUE verdict on original skb so we must not * clobber the jumpstack. * * For recursion via REJECT or SYNPROXY the stack will be clobbered * but it is no problem since absolute verdict is issued by these. */ if (static_key_false(&xt_tee_enabled)) jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated); e = get_entry(table_base, private->hook_entry[hook]); do { const struct xt_entry_target *t; const struct xt_entry_match *ematch; struct xt_counters *counter; WARN_ON(!e); acpar.thoff = 0; if (!ip6_packet_match(skb, indev, outdev, &e->ipv6, &acpar.thoff, &acpar.fragoff, &acpar.hotdrop)) { no_match: e = ip6t_next_entry(e); continue; } xt_ematch_foreach(ematch, e) { acpar.match = ematch->u.kernel.match; acpar.matchinfo = ematch->data; if (!acpar.match->match(skb, &acpar)) goto no_match; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, skb->len, 1); t = ip6t_get_target_c(e); WARN_ON(!t->u.kernel.target); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* The packet is traced: log it */ if (unlikely(skb->nf_trace)) trace_packet(state->net, skb, hook, state->in, state->out, table->name, private, e); #endif /* 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 = ip6t_next_entry(jumpstack[--stackidx]); continue; } if (table_base + v != ip6t_next_entry(e) && !(e->ipv6.flags & IP6T_F_GOTO)) { 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) e = ip6t_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; } /* 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_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ip6t_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 *)ip6t_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) return 0; e->comefrom |= ((1 << hook) | (1 << NF_INET_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_INET_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 void cleanup_match(struct xt_entry_match *m, struct net *net) { struct xt_mtdtor_param par; par.net = net; par.match = m->u.kernel.match; par.matchinfo = m->data; par.family = NFPROTO_IPV6; if (par.match->destroy != NULL) par.match->destroy(&par); module_put(par.match->me); } static int check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { const struct ip6t_ip6 *ipv6 = par->entryinfo; par->match = m->u.kernel.match; par->matchinfo = m->data; return xt_check_match(par, m->u.match_size - sizeof(*m), ipv6->proto, ipv6->invflags & IP6T_INV_PROTO); } static int find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { struct xt_match *match; int ret; match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) return PTR_ERR(match); m->u.kernel.match = match; ret = check_match(m, par); if (ret) goto err; return 0; err: module_put(m->u.kernel.match->me); return ret; } static int check_target(struct ip6t_entry *e, struct net *net, const char *name) { struct xt_entry_target *t = ip6t_get_target(e); struct xt_tgchk_param par = { .net = net, .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_IPV6, }; t = ip6t_get_target(e); return xt_check_target(&par, t->u.target_size - sizeof(*t), e->ipv6.proto, e->ipv6.invflags & IP6T_INV_PROTO); } static int find_check_entry(struct ip6t_entry *e, struct net *net, 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; unsigned int j; struct xt_mtchk_param mtpar; struct xt_entry_match *ematch; if (!xt_percpu_counter_alloc(alloc_state, &e->counters)) return -ENOMEM; j = 0; mtpar.net = net; mtpar.table = name; mtpar.entryinfo = &e->ipv6; mtpar.hook_mask = e->comefrom; mtpar.family = NFPROTO_IPV6; xt_ematch_foreach(ematch, e) { ret = find_check_match(ematch, &mtpar); if (ret != 0) goto cleanup_matches; ++j; } t = ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { ret = PTR_ERR(target); goto cleanup_matches; } t->u.kernel.target = target; ret = check_target(e, net, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); cleanup_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; cleanup_match(ematch, net); } xt_percpu_counter_free(&e->counters); return ret; } static bool check_underflow(const struct ip6t_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = ip6t_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 int check_entry_size_and_hooks(struct ip6t_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 ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) return -EINVAL; if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) return -EINVAL; if (!ip6_checkentry(&e->ipv6)) 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_INET_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 void cleanup_entry(struct ip6t_entry *e, struct net *net) { struct xt_tgdtor_param par; struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) cleanup_match(ematch, net); t = ip6t_get_target(e); par.net = net; par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_IPV6; 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 net *net, struct xt_table_info *newinfo, void *entry0, const struct ip6t_replace *repl) { struct xt_percpu_counter_alloc_state alloc_state = { 0 }; struct ip6t_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_INET_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(ip6t_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_INET_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, net, 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, net); } 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 ip6t_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 ip6t_entry *iter; unsigned int cpu, i; for_each_possible_cpu(cpu) { i = 0; xt_entry_foreach(iter, t->entries, t->size) { const 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 ip6t_entry *e; struct xt_counters *counters; const struct xt_table_info *private = table->private; int ret = 0; const 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++){ unsigned int i; const struct xt_entry_match *m; 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 ip6t_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } for (i = sizeof(struct ip6t_entry); i < e->target_offset; i += m->u.match_size) { m = (void *)e + i; if (xt_match_to_user(m, userptr + off + i)) { ret = -EFAULT; goto free_counters; } } t = ip6t_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(AF_INET6, 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(AF_INET6, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct ip6t_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_match *ematch; const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - base; xt_ematch_foreach(ematch, e) off += xt_compat_match_offset(ematch->u.kernel.match); t = ip6t_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_INET_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct ip6t_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct ip6t_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 ip6t_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(AF_INET6, 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 ip6t_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(AF_INET6); #endif t = xt_request_find_table_lock(net, AF_INET6, name); if (!IS_ERR(t)) { struct ip6t_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(AF_INET6); 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(AF_INET6); #endif return ret; } static int get_entries(struct net *net, struct ip6t_get_entries __user *uptr, const int *len) { int ret; struct ip6t_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 ip6t_get_entries) + get.size) return -EINVAL; get.name[sizeof(get.name) - 1] = '\0'; t = xt_find_table_lock(net, AF_INET6, get.name); if (!IS_ERR(t)) { 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; struct ip6t_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, AF_INET6, 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 */ xt_entry_foreach(iter, oldinfo->entries, oldinfo->size) cleanup_entry(iter, net); 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("ip6tables: 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 ip6t_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ip6t_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(net, 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, net); 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 ip6t_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, AF_INET6, 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_ip6t_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_INET_NUMHOOKS]; u32 underflow[NF_INET_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; /* struct xt_counters * */ struct compat_ip6t_entry entries[0]; }; static int compat_copy_entry_to_user(struct ip6t_entry *e, void __user **dstptr, unsigned int *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_ip6t_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; const struct xt_entry_match *ematch; int ret = 0; origsize = *size; ce = *dstptr; if (copy_to_user(ce, e, sizeof(struct ip6t_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_ip6t_entry); *size -= sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); xt_ematch_foreach(ematch, e) { ret = xt_compat_match_to_user(ematch, dstptr, size); if (ret != 0) return ret; } target_offset = e->target_offset - (origsize - *size); t = ip6t_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_find_calc_match(struct xt_entry_match *m, const struct ip6t_ip6 *ipv6, int *size) { struct xt_match *match; match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) return PTR_ERR(match); m->u.kernel.match = match; *size += xt_compat_match_offset(match); return 0; } static void compat_release_entry(struct compat_ip6t_entry *e) { struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) module_put(ematch->u.kernel.match->me); t = compat_ip6t_get_target(e); module_put(t->u.kernel.target->me); } static int check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off; if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) return -EINVAL; if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) return -EINVAL; if (!ip6_checkentry(&e->ipv6)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } static void compat_copy_entry_from_user(struct compat_ip6t_entry *e, void **dstptr, unsigned int *size, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct ip6t_entry *de; unsigned int origsize; int h; struct xt_entry_match *ematch; origsize = *size; de = *dstptr; memcpy(de, e, sizeof(struct ip6t_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct ip6t_entry); *size += sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); xt_ematch_foreach(ematch, e) xt_compat_match_from_user(ematch, dstptr, size); de->target_offset = e->target_offset - (origsize - *size); t = compat_ip6t_get_target(e); xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_INET_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 net *net, struct xt_table_info **pinfo, void **pentry0, const struct compat_ip6t_replace *compatr) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_ip6t_entry *iter0; struct ip6t_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(AF_INET6); xt_compat_init_offsets(AF_INET6, 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_INET_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(AF_INET6); xt_compat_unlock(AF_INET6); memcpy(&repl, compatr, sizeof(*compatr)); for (i = 0; i < NF_INET_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(net, 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(AF_INET6); xt_compat_unlock(AF_INET6); 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_ip6t_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ip6t_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(net, &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, net); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_ip6t_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 IP6T_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case IP6T_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: ret = -EINVAL; } return ret; } struct compat_ip6t_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_ip6t_entry entrytable[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 ip6t_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; } static int compat_get_entries(struct net *net, struct compat_ip6t_get_entries __user *uptr, int *len) { int ret; struct compat_ip6t_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_ip6t_get_entries) + get.size) return -EINVAL; get.name[sizeof(get.name) - 1] = '\0'; xt_compat_lock(AF_INET6); t = xt_find_table_lock(net, AF_INET6, 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(AF_INET6); module_put(t->me); xt_table_unlock(t); } else ret = PTR_ERR(t); xt_compat_unlock(AF_INET6); return ret; } static int do_ip6t_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_ip6t_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 IP6T_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case IP6T_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_ip6t_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_ip6t_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 IP6T_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case IP6T_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: ret = -EINVAL; } return ret; } static int do_ip6t_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 IP6T_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case IP6T_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case IP6T_SO_GET_REVISION_MATCH: case IP6T_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; int target; 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; if (cmd == IP6T_SO_GET_REVISION_TARGET) target = 1; else target = 0; try_then_request_module(xt_find_revision(AF_INET6, rev.name, rev.revision, target, &ret), "ip6t_%s", rev.name); break; } default: ret = -EINVAL; } return ret; } static void __ip6t_unregister_table(struct net *net, struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct ip6t_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, net); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int ip6t_register_table(struct net *net, const struct xt_table *table, const struct ip6t_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(net, 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) { __ip6t_unregister_table(net, new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void ip6t_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)); __ip6t_unregister_table(net, table); } /* Returns 1 if the type and code is matched by the range, 0 otherwise */ static inline bool icmp6_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code, u_int8_t type, u_int8_t code, bool invert) { return (type == test_type && code >= min_code && code <= max_code) ^ invert; } static bool icmp6_match(const struct sk_buff *skb, struct xt_action_param *par) { const struct icmp6hdr *ic; struct icmp6hdr _icmph; const struct ip6t_icmp *icmpinfo = par->matchinfo; /* Must not be a fragment. */ if (par->fragoff != 0) return false; ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph); if (ic == NULL) { /* We've been asked to examine this packet, and we * can't. Hence, no choice but to drop. */ par->hotdrop = true; return false; } return icmp6_type_code_match(icmpinfo->type, icmpinfo->code[0], icmpinfo->code[1], ic->icmp6_type, ic->icmp6_code, !!(icmpinfo->invflags&IP6T_ICMP_INV)); } /* Called when user tries to insert an entry of this type. */ static int icmp6_checkentry(const struct xt_mtchk_param *par) { const struct ip6t_icmp *icmpinfo = par->matchinfo; /* Must specify no unknown invflags */ return (icmpinfo->invflags & ~IP6T_ICMP_INV) ? -EINVAL : 0; } /* The built-in targets: standard (NULL) and error. */ static struct xt_target ip6t_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_IPV6, #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 = ip6t_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_IPV6, }, }; static struct nf_sockopt_ops ip6t_sockopts = { .pf = PF_INET6, .set_optmin = IP6T_BASE_CTL, .set_optmax = IP6T_SO_SET_MAX+1, .set = do_ip6t_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_ip6t_set_ctl, #endif .get_optmin = IP6T_BASE_CTL, .get_optmax = IP6T_SO_GET_MAX+1, .get = do_ip6t_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_ip6t_get_ctl, #endif .owner = THIS_MODULE, }; static struct xt_match ip6t_builtin_mt[] __read_mostly = { { .name = "icmp6", .match = icmp6_match, .matchsize = sizeof(struct ip6t_icmp), .checkentry = icmp6_checkentry, .proto = IPPROTO_ICMPV6, .family = NFPROTO_IPV6, }, }; static int __net_init ip6_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_IPV6); } static void __net_exit ip6_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_IPV6); } static struct pernet_operations ip6_tables_net_ops = { .init = ip6_tables_net_init, .exit = ip6_tables_net_exit, }; static int __init ip6_tables_init(void) { int ret; ret = register_pernet_subsys(&ip6_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(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg)); if (ret < 0) goto err2; ret = xt_register_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt)); if (ret < 0) goto err4; /* Register setsockopt */ ret = nf_register_sockopt(&ip6t_sockopts); if (ret < 0) goto err5; return 0; err5: xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt)); err4: xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg)); err2: unregister_pernet_subsys(&ip6_tables_net_ops); err1: return ret; } static void __exit ip6_tables_fini(void) { nf_unregister_sockopt(&ip6t_sockopts); xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt)); xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg)); unregister_pernet_subsys(&ip6_tables_net_ops); } EXPORT_SYMBOL(ip6t_register_table); EXPORT_SYMBOL(ip6t_unregister_table); EXPORT_SYMBOL(ip6t_do_table); module_init(ip6_tables_init); module_exit(ip6_tables_fini);
./CrossVul/dataset_final_sorted/CWE-476/c/bad_99_2
crossvul-cpp_data_bad_99_1
/* * Packet matching code. * * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org> * Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.net> * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/cache.h> #include <linux/capability.h> #include <linux/skbuff.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/netdevice.h> #include <linux/module.h> #include <linux/icmp.h> #include <net/ip.h> #include <net/compat.h> #include <linux/uaccess.h> #include <linux/mutex.h> #include <linux/proc_fs.h> #include <linux/err.h> #include <linux/cpumask.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_log.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>"); MODULE_DESCRIPTION("IPv4 packet filter"); void *ipt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(ipt, IPT); } EXPORT_SYMBOL_GPL(ipt_alloc_initial_table); /* Returns whether matches rule or not. */ /* Performance critical - called for every packet */ static inline bool ip_packet_match(const struct iphdr *ip, const char *indev, const char *outdev, const struct ipt_ip *ipinfo, int isfrag) { unsigned long ret; if (NF_INVF(ipinfo, IPT_INV_SRCIP, (ip->saddr & ipinfo->smsk.s_addr) != ipinfo->src.s_addr) || NF_INVF(ipinfo, IPT_INV_DSTIP, (ip->daddr & ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr)) return false; ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask); if (NF_INVF(ipinfo, IPT_INV_VIA_IN, ret != 0)) return false; ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask); if (NF_INVF(ipinfo, IPT_INV_VIA_OUT, ret != 0)) return false; /* Check specific protocol */ if (ipinfo->proto && NF_INVF(ipinfo, IPT_INV_PROTO, ip->protocol != ipinfo->proto)) return false; /* If we have a fragment rule but the packet is not a fragment * then we return zero */ if (NF_INVF(ipinfo, IPT_INV_FRAG, (ipinfo->flags & IPT_F_FRAG) && !isfrag)) return false; return true; } static bool ip_checkentry(const struct ipt_ip *ip) { if (ip->flags & ~IPT_F_MASK) return false; if (ip->invflags & ~IPT_INV_MASK) return false; return true; } static unsigned int ipt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo); return NF_DROP; } /* Performance critical */ static inline struct ipt_entry * get_entry(const void *base, unsigned int offset) { return (struct ipt_entry *)(base + offset); } /* All zeroes == unconditional rule. */ /* Mildly perf critical (only if packet tracing is on) */ static inline bool unconditional(const struct ipt_entry *e) { static const struct ipt_ip uncond; return e->target_offset == sizeof(struct ipt_entry) && memcmp(&e->ip, &uncond, sizeof(uncond)) == 0; } /* for const-correctness */ static inline const struct xt_entry_target * ipt_get_target_c(const struct ipt_entry *e) { return ipt_get_target((struct ipt_entry *)e); } #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) static const char *const hooknames[] = { [NF_INET_PRE_ROUTING] = "PREROUTING", [NF_INET_LOCAL_IN] = "INPUT", [NF_INET_FORWARD] = "FORWARD", [NF_INET_LOCAL_OUT] = "OUTPUT", [NF_INET_POST_ROUTING] = "POSTROUTING", }; enum nf_ip_trace_comments { NF_IP_TRACE_COMMENT_RULE, NF_IP_TRACE_COMMENT_RETURN, NF_IP_TRACE_COMMENT_POLICY, }; static const char *const comments[] = { [NF_IP_TRACE_COMMENT_RULE] = "rule", [NF_IP_TRACE_COMMENT_RETURN] = "return", [NF_IP_TRACE_COMMENT_POLICY] = "policy", }; static const struct nf_loginfo trace_loginfo = { .type = NF_LOG_TYPE_LOG, .u = { .log = { .level = 4, .logflags = NF_LOG_DEFAULT_MASK, }, }, }; /* Mildly perf critical (only if packet tracing is on) */ static inline int get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e, const char *hookname, const char **chainname, const char **comment, unsigned int *rulenum) { const struct xt_standard_target *t = (void *)ipt_get_target_c(s); if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) { /* Head of user chain: ERROR target with chainname */ *chainname = t->target.data; (*rulenum) = 0; } else if (s == e) { (*rulenum)++; if (unconditional(s) && strcmp(t->target.u.kernel.target->name, XT_STANDARD_TARGET) == 0 && t->verdict < 0) { /* Tail of chains: STANDARD target (return/policy) */ *comment = *chainname == hookname ? comments[NF_IP_TRACE_COMMENT_POLICY] : comments[NF_IP_TRACE_COMMENT_RETURN]; } return 1; } else (*rulenum)++; return 0; } static void trace_packet(struct net *net, const struct sk_buff *skb, unsigned int hook, const struct net_device *in, const struct net_device *out, const char *tablename, const struct xt_table_info *private, const struct ipt_entry *e) { const struct ipt_entry *root; const char *hookname, *chainname, *comment; const struct ipt_entry *iter; unsigned int rulenum = 0; root = get_entry(private->entries, private->hook_entry[hook]); hookname = chainname = hooknames[hook]; comment = comments[NF_IP_TRACE_COMMENT_RULE]; xt_entry_foreach(iter, root, private->size - private->hook_entry[hook]) if (get_chainname_rulenum(iter, e, hookname, &chainname, &comment, &rulenum) != 0) break; nf_log_trace(net, AF_INET, hook, skb, in, out, &trace_loginfo, "TRACE: %s:%s:%s:%u ", tablename, chainname, comment, rulenum); } #endif static inline struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry) { return (void *)entry + entry->next_offset; } /* Returns one of the generic firewall policies, like NF_ACCEPT. */ unsigned int ipt_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)))); const struct iphdr *ip; /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; const void *table_base; struct ipt_entry *e, **jumpstack; unsigned int stackidx, cpu; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; /* Initialization */ stackidx = 0; ip = ip_hdr(skb); indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET; acpar.thoff = ip_hdrlen(skb); acpar.hotdrop = false; acpar.state = state; WARN_ON(!(table->valid_hooks & (1 << hook))); 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 ipt_entry **)private->jumpstack[cpu]; /* Switch to alternate jumpstack if we're being invoked via TEE. * TEE issues XT_CONTINUE verdict on original skb so we must not * clobber the jumpstack. * * For recursion via REJECT or SYNPROXY the stack will be clobbered * but it is no problem since absolute verdict is issued by these. */ if (static_key_false(&xt_tee_enabled)) jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated); e = get_entry(table_base, private->hook_entry[hook]); do { const struct xt_entry_target *t; const struct xt_entry_match *ematch; struct xt_counters *counter; WARN_ON(!e); if (!ip_packet_match(ip, indev, outdev, &e->ip, acpar.fragoff)) { no_match: e = ipt_next_entry(e); continue; } xt_ematch_foreach(ematch, e) { acpar.match = ematch->u.kernel.match; acpar.matchinfo = ematch->data; if (!acpar.match->match(skb, &acpar)) goto no_match; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, skb->len, 1); t = ipt_get_target(e); WARN_ON(!t->u.kernel.target); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* The packet is traced: log it */ if (unlikely(skb->nf_trace)) trace_packet(state->net, skb, hook, state->in, state->out, table->name, private, e); #endif /* 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 = ipt_next_entry(e); } continue; } if (table_base + v != ipt_next_entry(e) && !(e->ip.flags & IPT_F_GOTO)) 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. */ ip = ip_hdr(skb); e = ipt_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; } /* 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_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_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 *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) return 0; e->comefrom |= ((1 << hook) | (1 << NF_INET_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_INET_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 void cleanup_match(struct xt_entry_match *m, struct net *net) { struct xt_mtdtor_param par; par.net = net; par.match = m->u.kernel.match; par.matchinfo = m->data; par.family = NFPROTO_IPV4; if (par.match->destroy != NULL) par.match->destroy(&par); module_put(par.match->me); } static int check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { const struct ipt_ip *ip = par->entryinfo; par->match = m->u.kernel.match; par->matchinfo = m->data; return xt_check_match(par, m->u.match_size - sizeof(*m), ip->proto, ip->invflags & IPT_INV_PROTO); } static int find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { struct xt_match *match; int ret; match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) return PTR_ERR(match); m->u.kernel.match = match; ret = check_match(m, par); if (ret) goto err; return 0; err: module_put(m->u.kernel.match->me); return ret; } static int check_target(struct ipt_entry *e, struct net *net, const char *name) { struct xt_entry_target *t = ipt_get_target(e); struct xt_tgchk_param par = { .net = net, .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_IPV4, }; return xt_check_target(&par, t->u.target_size - sizeof(*t), e->ip.proto, e->ip.invflags & IPT_INV_PROTO); } static int find_check_entry(struct ipt_entry *e, struct net *net, 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; unsigned int j; struct xt_mtchk_param mtpar; struct xt_entry_match *ematch; if (!xt_percpu_counter_alloc(alloc_state, &e->counters)) return -ENOMEM; j = 0; mtpar.net = net; mtpar.table = name; mtpar.entryinfo = &e->ip; mtpar.hook_mask = e->comefrom; mtpar.family = NFPROTO_IPV4; xt_ematch_foreach(ematch, e) { ret = find_check_match(ematch, &mtpar); if (ret != 0) goto cleanup_matches; ++j; } t = ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { ret = PTR_ERR(target); goto cleanup_matches; } t->u.kernel.target = target; ret = check_target(e, net, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); cleanup_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; cleanup_match(ematch, net); } xt_percpu_counter_free(&e->counters); return ret; } static bool check_underflow(const struct ipt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = ipt_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 int check_entry_size_and_hooks(struct ipt_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 ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) return -EINVAL; if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) return -EINVAL; if (!ip_checkentry(&e->ip)) 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_INET_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 void cleanup_entry(struct ipt_entry *e, struct net *net) { struct xt_tgdtor_param par; struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) cleanup_match(ematch, net); t = ipt_get_target(e); par.net = net; par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_IPV4; 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 net *net, struct xt_table_info *newinfo, void *entry0, const struct ipt_replace *repl) { struct xt_percpu_counter_alloc_state alloc_state = { 0 }; struct ipt_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_INET_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(ipt_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_INET_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, net, 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, net); } 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 ipt_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; /* macro does multi eval of i */ cond_resched(); } } } static void get_old_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct ipt_entry *iter; unsigned int cpu, i; for_each_possible_cpu(cpu) { i = 0; xt_entry_foreach(iter, t->entries, t->size) { const struct xt_counters *tmp; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); ADD_COUNTER(counters[i], tmp->bcnt, tmp->pcnt); ++i; /* macro does multi eval of 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 ipt_entry *e; struct xt_counters *counters; const struct xt_table_info *private = table->private; int ret = 0; const 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++){ unsigned int i; const struct xt_entry_match *m; 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 ipt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } for (i = sizeof(struct ipt_entry); i < e->target_offset; i += m->u.match_size) { m = (void *)e + i; if (xt_match_to_user(m, userptr + off + i)) { ret = -EFAULT; goto free_counters; } } t = ipt_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(AF_INET, 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(AF_INET, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct ipt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_match *ematch; const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - base; xt_ematch_foreach(ematch, e) off += xt_compat_match_offset(ematch->u.kernel.match); t = ipt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_INET_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct ipt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct ipt_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 ipt_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(AF_INET, 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 ipt_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(AF_INET); #endif t = xt_request_find_table_lock(net, AF_INET, name); if (!IS_ERR(t)) { struct ipt_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(AF_INET); 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(AF_INET); #endif return ret; } static int get_entries(struct net *net, struct ipt_get_entries __user *uptr, const int *len) { int ret; struct ipt_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 ipt_get_entries) + get.size) return -EINVAL; get.name[sizeof(get.name) - 1] = '\0'; t = xt_find_table_lock(net, AF_INET, 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; struct ipt_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, AF_INET, 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 */ xt_entry_foreach(iter, oldinfo->entries, oldinfo->size) cleanup_entry(iter, net); 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("iptables: 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 ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_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(net, 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, net); 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 ipt_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, AF_INET, 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_ipt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_INET_NUMHOOKS]; u32 underflow[NF_INET_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; /* struct xt_counters * */ struct compat_ipt_entry entries[0]; }; static int compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr, unsigned int *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_ipt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; const struct xt_entry_match *ematch; int ret = 0; origsize = *size; ce = *dstptr; if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_ipt_entry); *size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); xt_ematch_foreach(ematch, e) { ret = xt_compat_match_to_user(ematch, dstptr, size); if (ret != 0) return ret; } target_offset = e->target_offset - (origsize - *size); t = ipt_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_find_calc_match(struct xt_entry_match *m, const struct ipt_ip *ip, int *size) { struct xt_match *match; match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) return PTR_ERR(match); m->u.kernel.match = match; *size += xt_compat_match_offset(match); return 0; } static void compat_release_entry(struct compat_ipt_entry *e) { struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) module_put(ematch->u.kernel.match->me); t = compat_ipt_get_target(e); module_put(t->u.kernel.target->me); } static int check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off; if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) return -EINVAL; if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) return -EINVAL; if (!ip_checkentry(&e->ip)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } static void compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr, unsigned int *size, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct ipt_entry *de; unsigned int origsize; int h; struct xt_entry_match *ematch; origsize = *size; de = *dstptr; memcpy(de, e, sizeof(struct ipt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct ipt_entry); *size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); xt_ematch_foreach(ematch, e) xt_compat_match_from_user(ematch, dstptr, size); de->target_offset = e->target_offset - (origsize - *size); t = compat_ipt_get_target(e); xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_INET_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 net *net, struct xt_table_info **pinfo, void **pentry0, const struct compat_ipt_replace *compatr) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_ipt_entry *iter0; struct ipt_replace repl; unsigned int size; int ret; info = *pinfo; entry0 = *pentry0; size = compatr->size; info->number = compatr->num_entries; j = 0; xt_compat_lock(AF_INET); xt_compat_init_offsets(AF_INET, 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_INET_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. * entry1/newinfo contains a 64bit ruleset that looks exactly as * generated by 64bit userspace. * * Call standard translate_table() to validate all hook_entrys, * underflows, check for loops, etc. */ xt_compat_flush_offsets(AF_INET); xt_compat_unlock(AF_INET); memcpy(&repl, compatr, sizeof(*compatr)); for (i = 0; i < NF_INET_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(net, 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(AF_INET); xt_compat_unlock(AF_INET); 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_ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_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(net, &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, net); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_ipt_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 IPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case IPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: ret = -EINVAL; } return ret; } struct compat_ipt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_ipt_entry entrytable[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 ipt_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; } static int compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr, int *len) { int ret; struct compat_ipt_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_ipt_get_entries) + get.size) return -EINVAL; get.name[sizeof(get.name) - 1] = '\0'; xt_compat_lock(AF_INET); t = xt_find_table_lock(net, AF_INET, 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(AF_INET); module_put(t->me); xt_table_unlock(t); } else ret = PTR_ERR(t); xt_compat_unlock(AF_INET); return ret; } static int do_ipt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_ipt_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 IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case IPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_ipt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_ipt_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 IPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case IPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: ret = -EINVAL; } return ret; } static int do_ipt_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 IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case IPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case IPT_SO_GET_REVISION_MATCH: case IPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; int target; 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; if (cmd == IPT_SO_GET_REVISION_TARGET) target = 1; else target = 0; try_then_request_module(xt_find_revision(AF_INET, rev.name, rev.revision, target, &ret), "ipt_%s", rev.name); break; } default: ret = -EINVAL; } return ret; } static void __ipt_unregister_table(struct net *net, struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct ipt_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, net); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int ipt_register_table(struct net *net, const struct xt_table *table, const struct ipt_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(net, 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) { __ipt_unregister_table(net, new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void ipt_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)); __ipt_unregister_table(net, table); } /* Returns 1 if the type and code is matched by the range, 0 otherwise */ static inline bool icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code, u_int8_t type, u_int8_t code, bool invert) { return ((test_type == 0xFF) || (type == test_type && code >= min_code && code <= max_code)) ^ invert; } static bool icmp_match(const struct sk_buff *skb, struct xt_action_param *par) { const struct icmphdr *ic; struct icmphdr _icmph; const struct ipt_icmp *icmpinfo = par->matchinfo; /* Must not be a fragment. */ if (par->fragoff != 0) return false; ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph); if (ic == NULL) { /* We've been asked to examine this packet, and we * can't. Hence, no choice but to drop. */ par->hotdrop = true; return false; } return icmp_type_code_match(icmpinfo->type, icmpinfo->code[0], icmpinfo->code[1], ic->type, ic->code, !!(icmpinfo->invflags&IPT_ICMP_INV)); } static int icmp_checkentry(const struct xt_mtchk_param *par) { const struct ipt_icmp *icmpinfo = par->matchinfo; /* Must specify no unknown invflags */ return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0; } static struct xt_target ipt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_IPV4, #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 = ipt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_IPV4, }, }; static struct nf_sockopt_ops ipt_sockopts = { .pf = PF_INET, .set_optmin = IPT_BASE_CTL, .set_optmax = IPT_SO_SET_MAX+1, .set = do_ipt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_ipt_set_ctl, #endif .get_optmin = IPT_BASE_CTL, .get_optmax = IPT_SO_GET_MAX+1, .get = do_ipt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_ipt_get_ctl, #endif .owner = THIS_MODULE, }; static struct xt_match ipt_builtin_mt[] __read_mostly = { { .name = "icmp", .match = icmp_match, .matchsize = sizeof(struct ipt_icmp), .checkentry = icmp_checkentry, .proto = IPPROTO_ICMP, .family = NFPROTO_IPV4, }, }; static int __net_init ip_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_IPV4); } static void __net_exit ip_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_IPV4); } static struct pernet_operations ip_tables_net_ops = { .init = ip_tables_net_init, .exit = ip_tables_net_exit, }; static int __init ip_tables_init(void) { int ret; ret = register_pernet_subsys(&ip_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(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); if (ret < 0) goto err2; ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); if (ret < 0) goto err4; /* Register setsockopt */ ret = nf_register_sockopt(&ipt_sockopts); if (ret < 0) goto err5; return 0; err5: xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); err4: xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); err2: unregister_pernet_subsys(&ip_tables_net_ops); err1: return ret; } static void __exit ip_tables_fini(void) { nf_unregister_sockopt(&ipt_sockopts); xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); unregister_pernet_subsys(&ip_tables_net_ops); } EXPORT_SYMBOL(ipt_register_table); EXPORT_SYMBOL(ipt_unregister_table); EXPORT_SYMBOL(ipt_do_table); module_init(ip_tables_init); module_exit(ip_tables_fini);
./CrossVul/dataset_final_sorted/CWE-476/c/bad_99_1
crossvul-cpp_data_bad_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(&current->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; address &= PAGE_MASK; error = security_mmap_addr(address); if (error) return error; /* 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/bad_1432_0
crossvul-cpp_data_good_1180_0
/* * utils for libavcodec * Copyright (c) 2001 Fabrice Bellard * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> * * 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 */ /** * @file * utils. */ #include "config.h" #include "libavutil/attributes.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/bprint.h" #include "libavutil/channel_layout.h" #include "libavutil/crc.h" #include "libavutil/frame.h" #include "libavutil/hwcontext.h" #include "libavutil/internal.h" #include "libavutil/mathematics.h" #include "libavutil/mem_internal.h" #include "libavutil/pixdesc.h" #include "libavutil/imgutils.h" #include "libavutil/samplefmt.h" #include "libavutil/dict.h" #include "libavutil/thread.h" #include "avcodec.h" #include "decode.h" #include "hwaccel.h" #include "libavutil/opt.h" #include "mpegvideo.h" #include "thread.h" #include "frame_thread_encoder.h" #include "internal.h" #include "raw.h" #include "bytestream.h" #include "version.h" #include <stdlib.h> #include <stdarg.h> #include <stdatomic.h> #include <limits.h> #include <float.h> #if CONFIG_ICONV # include <iconv.h> #endif #include "libavutil/ffversion.h" const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION; static AVMutex codec_mutex = AV_MUTEX_INITIALIZER; void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size) { uint8_t **p = ptr; if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { av_freep(p); *size = 0; return; } if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1)) memset(*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size) { uint8_t **p = ptr; if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { av_freep(p); *size = 0; return; } if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1)) memset(*p, 0, min_size + AV_INPUT_BUFFER_PADDING_SIZE); } int av_codec_is_encoder(const AVCodec *codec) { return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame); } int av_codec_is_decoder(const AVCodec *codec) { return codec && (codec->decode || codec->receive_frame); } int ff_set_dimensions(AVCodecContext *s, int width, int height) { int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s); if (ret < 0) width = height = 0; s->coded_width = width; s->coded_height = height; s->width = AV_CEIL_RSHIFT(width, s->lowres); s->height = AV_CEIL_RSHIFT(height, s->lowres); return ret; } int ff_set_sar(AVCodecContext *avctx, AVRational sar) { int ret = av_image_check_sar(avctx->width, avctx->height, sar); if (ret < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n", sar.num, sar.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; return ret; } else { avctx->sample_aspect_ratio = sar; } return 0; } int ff_side_data_update_matrix_encoding(AVFrame *frame, enum AVMatrixEncoding matrix_encoding) { AVFrameSideData *side_data; enum AVMatrixEncoding *data; side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING); if (!side_data) side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING, sizeof(enum AVMatrixEncoding)); if (!side_data) return AVERROR(ENOMEM); data = (enum AVMatrixEncoding*)side_data->data; *data = matrix_encoding; return 0; } void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P12LE: case AV_PIX_FMT_YUVA422P12BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P12LE: case AV_PIX_FMT_YUVA444P12BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV || s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres || s->codec_id == AV_CODEC_ID_VP5 || s->codec_id == AV_CODEC_ID_VP6 || s->codec_id == AV_CODEC_ID_VP6F || s->codec_id == AV_CODEC_ID_VP6A ) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; // H.264 uses edge emulation for out of frame motion vectors, for this // it requires a temporary area large enough to hold a 21x21 block, // increasing witdth ensure that the temporary area is large enough, // the next rounded up width is 32 *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; } void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt); int chroma_shift = desc->log2_chroma_w; int linesize_align[AV_NUM_DATA_POINTERS]; int align; avcodec_align_dimensions2(s, width, height, linesize_align); align = FFMAX(linesize_align[0], linesize_align[3]); linesize_align[1] <<= chroma_shift; linesize_align[2] <<= chroma_shift; align = FFMAX3(align, linesize_align[1], linesize_align[2]); *width = FFALIGN(*width, align); } int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos) { if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB) return AVERROR(EINVAL); pos--; *xpos = (pos&1) * 128; *ypos = ((pos>>1)^(pos<4)) * 128; return 0; } enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos) { int pos, xout, yout; for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) { if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos) return pos; } return AVCHROMA_LOC_UNSPECIFIED; } int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels, enum AVSampleFormat sample_fmt, const uint8_t *buf, int buf_size, int align) { int ch, planar, needed_size, ret = 0; needed_size = av_samples_get_buffer_size(NULL, nb_channels, frame->nb_samples, sample_fmt, align); if (buf_size < needed_size) return AVERROR(EINVAL); planar = av_sample_fmt_is_planar(sample_fmt); if (planar && nb_channels > AV_NUM_DATA_POINTERS) { if (!(frame->extended_data = av_mallocz_array(nb_channels, sizeof(*frame->extended_data)))) return AVERROR(ENOMEM); } else { frame->extended_data = frame->data; } if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0], (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples, sample_fmt, align)) < 0) { if (frame->extended_data != frame->data) av_freep(&frame->extended_data); return ret; } if (frame->extended_data != frame->data) { for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++) frame->data[ch] = frame->extended_data[ch]; } return ret; } void ff_color_frame(AVFrame *frame, const int c[4]) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format); int p, y, x; av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR); for (p = 0; p<desc->nb_components; p++) { uint8_t *dst = frame->data[p]; int is_chroma = p == 1 || p == 2; int bytes = is_chroma ? AV_CEIL_RSHIFT(frame->width, desc->log2_chroma_w) : frame->width; int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height; for (y = 0; y < height; y++) { if (desc->comp[0].depth >= 9) { for (x = 0; x<bytes; x++) ((uint16_t*)dst)[x] = c[p]; }else memset(dst, c[p], bytes); dst += frame->linesize[p]; } } } int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size) { int i; for (i = 0; i < count; i++) { int r = func(c, (char *)arg + i * size); if (ret) ret[i] = r; } emms_c(); return 0; } int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count) { int i; for (i = 0; i < count; i++) { int r = func(c, arg, i, 0); if (ret) ret[i] = r; } emms_c(); return 0; } enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc) { while (tags->pix_fmt >= 0) { if (tags->fourcc == fourcc) return tags->pix_fmt; tags++; } return AV_PIX_FMT_NONE; } #if FF_API_CODEC_GET_SET MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase) MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor) MAKE_ACCESSORS(AVCodecContext, codec, int, lowres) MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll) MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix) unsigned av_codec_get_codec_properties(const AVCodecContext *codec) { return codec->properties; } int av_codec_get_max_lowres(const AVCodec *codec) { return codec->max_lowres; } #endif int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){ return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM); } static int64_t get_bit_rate(AVCodecContext *ctx) { int64_t bit_rate; int bits_per_sample; switch (ctx->codec_type) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_DATA: case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_ATTACHMENT: bit_rate = ctx->bit_rate; break; case AVMEDIA_TYPE_AUDIO: bits_per_sample = av_get_bits_per_sample(ctx->codec_id); bit_rate = bits_per_sample ? ctx->sample_rate * (int64_t)ctx->channels * bits_per_sample : ctx->bit_rate; break; default: bit_rate = 0; break; } return bit_rate; } static void ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec) { if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init) ff_mutex_lock(&codec_mutex); } static void ff_unlock_avcodec(const AVCodec *codec) { if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init) ff_mutex_unlock(&codec_mutex); } int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; ff_unlock_avcodec(codec); ret = avcodec_open2(avctx, codec, options); ff_lock_avcodec(avctx, codec); return ret; } int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; int codec_init_ok = 0; AVDictionary *tmp = NULL; const AVPixFmtDescriptor *pixdesc; if (avcodec_is_open(avctx)) return 0; if ((!codec && !avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n"); return AVERROR(EINVAL); } if ((codec && avctx->codec && codec != avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, " "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name); return AVERROR(EINVAL); } if (!codec) codec = avctx->codec; if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE) return AVERROR(EINVAL); if (options) av_dict_copy(&tmp, *options, 0); ff_lock_avcodec(avctx, codec); avctx->internal = av_mallocz(sizeof(*avctx->internal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; } avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool)); if (!avctx->internal->pool) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->to_free = av_frame_alloc(); if (!avctx->internal->to_free) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->compat_decode_frame = av_frame_alloc(); if (!avctx->internal->compat_decode_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_frame = av_frame_alloc(); if (!avctx->internal->buffer_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_pkt = av_packet_alloc(); if (!avctx->internal->buffer_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->ds.in_pkt = av_packet_alloc(); if (!avctx->internal->ds.in_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->last_pkt_props = av_packet_alloc(); if (!avctx->internal->last_pkt_props) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->skip_samples_multiplier = 1; if (codec->priv_data_size > 0) { if (!avctx->priv_data) { avctx->priv_data = av_mallocz(codec->priv_data_size); if (!avctx->priv_data) { ret = AVERROR(ENOMEM); goto end; } if (codec->priv_class) { *(const AVClass **)avctx->priv_data = codec->priv_class; av_opt_set_defaults(avctx->priv_data); } } if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0) goto free_and_end; } else { avctx->priv_data = NULL; } if ((ret = av_opt_set_dict(avctx, &tmp)) < 0) goto free_and_end; if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) { av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist); ret = AVERROR(EINVAL); goto free_and_end; } // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) { if (avctx->coded_width && avctx->coded_height) ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height); else if (avctx->width && avctx->height) ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto free_and_end; } if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height) && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0 || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) { av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n"); ff_set_dimensions(avctx, 0, 0); } if (avctx->width > 0 && avctx->height > 0) { if (av_image_check_sar(avctx->width, avctx->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } } /* if the decoder init function was already called previously, * free the already allocated subtitle_header before overwriting it */ if (av_codec_is_decoder(codec)) av_freep(&avctx->subtitle_header); if (avctx->channels > FF_SANE_NB_CHANNELS) { av_log(avctx, AV_LOG_ERROR, "Too many channels: %d\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } avctx->codec = codec; if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) && avctx->codec_id == AV_CODEC_ID_NONE) { avctx->codec_type = codec->type; avctx->codec_id = codec->id; } if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) { av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n"); ret = AVERROR(EINVAL); goto free_and_end; } avctx->frame_number = 0; avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id); if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder"; AVCodec *codec2; av_log(avctx, AV_LOG_ERROR, "The %s '%s' is experimental but experimental codecs are not enabled, " "add '-strict %d' if you want to use it.\n", codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL); codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL)) av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n", codec_string, codec2->name); ret = AVERROR_EXPERIMENTAL; goto free_and_end; } if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && (!avctx->time_base.num || !avctx->time_base.den)) { avctx->time_base.num = 1; avctx->time_base.den = avctx->sample_rate; } if (!HAVE_THREADS) av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n"); if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) { ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL); ff_lock_avcodec(avctx, codec); if (ret < 0) goto free_and_end; } if (av_codec_is_decoder(avctx->codec)) { ret = ff_decode_bsfs_init(avctx); if (ret < 0) goto free_and_end; } if (HAVE_THREADS && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) { ret = ff_thread_init(avctx); if (ret < 0) { goto free_and_end; } } if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS)) avctx->thread_count = 1; if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) { av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n", avctx->codec->max_lowres); avctx->lowres = avctx->codec->max_lowres; } if (av_codec_is_encoder(avctx->codec)) { int i; #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } FF_ENABLE_DEPRECATION_WARNINGS #endif if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) { av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->sample_fmts) { for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) { if (avctx->sample_fmt == avctx->codec->sample_fmts[i]) break; if (avctx->channels == 1 && av_get_planar_sample_fmt(avctx->sample_fmt) == av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) { avctx->sample_fmt = avctx->codec->sample_fmts[i]; break; } } if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt); av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->codec->pix_fmts) { for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++) if (avctx->pix_fmt == avctx->codec->pix_fmts[i]) break; if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG) && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt); av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P) avctx->color_range = AVCOL_RANGE_JPEG; } if (avctx->codec->supported_samplerates) { for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++) if (avctx->sample_rate == avctx->codec->supported_samplerates[i]) break; if (avctx->codec->supported_samplerates[i] == 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->sample_rate < 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->channel_layouts) { if (!avctx->channel_layout) { av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n"); } else { for (i = 0; avctx->codec->channel_layouts[i] != 0; i++) if (avctx->channel_layout == avctx->codec->channel_layouts[i]) break; if (avctx->codec->channel_layouts[i] == 0) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf); ret = AVERROR(EINVAL); goto free_and_end; } } } if (avctx->channel_layout && avctx->channels) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Channel layout '%s' with %d channels does not match number of specified channels %d\n", buf, channels, avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } } else if (avctx->channel_layout) { avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout); } if (avctx->channels < 0) { av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) { pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt); if ( avctx->bits_per_raw_sample < 0 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) { av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n", avctx->bits_per_raw_sample, pixdesc->comp[0].depth); avctx->bits_per_raw_sample = pixdesc->comp[0].depth; } if (avctx->width <= 0 || avctx->height <= 0) { av_log(avctx, AV_LOG_ERROR, "dimensions not set\n"); ret = AVERROR(EINVAL); goto free_and_end; } } if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO) && avctx->bit_rate>0 && avctx->bit_rate<1000) { av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate); } if (!avctx->rc_initial_buffer_occupancy) avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { av_log(avctx, AV_LOG_ERROR, "ticks_per_frame %d too large for the timebase %d/%d.", avctx->ticks_per_frame, avctx->time_base.num, avctx->time_base.den); goto free_and_end; } if (avctx->hw_frames_ctx) { AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (frames_ctx->format != avctx->pix_fmt) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE && avctx->sw_pix_fmt != frames_ctx->sw_format) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.sw_pix_fmt (%s) " "and AVHWFramesContext.sw_format (%s)\n", av_get_pix_fmt_name(avctx->sw_pix_fmt), av_get_pix_fmt_name(frames_ctx->sw_format)); ret = AVERROR(EINVAL); goto free_and_end; } avctx->sw_pix_fmt = frames_ctx->sw_format; } } avctx->pts_correction_num_faulty_pts = avctx->pts_correction_num_faulty_dts = 0; avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO) av_log(avctx, AV_LOG_WARNING, "gray decoding requested but not enabled at configuration time\n"); if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)) { ret = avctx->codec->init(avctx); if (ret < 0) { goto free_and_end; } codec_init_ok = 1; } ret=0; if (av_codec_is_decoder(avctx->codec)) { if (!avctx->bit_rate) avctx->bit_rate = get_bit_rate(avctx); /* validate channel layout from the decoder */ if (avctx->channel_layout) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (!avctx->channels) avctx->channels = channels; else if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_WARNING, "Channel layout '%s' with %d channels does not match specified number of channels %d: " "ignoring specified channel layout\n", buf, channels, avctx->channels); avctx->channel_layout = 0; } } if (avctx->channels && avctx->channels < 0 || avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->bits_per_coded_sample < 0) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sub_charenc) { if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, "Character encoding is only " "supported with subtitles codecs\n"); ret = AVERROR(EINVAL); goto free_and_end; } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) { av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, " "subtitles character encoding will be ignored\n", avctx->codec_descriptor->name); avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING; } else { /* input character encoding is set for a text based subtitle * codec at this point */ if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC) avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER; if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) { #if CONFIG_ICONV iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc); if (cd == (iconv_t)-1) { ret = AVERROR(errno); av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context " "with input character encoding \"%s\"\n", avctx->sub_charenc); goto free_and_end; } iconv_close(cd); #else av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles " "conversion needs a libavcodec built with iconv support " "for this codec\n"); ret = AVERROR(ENOSYS); goto free_and_end; #endif } } } #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif } if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) { av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class); } end: ff_unlock_avcodec(codec); if (options) { av_dict_free(options); *options = tmp; } return ret; free_and_end: if (avctx->codec && avctx->codec->close && (codec_init_ok || (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))) avctx->codec->close(avctx); if (codec->priv_class && codec->priv_data_size) av_opt_free(avctx->priv_data); av_opt_free(avctx); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_free(&tmp); av_freep(&avctx->priv_data); if (avctx->internal) { av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->compat_decode_frame); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); av_packet_free(&avctx->internal->last_pkt_props); av_packet_free(&avctx->internal->ds.in_pkt); ff_decode_bsfs_uninit(avctx); av_freep(&avctx->internal->pool); } av_freep(&avctx->internal); avctx->codec = NULL; goto end; } void avsubtitle_free(AVSubtitle *sub) { int i; for (i = 0; i < sub->num_rects; i++) { av_freep(&sub->rects[i]->data[0]); av_freep(&sub->rects[i]->data[1]); av_freep(&sub->rects[i]->data[2]); av_freep(&sub->rects[i]->data[3]); av_freep(&sub->rects[i]->text); av_freep(&sub->rects[i]->ass); av_freep(&sub->rects[i]); } av_freep(&sub->rects); memset(sub, 0, sizeof(*sub)); } av_cold int avcodec_close(AVCodecContext *avctx) { int i; if (!avctx) return 0; if (avcodec_is_open(avctx)) { FramePool *pool = avctx->internal->pool; if (CONFIG_FRAME_THREAD_ENCODER && avctx->internal->frame_thread_encoder && avctx->thread_count > 1) { ff_frame_thread_encoder_free(avctx); } if (HAVE_THREADS && avctx->internal->thread_ctx) ff_thread_free(avctx); if (avctx->codec && avctx->codec->close) avctx->codec->close(avctx); avctx->internal->byte_buffer_size = 0; av_freep(&avctx->internal->byte_buffer); av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->compat_decode_frame); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); av_packet_free(&avctx->internal->last_pkt_props); av_packet_free(&avctx->internal->ds.in_pkt); for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++) av_buffer_pool_uninit(&pool->pools[i]); av_freep(&avctx->internal->pool); if (avctx->hwaccel && avctx->hwaccel->uninit) avctx->hwaccel->uninit(avctx); av_freep(&avctx->internal->hwaccel_priv_data); ff_decode_bsfs_uninit(avctx); av_freep(&avctx->internal); } for (i = 0; i < avctx->nb_coded_side_data; i++) av_freep(&avctx->coded_side_data[i].data); av_freep(&avctx->coded_side_data); avctx->nb_coded_side_data = 0; av_buffer_unref(&avctx->hw_frames_ctx); av_buffer_unref(&avctx->hw_device_ctx); if (avctx->priv_data && avctx->codec && avctx->codec->priv_class) av_opt_free(avctx->priv_data); av_opt_free(avctx); av_freep(&avctx->priv_data); if (av_codec_is_encoder(avctx->codec)) { av_freep(&avctx->extradata); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif } avctx->codec = NULL; avctx->active_thread_type = 0; return 0; } const char *avcodec_get_name(enum AVCodecID id) { const AVCodecDescriptor *cd; AVCodec *codec; if (id == AV_CODEC_ID_NONE) return "none"; cd = avcodec_descriptor_get(id); if (cd) return cd->name; av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id); codec = avcodec_find_decoder(id); if (codec) return codec->name; codec = avcodec_find_encoder(id); if (codec) return codec->name; return "unknown_codec"; } size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag) { int i, len, ret = 0; #define TAG_PRINT(x) \ (((x) >= '0' && (x) <= '9') || \ ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') || \ ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_')) for (i = 0; i < 4; i++) { len = snprintf(buf, buf_size, TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF); buf += len; buf_size = buf_size > len ? buf_size - len : 0; ret += len; codec_tag >>= 8; } return ret; } void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode) { const char *codec_type; const char *codec_name; const char *profile = NULL; int64_t bitrate; int new_line = 0; AVRational display_aspect_ratio; const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", "; if (!buf || buf_size <= 0) return; codec_type = av_get_media_type_string(enc->codec_type); codec_name = avcodec_get_name(enc->codec_id); profile = avcodec_profile_name(enc->codec_id, enc->profile); snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown", codec_name); buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */ if (enc->codec && strcmp(enc->codec->name, codec_name)) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name); if (profile) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile); if ( enc->codec_type == AVMEDIA_TYPE_VIDEO && av_log_get_level() >= AV_LOG_VERBOSE && enc->refs) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %d reference frame%s", enc->refs, enc->refs > 1 ? "s" : ""); if (enc->codec_tag) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s / 0x%04X)", av_fourcc2str(enc->codec_tag), enc->codec_tag); switch (enc->codec_type) { case AVMEDIA_TYPE_VIDEO: { char detail[256] = "("; av_strlcat(buf, separator, buf_size); snprintf(buf + strlen(buf), buf_size - strlen(buf), "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" : av_get_pix_fmt_name(enc->pix_fmt)); if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE && enc->bits_per_raw_sample < av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth) av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample); if (enc->color_range != AVCOL_RANGE_UNSPECIFIED) av_strlcatf(detail, sizeof(detail), "%s, ", av_color_range_name(enc->color_range)); if (enc->colorspace != AVCOL_SPC_UNSPECIFIED || enc->color_primaries != AVCOL_PRI_UNSPECIFIED || enc->color_trc != AVCOL_TRC_UNSPECIFIED) { if (enc->colorspace != (int)enc->color_primaries || enc->colorspace != (int)enc->color_trc) { new_line = 1; av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ", av_color_space_name(enc->colorspace), av_color_primaries_name(enc->color_primaries), av_color_transfer_name(enc->color_trc)); } else av_strlcatf(detail, sizeof(detail), "%s, ", av_get_colorspace_name(enc->colorspace)); } if (enc->field_order != AV_FIELD_UNKNOWN) { const char *field_order = "progressive"; if (enc->field_order == AV_FIELD_TT) field_order = "top first"; else if (enc->field_order == AV_FIELD_BB) field_order = "bottom first"; else if (enc->field_order == AV_FIELD_TB) field_order = "top coded first (swapped)"; else if (enc->field_order == AV_FIELD_BT) field_order = "bottom coded first (swapped)"; av_strlcatf(detail, sizeof(detail), "%s, ", field_order); } if (av_log_get_level() >= AV_LOG_VERBOSE && enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) av_strlcatf(detail, sizeof(detail), "%s, ", av_chroma_location_name(enc->chroma_sample_location)); if (strlen(detail) > 1) { detail[strlen(detail) - 2] = 0; av_strlcatf(buf, buf_size, "%s)", detail); } } if (enc->width) { av_strlcat(buf, new_line ? separator : ", ", buf_size); snprintf(buf + strlen(buf), buf_size - strlen(buf), "%dx%d", enc->width, enc->height); if (av_log_get_level() >= AV_LOG_VERBOSE && (enc->width != enc->coded_width || enc->height != enc->coded_height)) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%dx%d)", enc->coded_width, enc->coded_height); if (enc->sample_aspect_ratio.num) { av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den, enc->width * (int64_t)enc->sample_aspect_ratio.num, enc->height * (int64_t)enc->sample_aspect_ratio.den, 1024 * 1024); snprintf(buf + strlen(buf), buf_size - strlen(buf), " [SAR %d:%d DAR %d:%d]", enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den, display_aspect_ratio.num, display_aspect_ratio.den); } if (av_log_get_level() >= AV_LOG_DEBUG) { int g = av_gcd(enc->time_base.num, enc->time_base.den); snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %d/%d", enc->time_base.num / g, enc->time_base.den / g); } } if (encode) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", q=%d-%d", enc->qmin, enc->qmax); } else { if (enc->properties & FF_CODEC_PROPERTY_CLOSED_CAPTIONS) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", Closed Captions"); if (enc->properties & FF_CODEC_PROPERTY_LOSSLESS) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", lossless"); } break; case AVMEDIA_TYPE_AUDIO: av_strlcat(buf, separator, buf_size); if (enc->sample_rate) { snprintf(buf + strlen(buf), buf_size - strlen(buf), "%d Hz, ", enc->sample_rate); } av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout); if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s", av_get_sample_fmt_name(enc->sample_fmt)); } if ( enc->bits_per_raw_sample > 0 && enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%d bit)", enc->bits_per_raw_sample); if (av_log_get_level() >= AV_LOG_VERBOSE) { if (enc->initial_padding) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", delay %d", enc->initial_padding); if (enc->trailing_padding) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", padding %d", enc->trailing_padding); } break; case AVMEDIA_TYPE_DATA: if (av_log_get_level() >= AV_LOG_DEBUG) { int g = av_gcd(enc->time_base.num, enc->time_base.den); if (g) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %d/%d", enc->time_base.num / g, enc->time_base.den / g); } break; case AVMEDIA_TYPE_SUBTITLE: if (enc->width) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %dx%d", enc->width, enc->height); break; default: return; } if (encode) { if (enc->flags & AV_CODEC_FLAG_PASS1) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", pass 1"); if (enc->flags & AV_CODEC_FLAG_PASS2) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", pass 2"); } bitrate = get_bit_rate(enc); if (bitrate != 0) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %"PRId64" kb/s", bitrate / 1000); } else if (enc->rc_max_rate > 0) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", max. %"PRId64" kb/s", enc->rc_max_rate / 1000); } } const char *av_get_profile_name(const AVCodec *codec, int profile) { const AVProfile *p; if (profile == FF_PROFILE_UNKNOWN || !codec->profiles) return NULL; for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++) if (p->profile == profile) return p->name; return NULL; } const char *avcodec_profile_name(enum AVCodecID codec_id, int profile) { const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id); const AVProfile *p; if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles) return NULL; for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++) if (p->profile == profile) return p->name; return NULL; } unsigned avcodec_version(void) { av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563); av_assert0(AV_CODEC_ID_ADPCM_G722==69660); av_assert0(AV_CODEC_ID_SRT==94216); av_assert0(LIBAVCODEC_VERSION_MICRO >= 100); return LIBAVCODEC_VERSION_INT; } const char *avcodec_configuration(void) { return FFMPEG_CONFIGURATION; } const char *avcodec_license(void) { #define LICENSE_PREFIX "libavcodec license: " return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1; } int av_get_exact_bits_per_sample(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_8SVX_EXP: case AV_CODEC_ID_8SVX_FIB: case AV_CODEC_ID_ADPCM_CT: case AV_CODEC_ID_ADPCM_IMA_APC: case AV_CODEC_ID_ADPCM_IMA_EA_SEAD: case AV_CODEC_ID_ADPCM_IMA_OKI: case AV_CODEC_ID_ADPCM_IMA_WS: case AV_CODEC_ID_ADPCM_G722: case AV_CODEC_ID_ADPCM_YAMAHA: case AV_CODEC_ID_ADPCM_AICA: return 4; case AV_CODEC_ID_DSD_LSBF: case AV_CODEC_ID_DSD_MSBF: case AV_CODEC_ID_DSD_LSBF_PLANAR: case AV_CODEC_ID_DSD_MSBF_PLANAR: case AV_CODEC_ID_PCM_ALAW: case AV_CODEC_ID_PCM_MULAW: case AV_CODEC_ID_PCM_VIDC: case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S8_PLANAR: case AV_CODEC_ID_PCM_U8: case AV_CODEC_ID_PCM_ZORK: case AV_CODEC_ID_SDX2_DPCM: return 8; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S16BE_PLANAR: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S16LE_PLANAR: case AV_CODEC_ID_PCM_U16BE: case AV_CODEC_ID_PCM_U16LE: return 16; case AV_CODEC_ID_PCM_S24DAUD: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S24LE_PLANAR: case AV_CODEC_ID_PCM_U24BE: case AV_CODEC_ID_PCM_U24LE: return 24; case AV_CODEC_ID_PCM_S32BE: case AV_CODEC_ID_PCM_S32LE: case AV_CODEC_ID_PCM_S32LE_PLANAR: case AV_CODEC_ID_PCM_U32BE: case AV_CODEC_ID_PCM_U32LE: case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F24LE: case AV_CODEC_ID_PCM_F16LE: return 32; case AV_CODEC_ID_PCM_F64BE: case AV_CODEC_ID_PCM_F64LE: case AV_CODEC_ID_PCM_S64BE: case AV_CODEC_ID_PCM_S64LE: return 64; default: return 0; } } enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be) { static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = { [AV_SAMPLE_FMT_U8 ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 }, [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE }, [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE }, [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE }, [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE }, [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 }, [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE }, [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE }, [AV_SAMPLE_FMT_S64P] = { AV_CODEC_ID_PCM_S64LE, AV_CODEC_ID_PCM_S64BE }, [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE }, [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE }, }; if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB) return AV_CODEC_ID_NONE; if (be < 0 || be > 1) be = AV_NE(1, 0); return map[fmt][be]; } int av_get_bits_per_sample(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_ADPCM_SBPRO_2: return 2; case AV_CODEC_ID_ADPCM_SBPRO_3: return 3; case AV_CODEC_ID_ADPCM_SBPRO_4: case AV_CODEC_ID_ADPCM_IMA_WAV: case AV_CODEC_ID_ADPCM_IMA_QT: case AV_CODEC_ID_ADPCM_SWF: case AV_CODEC_ID_ADPCM_MS: return 4; default: return av_get_exact_bits_per_sample(codec_id); } } static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba, uint32_t tag, int bits_per_coded_sample, int64_t bitrate, uint8_t * extradata, int frame_size, int frame_bytes) { int bps = av_get_exact_bits_per_sample(id); int framecount = (ba > 0 && frame_bytes / ba > 0) ? frame_bytes / ba : 1; /* codecs with an exact constant bits per sample */ if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768) return (frame_bytes * 8LL) / (bps * ch); bps = bits_per_coded_sample; /* codecs with a fixed packet duration */ switch (id) { case AV_CODEC_ID_ADPCM_ADX: return 32; case AV_CODEC_ID_ADPCM_IMA_QT: return 64; case AV_CODEC_ID_ADPCM_EA_XAS: return 128; case AV_CODEC_ID_AMR_NB: case AV_CODEC_ID_EVRC: case AV_CODEC_ID_GSM: case AV_CODEC_ID_QCELP: case AV_CODEC_ID_RA_288: return 160; case AV_CODEC_ID_AMR_WB: case AV_CODEC_ID_GSM_MS: return 320; case AV_CODEC_ID_MP1: return 384; case AV_CODEC_ID_ATRAC1: return 512; case AV_CODEC_ID_ATRAC9: case AV_CODEC_ID_ATRAC3: return 1024 * framecount; case AV_CODEC_ID_ATRAC3P: return 2048; case AV_CODEC_ID_MP2: case AV_CODEC_ID_MUSEPACK7: return 1152; case AV_CODEC_ID_AC3: return 1536; } if (sr > 0) { /* calc from sample rate */ if (id == AV_CODEC_ID_TTA) return 256 * sr / 245; else if (id == AV_CODEC_ID_DST) return 588 * sr / 44100; if (ch > 0) { /* calc from sample rate and channels */ if (id == AV_CODEC_ID_BINKAUDIO_DCT) return (480 << (sr / 22050)) / ch; } if (id == AV_CODEC_ID_MP3) return sr <= 24000 ? 576 : 1152; } if (ba > 0) { /* calc from block_align */ if (id == AV_CODEC_ID_SIPR) { switch (ba) { case 20: return 160; case 19: return 144; case 29: return 288; case 37: return 480; } } else if (id == AV_CODEC_ID_ILBC) { switch (ba) { case 38: return 160; case 50: return 240; } } } if (frame_bytes > 0) { /* calc from frame_bytes only */ if (id == AV_CODEC_ID_TRUESPEECH) return 240 * (frame_bytes / 32); if (id == AV_CODEC_ID_NELLYMOSER) return 256 * (frame_bytes / 64); if (id == AV_CODEC_ID_RA_144) return 160 * (frame_bytes / 20); if (bps > 0) { /* calc from frame_bytes and bits_per_coded_sample */ if (id == AV_CODEC_ID_ADPCM_G726 || id == AV_CODEC_ID_ADPCM_G726LE) return frame_bytes * 8 / bps; } if (ch > 0 && ch < INT_MAX/16) { /* calc from frame_bytes and channels */ switch (id) { case AV_CODEC_ID_ADPCM_AFC: return frame_bytes / (9 * ch) * 16; case AV_CODEC_ID_ADPCM_PSX: case AV_CODEC_ID_ADPCM_DTK: return frame_bytes / (16 * ch) * 28; case AV_CODEC_ID_ADPCM_4XM: case AV_CODEC_ID_ADPCM_IMA_DAT4: case AV_CODEC_ID_ADPCM_IMA_ISS: return (frame_bytes - 4 * ch) * 2 / ch; case AV_CODEC_ID_ADPCM_IMA_SMJPEG: return (frame_bytes - 4) * 2 / ch; case AV_CODEC_ID_ADPCM_IMA_AMV: return (frame_bytes - 8) * 2 / ch; case AV_CODEC_ID_ADPCM_THP: case AV_CODEC_ID_ADPCM_THP_LE: if (extradata) return frame_bytes * 14 / (8 * ch); break; case AV_CODEC_ID_ADPCM_XA: return (frame_bytes / 128) * 224 / ch; case AV_CODEC_ID_INTERPLAY_DPCM: return (frame_bytes - 6 - ch) / ch; case AV_CODEC_ID_ROQ_DPCM: return (frame_bytes - 8) / ch; case AV_CODEC_ID_XAN_DPCM: return (frame_bytes - 2 * ch) / ch; case AV_CODEC_ID_MACE3: return 3 * frame_bytes / ch; case AV_CODEC_ID_MACE6: return 6 * frame_bytes / ch; case AV_CODEC_ID_PCM_LXF: return 2 * (frame_bytes / (5 * ch)); case AV_CODEC_ID_IAC: case AV_CODEC_ID_IMC: return 4 * frame_bytes / ch; } if (tag) { /* calc from frame_bytes, channels, and codec_tag */ if (id == AV_CODEC_ID_SOL_DPCM) { if (tag == 3) return frame_bytes / ch; else return frame_bytes * 2 / ch; } } if (ba > 0) { /* calc from frame_bytes, channels, and block_align */ int blocks = frame_bytes / ba; switch (id) { case AV_CODEC_ID_ADPCM_IMA_WAV: if (bps < 2 || bps > 5) return 0; return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8); case AV_CODEC_ID_ADPCM_IMA_DK3: return blocks * (((ba - 16) * 2 / 3 * 4) / ch); case AV_CODEC_ID_ADPCM_IMA_DK4: return blocks * (1 + (ba - 4 * ch) * 2 / ch); case AV_CODEC_ID_ADPCM_IMA_RAD: return blocks * ((ba - 4 * ch) * 2 / ch); case AV_CODEC_ID_ADPCM_MS: return blocks * (2 + (ba - 7 * ch) * 2 / ch); case AV_CODEC_ID_ADPCM_MTAF: return blocks * (ba - 16) * 2 / ch; } } if (bps > 0) { /* calc from frame_bytes, channels, and bits_per_coded_sample */ switch (id) { case AV_CODEC_ID_PCM_DVD: if(bps<4 || frame_bytes<3) return 0; return 2 * ((frame_bytes - 3) / ((bps * 2 / 8) * ch)); case AV_CODEC_ID_PCM_BLURAY: if(bps<4 || frame_bytes<4) return 0; return (frame_bytes - 4) / ((FFALIGN(ch, 2) * bps) / 8); case AV_CODEC_ID_S302M: return 2 * (frame_bytes / ((bps + 4) / 4)) / ch; } } } } /* Fall back on using frame_size */ if (frame_size > 1 && frame_bytes) return frame_size; //For WMA we currently have no other means to calculate duration thus we //do it here by assuming CBR, which is true for all known cases. if (bitrate > 0 && frame_bytes > 0 && sr > 0 && ba > 1) { if (id == AV_CODEC_ID_WMAV1 || id == AV_CODEC_ID_WMAV2) return (frame_bytes * 8LL * sr) / bitrate; } return 0; } int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes) { return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate, avctx->channels, avctx->block_align, avctx->codec_tag, avctx->bits_per_coded_sample, avctx->bit_rate, avctx->extradata, avctx->frame_size, frame_bytes); } int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes) { return get_audio_frame_duration(par->codec_id, par->sample_rate, par->channels, par->block_align, par->codec_tag, par->bits_per_coded_sample, par->bit_rate, par->extradata, par->frame_size, frame_bytes); } #if !HAVE_THREADS int ff_thread_init(AVCodecContext *s) { return -1; } #endif unsigned int av_xiphlacing(unsigned char *s, unsigned int v) { unsigned int n = 0; while (v >= 0xff) { *s++ = 0xff; v -= 0xff; n++; } *s = v; n++; return n; } int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b) { int i; for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ; return i; } const AVCodecHWConfig *avcodec_get_hw_config(const AVCodec *codec, int index) { int i; if (!codec->hw_configs || index < 0) return NULL; for (i = 0; i <= index; i++) if (!codec->hw_configs[i]) return NULL; return &codec->hw_configs[index]->public; } #if FF_API_USER_VISIBLE_AVHWACCEL AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel) { return NULL; } void av_register_hwaccel(AVHWAccel *hwaccel) { } #endif #if FF_API_LOCKMGR int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op)) { return 0; } #endif unsigned int avpriv_toupper4(unsigned int x) { return av_toupper(x & 0xFF) + (av_toupper((x >> 8) & 0xFF) << 8) + (av_toupper((x >> 16) & 0xFF) << 16) + ((unsigned)av_toupper((x >> 24) & 0xFF) << 24); } int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src) { int ret; dst->owner[0] = src->owner[0]; dst->owner[1] = src->owner[1]; ret = av_frame_ref(dst->f, src->f); if (ret < 0) return ret; av_assert0(!dst->progress); if (src->progress && !(dst->progress = av_buffer_ref(src->progress))) { ff_thread_release_buffer(dst->owner[0], dst); return AVERROR(ENOMEM); } return 0; } #if !HAVE_THREADS enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt) { return ff_get_format(avctx, fmt); } int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags) { f->owner[0] = f->owner[1] = avctx; return ff_get_buffer(avctx, f->f, flags); } void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f) { if (f->f) av_frame_unref(f->f); } void ff_thread_finish_setup(AVCodecContext *avctx) { } void ff_thread_report_progress(ThreadFrame *f, int progress, int field) { } void ff_thread_await_progress(ThreadFrame *f, int progress, int field) { } int ff_thread_can_start_frame(AVCodecContext *avctx) { return 1; } int ff_alloc_entries(AVCodecContext *avctx, int count) { return 0; } void ff_reset_entries(AVCodecContext *avctx) { } void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift) { } void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n) { } #endif int avcodec_is_open(AVCodecContext *s) { return !!s->internal; } int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf) { int ret; char *str; ret = av_bprint_finalize(buf, &str); if (ret < 0) return ret; if (!av_bprint_is_complete(buf)) { av_free(str); return AVERROR(ENOMEM); } avctx->extradata = str; /* Note: the string is NUL terminated (so extradata can be read as a * string), but the ending character is not accounted in the size (in * binary formats you are likely not supposed to mux that character). When * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE * zeros. */ avctx->extradata_size = buf->len; return 0; } const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p, const uint8_t *end, uint32_t *av_restrict state) { int i; av_assert0(p <= end); if (p >= end) return end; for (i = 0; i < 3; i++) { uint32_t tmp = *state << 8; *state = tmp + *(p++); if (tmp == 0x100 || p == end) return p; } while (p < end) { if (p[-1] > 1 ) p += 3; else if (p[-2] ) p += 2; else if (p[-3]|(p[-1]-1)) p++; else { p++; break; } } p = FFMIN(p, end) - 4; *state = AV_RB32(p); return p + 4; } AVCPBProperties *av_cpb_properties_alloc(size_t *size) { AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties)); if (!props) return NULL; if (size) *size = sizeof(*props); props->vbv_delay = UINT64_MAX; return props; } AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx) { AVPacketSideData *tmp; AVCPBProperties *props; size_t size; props = av_cpb_properties_alloc(&size); if (!props) return NULL; tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp)); if (!tmp) { av_freep(&props); return NULL; } avctx->coded_side_data = tmp; avctx->nb_coded_side_data++; avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES; avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props; avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size; return props; } static void codec_parameters_reset(AVCodecParameters *par) { av_freep(&par->extradata); memset(par, 0, sizeof(*par)); par->codec_type = AVMEDIA_TYPE_UNKNOWN; par->codec_id = AV_CODEC_ID_NONE; par->format = -1; par->field_order = AV_FIELD_UNKNOWN; par->color_range = AVCOL_RANGE_UNSPECIFIED; par->color_primaries = AVCOL_PRI_UNSPECIFIED; par->color_trc = AVCOL_TRC_UNSPECIFIED; par->color_space = AVCOL_SPC_UNSPECIFIED; par->chroma_location = AVCHROMA_LOC_UNSPECIFIED; par->sample_aspect_ratio = (AVRational){ 0, 1 }; par->profile = FF_PROFILE_UNKNOWN; par->level = FF_LEVEL_UNKNOWN; } AVCodecParameters *avcodec_parameters_alloc(void) { AVCodecParameters *par = av_mallocz(sizeof(*par)); if (!par) return NULL; codec_parameters_reset(par); return par; } void avcodec_parameters_free(AVCodecParameters **ppar) { AVCodecParameters *par = *ppar; if (!par) return; codec_parameters_reset(par); av_freep(ppar); } int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src) { codec_parameters_reset(dst); memcpy(dst, src, sizeof(*dst)); dst->extradata = NULL; dst->extradata_size = 0; if (src->extradata) { dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!dst->extradata) return AVERROR(ENOMEM); memcpy(dst->extradata, src->extradata, src->extradata_size); dst->extradata_size = src->extradata_size; } return 0; } int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec) { codec_parameters_reset(par); par->codec_type = codec->codec_type; par->codec_id = codec->codec_id; par->codec_tag = codec->codec_tag; par->bit_rate = codec->bit_rate; par->bits_per_coded_sample = codec->bits_per_coded_sample; par->bits_per_raw_sample = codec->bits_per_raw_sample; par->profile = codec->profile; par->level = codec->level; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: par->format = codec->pix_fmt; par->width = codec->width; par->height = codec->height; par->field_order = codec->field_order; par->color_range = codec->color_range; par->color_primaries = codec->color_primaries; par->color_trc = codec->color_trc; par->color_space = codec->colorspace; par->chroma_location = codec->chroma_sample_location; par->sample_aspect_ratio = codec->sample_aspect_ratio; par->video_delay = codec->has_b_frames; break; case AVMEDIA_TYPE_AUDIO: par->format = codec->sample_fmt; par->channel_layout = codec->channel_layout; par->channels = codec->channels; par->sample_rate = codec->sample_rate; par->block_align = codec->block_align; par->frame_size = codec->frame_size; par->initial_padding = codec->initial_padding; par->trailing_padding = codec->trailing_padding; par->seek_preroll = codec->seek_preroll; break; case AVMEDIA_TYPE_SUBTITLE: par->width = codec->width; par->height = codec->height; break; } if (codec->extradata) { par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) return AVERROR(ENOMEM); memcpy(par->extradata, codec->extradata, codec->extradata_size); par->extradata_size = codec->extradata_size; } return 0; } int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par) { codec->codec_type = par->codec_type; codec->codec_id = par->codec_id; codec->codec_tag = par->codec_tag; codec->bit_rate = par->bit_rate; codec->bits_per_coded_sample = par->bits_per_coded_sample; codec->bits_per_raw_sample = par->bits_per_raw_sample; codec->profile = par->profile; codec->level = par->level; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: codec->pix_fmt = par->format; codec->width = par->width; codec->height = par->height; codec->field_order = par->field_order; codec->color_range = par->color_range; codec->color_primaries = par->color_primaries; codec->color_trc = par->color_trc; codec->colorspace = par->color_space; codec->chroma_sample_location = par->chroma_location; codec->sample_aspect_ratio = par->sample_aspect_ratio; codec->has_b_frames = par->video_delay; break; case AVMEDIA_TYPE_AUDIO: codec->sample_fmt = par->format; codec->channel_layout = par->channel_layout; codec->channels = par->channels; codec->sample_rate = par->sample_rate; codec->block_align = par->block_align; codec->frame_size = par->frame_size; codec->delay = codec->initial_padding = par->initial_padding; codec->trailing_padding = par->trailing_padding; codec->seek_preroll = par->seek_preroll; break; case AVMEDIA_TYPE_SUBTITLE: codec->width = par->width; codec->height = par->height; break; } if (par->extradata) { av_freep(&codec->extradata); codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!codec->extradata) return AVERROR(ENOMEM); memcpy(codec->extradata, par->extradata, par->extradata_size); codec->extradata_size = par->extradata_size; } return 0; } int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len, void **data, size_t *sei_size) { AVFrameSideData *side_data = NULL; uint8_t *sei_data; if (frame) side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC); if (!side_data) { *data = NULL; return 0; } *sei_size = side_data->size + 11; *data = av_mallocz(*sei_size + prefix_len); if (!*data) return AVERROR(ENOMEM); sei_data = (uint8_t*)*data + prefix_len; // country code sei_data[0] = 181; sei_data[1] = 0; sei_data[2] = 49; /** * 'GA94' is standard in North America for ATSC, but hard coding * this style may not be the right thing to do -- other formats * do exist. This information is not available in the side_data * so we are going with this right now. */ AV_WL32(sei_data + 3, MKTAG('G', 'A', '9', '4')); sei_data[7] = 3; sei_data[8] = ((side_data->size/3) & 0x1f) | 0x40; sei_data[9] = 0; memcpy(sei_data + 10, side_data->data, side_data->size); sei_data[side_data->size+10] = 255; return 0; } int64_t ff_guess_coded_bitrate(AVCodecContext *avctx) { AVRational framerate = avctx->framerate; int bits_per_coded_sample = avctx->bits_per_coded_sample; int64_t bitrate; if (!(framerate.num && framerate.den)) framerate = av_inv_q(avctx->time_base); if (!(framerate.num && framerate.den)) return 0; if (!bits_per_coded_sample) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt); bits_per_coded_sample = av_get_bits_per_pixel(desc); } bitrate = (int64_t)bits_per_coded_sample * avctx->width * avctx->height * framerate.num / framerate.den; return bitrate; } int ff_int_from_list_or_default(void *ctx, const char * val_name, int val, const int * array_valid_values, int default_value) { int i = 0, ref_val; while (1) { ref_val = array_valid_values[i]; if (ref_val == INT_MAX) break; if (val == ref_val) return val; i++; } /* val is not a valid value */ av_log(ctx, AV_LOG_DEBUG, "%s %d are not supported. Set to default value : %d\n", val_name, val, default_value); return default_value; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_1180_0
crossvul-cpp_data_bad_1365_0
/** * @file tree_schema.c * @author Radek Krejci <rkrejci@cesnet.cz> * @brief Manipulation with libyang schema data structures * * Copyright (c) 2015 - 2018 CESNET, z.s.p.o. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #define _GNU_SOURCE #ifdef __APPLE__ # include <sys/param.h> #endif #include <assert.h> #include <ctype.h> #include <limits.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <dirent.h> #include "common.h" #include "context.h" #include "parser.h" #include "resolve.h" #include "xml.h" #include "xpath.h" #include "xml_internal.h" #include "tree_internal.h" #include "validation.h" #include "parser_yang.h" static int lys_type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old, int in_grp, int shallow, struct unres_schema *unres); API const struct lys_node_list * lys_is_key(const struct lys_node_leaf *node, uint8_t *index) { struct lys_node *parent = (struct lys_node *)node; struct lys_node_list *list; uint8_t i; if (!node || node->nodetype != LYS_LEAF) { return NULL; } do { parent = lys_parent(parent); } while (parent && parent->nodetype == LYS_USES); if (!parent || parent->nodetype != LYS_LIST) { return NULL; } list = (struct lys_node_list*)parent; for (i = 0; i < list->keys_size; i++) { if (list->keys[i] == node) { if (index) { (*index) = i; } return list; } } return NULL; } API const struct lys_node * lys_is_disabled(const struct lys_node *node, int recursive) { int i; if (!node) { return NULL; } check: if (node->nodetype != LYS_INPUT && node->nodetype != LYS_OUTPUT) { /* input/output does not have if-feature, so skip them */ /* check local if-features */ for (i = 0; i < node->iffeature_size; i++) { if (!resolve_iffeature(&node->iffeature[i])) { return node; } } } if (!recursive) { return NULL; } /* go through parents */ if (node->nodetype == LYS_AUGMENT) { /* go to parent actually means go to the target node */ node = ((struct lys_node_augment *)node)->target; if (!node) { /* unresolved augment, let's say it's enabled */ return NULL; } } else if (node->nodetype == LYS_EXT) { return NULL; } else if (node->parent) { node = node->parent; } else { return NULL; } if (recursive == 2) { /* continue only if the node cannot have a data instance */ if (node->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST)) { return NULL; } } goto check; } API const struct lys_type * lys_getnext_union_type(const struct lys_type *last, const struct lys_type *type) { int found = 0; if (!type || (type->base != LY_TYPE_UNION)) { return NULL; } return lyp_get_next_union_type((struct lys_type *)type, (struct lys_type *)last, &found); } int lys_get_sibling(const struct lys_node *siblings, const char *mod_name, int mod_name_len, const char *name, int nam_len, LYS_NODE type, const struct lys_node **ret) { const struct lys_node *node, *parent = NULL; const struct lys_module *mod = NULL; const char *node_mod_name; assert(siblings && mod_name && name); assert(!(type & (LYS_USES | LYS_GROUPING))); /* fill the lengths in case the caller is so indifferent */ if (!mod_name_len) { mod_name_len = strlen(mod_name); } if (!nam_len) { nam_len = strlen(name); } while (siblings && (siblings->nodetype == LYS_USES)) { siblings = siblings->child; } if (!siblings) { /* unresolved uses */ return EXIT_FAILURE; } if (siblings->nodetype == LYS_GROUPING) { for (node = siblings; (node->nodetype == LYS_GROUPING) && (node->prev != siblings); node = node->prev); if (node->nodetype == LYS_GROUPING) { /* we went through all the siblings, only groupings there - no valid sibling */ return EXIT_FAILURE; } /* update siblings to be valid */ siblings = node; } /* set parent correctly */ parent = lys_parent(siblings); /* go up all uses */ while (parent && (parent->nodetype == LYS_USES)) { parent = lys_parent(parent); } if (!parent) { /* handle situation when there is a top-level uses referencing a foreign grouping */ for (node = siblings; lys_parent(node) && (node->nodetype == LYS_USES); node = lys_parent(node)); mod = lys_node_module(node); } /* try to find the node */ node = NULL; while ((node = lys_getnext(node, parent, mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT))) { if (!type || (node->nodetype & type)) { /* module name comparison */ node_mod_name = lys_node_module(node)->name; if (!ly_strequal(node_mod_name, mod_name, 1) && (strncmp(node_mod_name, mod_name, mod_name_len) || node_mod_name[mod_name_len])) { continue; } /* direct name check */ if (ly_strequal(node->name, name, 1) || (!strncmp(node->name, name, nam_len) && !node->name[nam_len])) { if (ret) { *ret = node; } return EXIT_SUCCESS; } } } return EXIT_FAILURE; } int lys_getnext_data(const struct lys_module *mod, const struct lys_node *parent, const char *name, int nam_len, LYS_NODE type, int getnext_opts, const struct lys_node **ret) { const struct lys_node *node; assert((mod || parent) && name); assert(!(type & (LYS_AUGMENT | LYS_USES | LYS_GROUPING | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT))); if (!mod) { mod = lys_node_module(parent); } /* try to find the node */ node = NULL; while ((node = lys_getnext(node, parent, mod, getnext_opts))) { if (!type || (node->nodetype & type)) { /* module check */ if (lys_node_module(node) != lys_main_module(mod)) { continue; } /* direct name check */ if (!strncmp(node->name, name, nam_len) && !node->name[nam_len]) { if (ret) { *ret = node; } return EXIT_SUCCESS; } } } return EXIT_FAILURE; } API const struct lys_node * lys_getnext(const struct lys_node *last, const struct lys_node *parent, const struct lys_module *module, int options) { const struct lys_node *next, *aug_parent; struct lys_node **snode; if ((!parent && !module) || (module && module->type) || (parent && (parent->nodetype == LYS_USES) && !(options & LYS_GETNEXT_PARENTUSES))) { LOGARG; return NULL; } if (!last) { /* first call */ /* get know where to start */ if (parent) { /* schema subtree */ snode = lys_child(parent, LYS_UNKNOWN); /* do not return anything if the augment does not have any children */ if (!snode || !(*snode) || ((parent->nodetype == LYS_AUGMENT) && ((*snode)->parent != parent))) { return NULL; } next = last = *snode; } else { /* top level data */ if (!(options & LYS_GETNEXT_NOSTATECHECK) && (module->disabled || !module->implemented)) { /* nothing to return from a disabled/imported module */ return NULL; } next = last = module->data; } } else if ((last->nodetype == LYS_USES) && (options & LYS_GETNEXT_INTOUSES) && last->child) { /* continue with uses content */ next = last->child; } else { /* continue after the last returned value */ next = last->next; } repeat: if (parent && (parent->nodetype == LYS_AUGMENT) && next) { /* do not return anything outside the parent augment */ aug_parent = next->parent; do { while (aug_parent && (aug_parent->nodetype != LYS_AUGMENT)) { aug_parent = aug_parent->parent; } if (aug_parent) { if (aug_parent == parent) { break; } aug_parent = ((struct lys_node_augment *)aug_parent)->target; } } while (aug_parent); if (!aug_parent) { return NULL; } } while (next && (next->nodetype == LYS_GROUPING)) { if (options & LYS_GETNEXT_WITHGROUPING) { return next; } next = next->next; } if (!next) { /* cover case when parent is augment */ if (!last || last->parent == parent || lys_parent(last) == parent) { /* no next element */ return NULL; } last = lys_parent(last); next = last->next; goto repeat; } else { last = next; } if (!(options & LYS_GETNEXT_NOSTATECHECK) && lys_is_disabled(next, 0)) { next = next->next; goto repeat; } switch (next->nodetype) { case LYS_INPUT: case LYS_OUTPUT: if (options & LYS_GETNEXT_WITHINOUT) { return next; } else if (next->child) { next = next->child; } else { next = next->next; } goto repeat; case LYS_CASE: if (options & LYS_GETNEXT_WITHCASE) { return next; } else if (next->child) { next = next->child; } else { next = next->next; } goto repeat; case LYS_USES: /* go into */ if (options & LYS_GETNEXT_WITHUSES) { return next; } else if (next->child) { next = next->child; } else { next = next->next; } goto repeat; case LYS_RPC: case LYS_ACTION: case LYS_NOTIF: case LYS_LEAF: case LYS_ANYXML: case LYS_ANYDATA: case LYS_LIST: case LYS_LEAFLIST: return next; case LYS_CONTAINER: if (!((struct lys_node_container *)next)->presence && (options & LYS_GETNEXT_INTONPCONT)) { if (next->child) { /* go into */ next = next->child; } else { next = next->next; } goto repeat; } else { return next; } case LYS_CHOICE: if (options & LYS_GETNEXT_WITHCHOICE) { return next; } else if (next->child) { /* go into */ next = next->child; } else { next = next->next; } goto repeat; default: /* we should not be here */ return NULL; } } void lys_node_unlink(struct lys_node *node) { struct lys_node *parent, *first, **pp = NULL; struct lys_module *main_module; if (!node) { return; } /* unlink from data model if necessary */ if (node->module) { /* get main module with data tree */ main_module = lys_node_module(node); if (main_module->data == node) { main_module->data = node->next; } } /* store pointers to important nodes */ parent = node->parent; if (parent && (parent->nodetype == LYS_AUGMENT)) { /* handle augments - first, unlink it from the augment parent ... */ if (parent->child == node) { parent->child = (node->next && node->next->parent == parent) ? node->next : NULL; } if (parent->flags & LYS_NOTAPPLIED) { /* data are not connected in the target, so we cannot continue with the target as a parent */ parent = NULL; } else { /* data are connected in target, so we will continue with the target as a parent */ parent = ((struct lys_node_augment *)parent)->target; } } /* unlink from parent */ if (parent) { if (parent->nodetype == LYS_EXT) { pp = (struct lys_node **)lys_ext_complex_get_substmt(lys_snode2stmt(node->nodetype), (struct lys_ext_instance_complex*)parent, NULL); if (*pp == node) { *pp = node->next; } } else if (parent->child == node) { parent->child = node->next; } node->parent = NULL; } /* unlink from siblings */ if (node->prev == node) { /* there are no more siblings */ return; } if (node->next) { node->next->prev = node->prev; } else { /* unlinking the last element */ if (parent) { if (parent->nodetype == LYS_EXT) { first = *(struct lys_node **)pp; } else { first = parent->child; } } else { first = node; while (first->prev->next) { first = first->prev; } } first->prev = node->prev; } if (node->prev->next) { node->prev->next = node->next; } /* clean up the unlinked element */ node->next = NULL; node->prev = node; } struct lys_node_grp * lys_find_grouping_up(const char *name, struct lys_node *start) { struct lys_node *par_iter, *iter, *stop; for (par_iter = start; par_iter; par_iter = par_iter->parent) { /* top-level augment, look into module (uses augment is handled correctly below) */ if (par_iter->parent && !par_iter->parent->parent && (par_iter->parent->nodetype == LYS_AUGMENT)) { par_iter = lys_main_module(par_iter->parent->module)->data; if (!par_iter) { break; } } if (par_iter->nodetype == LYS_EXT) { /* we are in a top-level extension, search grouping in top-level groupings */ par_iter = lys_main_module(par_iter->module)->data; if (!par_iter) { /* not connected yet, wait */ return NULL; } } else if (par_iter->parent && (par_iter->parent->nodetype & (LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_USES))) { continue; } for (iter = par_iter, stop = NULL; iter; iter = iter->prev) { if (!stop) { stop = par_iter; } else if (iter == stop) { break; } if (iter->nodetype != LYS_GROUPING) { continue; } if (!strcmp(name, iter->name)) { return (struct lys_node_grp *)iter; } } } return NULL; } /* * get next grouping in the root's subtree, in the * first call, tha last is NULL */ static struct lys_node_grp * lys_get_next_grouping(struct lys_node_grp *lastgrp, struct lys_node *root) { struct lys_node *last = (struct lys_node *)lastgrp; struct lys_node *next; assert(root); if (!last) { last = root; } while (1) { if ((last->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LIST | LYS_GROUPING | LYS_INPUT | LYS_OUTPUT))) { next = last->child; } else { next = NULL; } if (!next) { if (last == root) { /* we are done */ return NULL; } /* no children, go to siblings */ next = last->next; } while (!next) { /* go back through parents */ if (lys_parent(last) == root) { /* we are done */ return NULL; } next = last->next; last = lys_parent(last); } if (next->nodetype == LYS_GROUPING) { return (struct lys_node_grp *)next; } last = next; } } /* logs directly */ int lys_check_id(struct lys_node *node, struct lys_node *parent, struct lys_module *module) { struct lys_node *start, *stop, *iter; struct lys_node_grp *grp; int down, up; assert(node); if (!parent) { assert(module); } else { module = parent->module; } module = lys_main_module(module); switch (node->nodetype) { case LYS_GROUPING: /* 6.2.1, rule 6 */ if (parent) { start = *lys_child(parent, LYS_GROUPING); if (!start) { down = 0; start = parent; } else { down = 1; } if (parent->nodetype == LYS_EXT) { up = 0; } else { up = 1; } } else { down = up = 1; start = module->data; } /* go up */ if (up && lys_find_grouping_up(node->name, start)) { LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, "grouping", node->name); return EXIT_FAILURE; } /* go down, because grouping can be defined after e.g. container in which is collision */ if (down) { for (iter = start, stop = NULL; iter; iter = iter->prev) { if (!stop) { stop = start; } else if (iter == stop) { break; } if (!(iter->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LIST | LYS_GROUPING | LYS_INPUT | LYS_OUTPUT))) { continue; } grp = NULL; while ((grp = lys_get_next_grouping(grp, iter))) { if (ly_strequal(node->name, grp->name, 1)) { LOGVAL(module->ctx, LYE_DUPID,LY_VLOG_LYS, node, "grouping", node->name); return EXIT_FAILURE; } } } } break; case LYS_LEAF: case LYS_LEAFLIST: case LYS_LIST: case LYS_CONTAINER: case LYS_CHOICE: case LYS_ANYDATA: /* 6.2.1, rule 7 */ if (parent) { iter = parent; while (iter && (iter->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE | LYS_AUGMENT))) { if (iter->nodetype == LYS_AUGMENT) { if (((struct lys_node_augment *)iter)->target) { /* augment is resolved, go up */ iter = ((struct lys_node_augment *)iter)->target; continue; } /* augment is not resolved, this is the final parent */ break; } iter = iter->parent; } if (!iter) { stop = NULL; iter = module->data; } else if (iter->nodetype == LYS_EXT) { stop = iter; iter = (struct lys_node *)lys_child(iter, node->nodetype); if (iter) { iter = *(struct lys_node **)iter; } } else { stop = iter; iter = iter->child; } } else { stop = NULL; iter = module->data; } while (iter) { if (iter->nodetype & (LYS_USES | LYS_CASE)) { iter = iter->child; continue; } if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CONTAINER | LYS_CHOICE | LYS_ANYDATA)) { if (iter->module == node->module && ly_strequal(iter->name, node->name, 1)) { LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, strnodetype(node->nodetype), node->name); return EXIT_FAILURE; } } /* special case for choice - we must check the choice's name as * well as the names of nodes under the choice */ if (iter->nodetype == LYS_CHOICE) { iter = iter->child; continue; } /* go to siblings */ if (!iter->next) { /* no sibling, go to parent's sibling */ do { /* for parent LYS_AUGMENT */ if (iter->parent == stop) { iter = stop; break; } iter = lys_parent(iter); if (iter && iter->next) { break; } } while (iter != stop); if (iter == stop) { break; } } iter = iter->next; } break; case LYS_CASE: /* 6.2.1, rule 8 */ if (parent) { start = *lys_child(parent, LYS_CASE); } else { start = module->data; } LY_TREE_FOR(start, iter) { if (!(iter->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST))) { continue; } if (iter->module == node->module && ly_strequal(iter->name, node->name, 1)) { LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, "case", node->name); return EXIT_FAILURE; } } break; default: /* no check needed */ break; } return EXIT_SUCCESS; } /* logs directly */ int lys_node_addchild(struct lys_node *parent, struct lys_module *module, struct lys_node *child, int options) { struct ly_ctx *ctx = child->module->ctx; struct lys_node *iter, **pchild, *log_parent; struct lys_node_inout *in, *out; struct lys_node_case *c; int type, shortcase = 0; void *p; struct lyext_substmt *info = NULL; assert(child); if (parent) { type = parent->nodetype; module = parent->module; log_parent = parent; if (type == LYS_USES) { /* we are adding children to uses -> we must be copying grouping contents into it, so properly check the parent */ log_parent = lys_parent(log_parent); while (log_parent && (log_parent->nodetype == LYS_USES)) { log_parent = lys_parent(log_parent); } if (log_parent) { type = log_parent->nodetype; } else { type = 0; } } } else { assert(module); assert(!(child->nodetype & (LYS_INPUT | LYS_OUTPUT))); type = 0; log_parent = NULL; } /* checks */ switch (type) { case LYS_CONTAINER: case LYS_LIST: case LYS_GROUPING: case LYS_USES: if (!(child->nodetype & (LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_GROUPING | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_ACTION | LYS_NOTIF))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype)); return EXIT_FAILURE; } break; case LYS_INPUT: case LYS_OUTPUT: case LYS_NOTIF: if (!(child->nodetype & (LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_GROUPING | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_USES))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype)); return EXIT_FAILURE; } break; case LYS_CHOICE: if (!(child->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "choice"); return EXIT_FAILURE; } if (child->nodetype != LYS_CASE) { shortcase = 1; } break; case LYS_CASE: if (!(child->nodetype & (LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_USES))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "case"); return EXIT_FAILURE; } break; case LYS_RPC: case LYS_ACTION: if (!(child->nodetype & (LYS_INPUT | LYS_OUTPUT | LYS_GROUPING))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "rpc"); return EXIT_FAILURE; } break; case LYS_LEAF: case LYS_LEAFLIST: case LYS_ANYXML: case LYS_ANYDATA: LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype)); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"%s\" statement cannot have any data substatement.", strnodetype(log_parent->nodetype)); return EXIT_FAILURE; case LYS_AUGMENT: if (!(child->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_ACTION | LYS_NOTIF))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype)); return EXIT_FAILURE; } break; case LYS_UNKNOWN: /* top level */ if (!(child->nodetype & (LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_GROUPING | LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_RPC | LYS_NOTIF | LYS_AUGMENT))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "(sub)module"); return EXIT_FAILURE; } break; case LYS_EXT: /* plugin-defined */ p = lys_ext_complex_get_substmt(lys_snode2stmt(child->nodetype), (struct lys_ext_instance_complex*)log_parent, &info); if (!p) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), ((struct lys_ext_instance_complex*)log_parent)->def->name); return EXIT_FAILURE; } /* TODO check cardinality */ break; } /* check identifier uniqueness */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && lys_check_id(child, parent, module)) { return EXIT_FAILURE; } if (child->parent) { lys_node_unlink(child); } if ((child->nodetype & (LYS_INPUT | LYS_OUTPUT)) && parent->nodetype != LYS_EXT) { /* find the implicit input/output node */ LY_TREE_FOR(parent->child, iter) { if (iter->nodetype == child->nodetype) { break; } } assert(iter); /* switch the old implicit node (iter) with the new one (child) */ if (parent->child == iter) { /* first child */ parent->child = child; } else { iter->prev->next = child; } child->prev = iter->prev; child->next = iter->next; if (iter->next) { iter->next->prev = child; } else { /* last child */ parent->child->prev = child; } child->parent = parent; /* isolate the node and free it */ iter->next = NULL; iter->prev = iter; iter->parent = NULL; lys_node_free(iter, NULL, 0); } else { if (shortcase) { /* create the implicit case to allow it to serve as a target of the augments, * it won't be printed, but it will be present in the tree */ c = calloc(1, sizeof *c); LY_CHECK_ERR_RETURN(!c, LOGMEM(ctx), EXIT_FAILURE); c->name = lydict_insert(module->ctx, child->name, 0); c->flags = LYS_IMPLICIT; if (!(options & (LYS_PARSE_OPT_CFG_IGNORE | LYS_PARSE_OPT_CFG_NOINHERIT))) { /* get config flag from parent */ c->flags |= parent->flags & LYS_CONFIG_MASK; } c->module = module; c->nodetype = LYS_CASE; c->prev = (struct lys_node*)c; lys_node_addchild(parent, module, (struct lys_node*)c, options); parent = (struct lys_node*)c; } /* connect the child correctly */ if (!parent) { if (module->data) { module->data->prev->next = child; child->prev = module->data->prev; module->data->prev = child; } else { module->data = child; } } else { pchild = lys_child(parent, child->nodetype); assert(pchild); child->parent = parent; if (!(*pchild)) { /* the only/first child of the parent */ *pchild = child; iter = child; } else { /* add a new child at the end of parent's child list */ iter = (*pchild)->prev; iter->next = child; child->prev = iter; } while (iter->next) { iter = iter->next; iter->parent = parent; } (*pchild)->prev = iter; } } /* check config value (but ignore them in groupings and augments) */ for (iter = parent; iter && !(iter->nodetype & (LYS_GROUPING | LYS_AUGMENT | LYS_EXT)); iter = iter->parent); if (parent && !iter) { for (iter = child; iter && !(iter->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC)); iter = iter->parent); if (!iter && (parent->flags & LYS_CONFIG_R) && (child->flags & LYS_CONFIG_W)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, child, "true", "config"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children."); return EXIT_FAILURE; } } /* propagate information about status data presence */ if ((child->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA)) && (child->flags & LYS_INCL_STATUS)) { for(iter = parent; iter; iter = lys_parent(iter)) { /* store it only into container or list - the only data inner nodes */ if (iter->nodetype & (LYS_CONTAINER | LYS_LIST)) { if (iter->flags & LYS_INCL_STATUS) { /* done, someone else set it already from here */ break; } /* set flag about including status data */ iter->flags |= LYS_INCL_STATUS; } } } /* create implicit input/output nodes to have available them as possible target for augment */ if ((child->nodetype & (LYS_RPC | LYS_ACTION)) && !child->child) { in = calloc(1, sizeof *in); out = calloc(1, sizeof *out); if (!in || !out) { LOGMEM(ctx); free(in); free(out); return EXIT_FAILURE; } in->nodetype = LYS_INPUT; in->name = lydict_insert(child->module->ctx, "input", 5); out->nodetype = LYS_OUTPUT; out->name = lydict_insert(child->module->ctx, "output", 6); in->module = out->module = child->module; in->parent = out->parent = child; in->flags = out->flags = LYS_IMPLICIT; in->next = (struct lys_node *)out; in->prev = (struct lys_node *)out; out->prev = (struct lys_node *)in; child->child = (struct lys_node *)in; } return EXIT_SUCCESS; } const struct lys_module * lys_parse_mem_(struct ly_ctx *ctx, const char *data, LYS_INFORMAT format, const char *revision, int internal, int implement) { char *enlarged_data = NULL; struct lys_module *mod = NULL; unsigned int len; if (!ctx || !data) { LOGARG; return NULL; } if (!internal && format == LYS_IN_YANG) { /* enlarge data by 2 bytes for flex */ len = strlen(data); enlarged_data = malloc((len + 2) * sizeof *enlarged_data); LY_CHECK_ERR_RETURN(!enlarged_data, LOGMEM(ctx), NULL); memcpy(enlarged_data, data, len); enlarged_data[len] = enlarged_data[len + 1] = '\0'; data = enlarged_data; } switch (format) { case LYS_IN_YIN: mod = yin_read_module(ctx, data, revision, implement); break; case LYS_IN_YANG: mod = yang_read_module(ctx, data, 0, revision, implement); break; default: LOGERR(ctx, LY_EINVAL, "Invalid schema input format."); break; } free(enlarged_data); /* hack for NETCONF's edit-config's operation attribute. It is not defined in the schema, but since libyang * implements YANG metadata (annotations), we need its definition. Because the ietf-netconf schema is not the * internal part of libyang, we cannot add the annotation into the schema source, but we do it here to have * the anotation definitions available in the internal schema structure. There is another hack in schema * printers to do not print this internally added annotation. */ if (mod && ly_strequal(mod->name, "ietf-netconf", 0)) { if (lyp_add_ietf_netconf_annotations_config(mod)) { lys_free(mod, NULL, 1, 1); return NULL; } } return mod; } API const struct lys_module * lys_parse_mem(struct ly_ctx *ctx, const char *data, LYS_INFORMAT format) { return lys_parse_mem_(ctx, data, format, NULL, 0, 1); } struct lys_submodule * lys_sub_parse_mem(struct lys_module *module, const char *data, LYS_INFORMAT format, struct unres_schema *unres) { char *enlarged_data = NULL; struct lys_submodule *submod = NULL; unsigned int len; assert(module); assert(data); if (format == LYS_IN_YANG) { /* enlarge data by 2 bytes for flex */ len = strlen(data); enlarged_data = malloc((len + 2) * sizeof *enlarged_data); LY_CHECK_ERR_RETURN(!enlarged_data, LOGMEM(module->ctx), NULL); memcpy(enlarged_data, data, len); enlarged_data[len] = enlarged_data[len + 1] = '\0'; data = enlarged_data; } /* get the main module */ module = lys_main_module(module); switch (format) { case LYS_IN_YIN: submod = yin_read_submodule(module, data, unres); break; case LYS_IN_YANG: submod = yang_read_submodule(module, data, 0, unres); break; default: assert(0); break; } free(enlarged_data); return submod; } API const struct lys_module * lys_parse_path(struct ly_ctx *ctx, const char *path, LYS_INFORMAT format) { int fd; const struct lys_module *ret; const char *rev, *dot, *filename; size_t len; if (!ctx || !path) { LOGARG; return NULL; } fd = open(path, O_RDONLY); if (fd == -1) { LOGERR(ctx, LY_ESYS, "Opening file \"%s\" failed (%s).", path, strerror(errno)); return NULL; } ret = lys_parse_fd(ctx, fd, format); close(fd); if (!ret) { /* error */ return NULL; } /* check that name and revision match filename */ filename = strrchr(path, '/'); if (!filename) { filename = path; } else { filename++; } rev = strchr(filename, '@'); dot = strrchr(filename, '.'); /* name */ len = strlen(ret->name); if (strncmp(filename, ret->name, len) || ((rev && rev != &filename[len]) || (!rev && dot != &filename[len]))) { LOGWRN(ctx, "File name \"%s\" does not match module name \"%s\".", filename, ret->name); } if (rev) { len = dot - ++rev; if (!ret->rev_size || len != 10 || strncmp(ret->rev[0].date, rev, len)) { LOGWRN(ctx, "File name \"%s\" does not match module revision \"%s\".", filename, ret->rev_size ? ret->rev[0].date : "none"); } } if (!ret->filepath) { /* store URI */ char rpath[PATH_MAX]; if (realpath(path, rpath) != NULL) { ((struct lys_module *)ret)->filepath = lydict_insert(ctx, rpath, 0); } else { ((struct lys_module *)ret)->filepath = lydict_insert(ctx, path, 0); } } return ret; } API const struct lys_module * lys_parse_fd(struct ly_ctx *ctx, int fd, LYS_INFORMAT format) { return lys_parse_fd_(ctx, fd, format, NULL, 1); } static void lys_parse_set_filename(struct ly_ctx *ctx, const char **filename, int fd) { #ifdef __APPLE__ char path[MAXPATHLEN]; #else int len; char path[PATH_MAX], proc_path[32]; #endif #ifdef __APPLE__ if (fcntl(fd, F_GETPATH, path) != -1) { *filename = lydict_insert(ctx, path, 0); } #else /* get URI if there is /proc */ sprintf(proc_path, "/proc/self/fd/%d", fd); if ((len = readlink(proc_path, path, PATH_MAX - 1)) > 0) { *filename = lydict_insert(ctx, path, len); } #endif } const struct lys_module * lys_parse_fd_(struct ly_ctx *ctx, int fd, LYS_INFORMAT format, const char *revision, int implement) { const struct lys_module *module; size_t length; char *addr; if (!ctx || fd < 0) { LOGARG; return NULL; } if (lyp_mmap(ctx, fd, format == LYS_IN_YANG ? 1 : 0, &length, (void **)&addr)) { LOGERR(ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__); return NULL; } else if (!addr) { LOGERR(ctx, LY_EINVAL, "Empty schema file."); return NULL; } module = lys_parse_mem_(ctx, addr, format, revision, 1, implement); lyp_munmap(addr, length); if (module && !module->filepath) { lys_parse_set_filename(ctx, (const char **)&module->filepath, fd); } return module; } struct lys_submodule * lys_sub_parse_fd(struct lys_module *module, int fd, LYS_INFORMAT format, struct unres_schema *unres) { struct lys_submodule *submodule; size_t length; char *addr; assert(module); assert(fd >= 0); if (lyp_mmap(module->ctx, fd, format == LYS_IN_YANG ? 1 : 0, &length, (void **)&addr)) { LOGERR(module->ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__); return NULL; } else if (!addr) { LOGERR(module->ctx, LY_EINVAL, "Empty submodule schema file."); return NULL; } /* get the main module */ module = lys_main_module(module); switch (format) { case LYS_IN_YIN: submodule = yin_read_submodule(module, addr, unres); break; case LYS_IN_YANG: submodule = yang_read_submodule(module, addr, 0, unres); break; default: LOGINT(module->ctx); return NULL; } lyp_munmap(addr, length); if (submodule && !submodule->filepath) { lys_parse_set_filename(module->ctx, (const char **)&submodule->filepath, fd); } return submodule; } API int lys_search_localfile(const char * const *searchpaths, int cwd, const char *name, const char *revision, char **localfile, LYS_INFORMAT *format) { size_t len, flen, match_len = 0, dir_len; int i, implicit_cwd = 0, ret = EXIT_FAILURE; char *wd, *wn = NULL; DIR *dir = NULL; struct dirent *file; char *match_name = NULL; LYS_INFORMAT format_aux, match_format = 0; unsigned int u; struct ly_set *dirs; struct stat st; if (!localfile) { LOGARG; return EXIT_FAILURE; } /* start to fill the dir fifo with the context's search path (if set) * and the current working directory */ dirs = ly_set_new(); if (!dirs) { LOGMEM(NULL); return EXIT_FAILURE; } len = strlen(name); if (cwd) { wd = get_current_dir_name(); if (!wd) { LOGMEM(NULL); goto cleanup; } else { /* add implicit current working directory (./) to be searched, * this directory is not searched recursively */ if (ly_set_add(dirs, wd, 0) == -1) { goto cleanup; } implicit_cwd = 1; } } if (searchpaths) { for (i = 0; searchpaths[i]; i++) { /* check for duplicities with the implicit current working directory */ if (implicit_cwd && !strcmp(dirs->set.g[0], searchpaths[i])) { implicit_cwd = 0; continue; } wd = strdup(searchpaths[i]); if (!wd) { LOGMEM(NULL); goto cleanup; } else if (ly_set_add(dirs, wd, 0) == -1) { goto cleanup; } } } wd = NULL; /* start searching */ while (dirs->number) { free(wd); free(wn); wn = NULL; dirs->number--; wd = (char *)dirs->set.g[dirs->number]; dirs->set.g[dirs->number] = NULL; LOGVRB("Searching for \"%s\" in %s.", name, wd); if (dir) { closedir(dir); } dir = opendir(wd); dir_len = strlen(wd); if (!dir) { LOGWRN(NULL, "Unable to open directory \"%s\" for searching (sub)modules (%s).", wd, strerror(errno)); } else { while ((file = readdir(dir))) { if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) { /* skip . and .. */ continue; } free(wn); if (asprintf(&wn, "%s/%s", wd, file->d_name) == -1) { LOGMEM(NULL); goto cleanup; } if (stat(wn, &st) == -1) { LOGWRN(NULL, "Unable to get information about \"%s\" file in \"%s\" when searching for (sub)modules (%s)", file->d_name, wd, strerror(errno)); continue; } if (S_ISDIR(st.st_mode) && (dirs->number || !implicit_cwd)) { /* we have another subdirectory in searchpath to explore, * subdirectories are not taken into account in current working dir (dirs->set.g[0]) */ if (ly_set_add(dirs, wn, 0) == -1) { goto cleanup; } /* continue with the next item in current directory */ wn = NULL; continue; } else if (!S_ISREG(st.st_mode)) { /* not a regular file (note that we see the target of symlinks instead of symlinks */ continue; } /* here we know that the item is a file which can contain a module */ if (strncmp(name, file->d_name, len) || (file->d_name[len] != '.' && file->d_name[len] != '@')) { /* different filename than the module we search for */ continue; } /* get type according to filename suffix */ flen = strlen(file->d_name); if (!strcmp(&file->d_name[flen - 4], ".yin")) { format_aux = LYS_IN_YIN; } else if (!strcmp(&file->d_name[flen - 5], ".yang")) { format_aux = LYS_IN_YANG; } else { /* not supportde suffix/file format */ continue; } if (revision) { /* we look for the specific revision, try to get it from the filename */ if (file->d_name[len] == '@') { /* check revision from the filename */ if (strncmp(revision, &file->d_name[len + 1], strlen(revision))) { /* another revision */ continue; } else { /* exact revision */ free(match_name); match_name = wn; wn = NULL; match_len = dir_len + 1 + len; match_format = format_aux; goto success; } } else { /* continue trying to find exact revision match, use this only if not found */ free(match_name); match_name = wn; wn = NULL; match_len = dir_len + 1 +len; match_format = format_aux; continue; } } else { /* remember the revision and try to find the newest one */ if (match_name) { if (file->d_name[len] != '@' || lyp_check_date(NULL, &file->d_name[len + 1])) { continue; } else if (match_name[match_len] == '@' && (strncmp(&match_name[match_len + 1], &file->d_name[len + 1], LY_REV_SIZE - 1) >= 0)) { continue; } free(match_name); } match_name = wn; wn = NULL; match_len = dir_len + 1 + len; match_format = format_aux; continue; } } } } success: (*localfile) = match_name; match_name = NULL; if (format) { (*format) = match_format; } ret = EXIT_SUCCESS; cleanup: free(wn); free(wd); if (dir) { closedir(dir); } free(match_name); for (u = 0; u < dirs->number; u++) { free(dirs->set.g[u]); } ly_set_free(dirs); return ret; } int lys_ext_iter(struct lys_ext_instance **ext, uint8_t ext_size, uint8_t start, LYEXT_SUBSTMT substmt) { unsigned int u; for (u = start; u < ext_size; u++) { if (ext[u]->insubstmt == substmt) { return u; } } return -1; } /* * duplicate extension instance */ int lys_ext_dup(struct ly_ctx *ctx, struct lys_module *mod, struct lys_ext_instance **orig, uint8_t size, void *parent, LYEXT_PAR parent_type, struct lys_ext_instance ***new, int shallow, struct unres_schema *unres) { int i; uint8_t u = 0; struct lys_ext_instance **result; struct unres_ext *info, *info_orig; size_t len; assert(new); if (!size) { if (orig) { LOGINT(ctx); return EXIT_FAILURE; } (*new) = NULL; return EXIT_SUCCESS; } (*new) = result = calloc(size, sizeof *result); LY_CHECK_ERR_RETURN(!result, LOGMEM(ctx), EXIT_FAILURE); for (u = 0; u < size; u++) { if (orig[u]) { /* resolved extension instance, just duplicate it */ switch(orig[u]->ext_type) { case LYEXT_FLAG: result[u] = malloc(sizeof(struct lys_ext_instance)); LY_CHECK_ERR_GOTO(!result[u], LOGMEM(ctx), error); break; case LYEXT_COMPLEX: len = ((struct lyext_plugin_complex*)orig[u]->def->plugin)->instance_size; result[u] = calloc(1, len); LY_CHECK_ERR_GOTO(!result[u], LOGMEM(ctx), error); ((struct lys_ext_instance_complex*)result[u])->substmt = ((struct lyext_plugin_complex*)orig[u]->def->plugin)->substmt; /* TODO duplicate data in extension instance content */ memcpy((void*)result[u] + sizeof(**orig), (void*)orig[u] + sizeof(**orig), len - sizeof(**orig)); break; } /* generic part */ result[u]->def = orig[u]->def; result[u]->flags = LYEXT_OPT_CONTENT; result[u]->arg_value = lydict_insert(ctx, orig[u]->arg_value, 0); result[u]->parent = parent; result[u]->parent_type = parent_type; result[u]->insubstmt = orig[u]->insubstmt; result[u]->insubstmt_index = orig[u]->insubstmt_index; result[u]->ext_type = orig[u]->ext_type; result[u]->priv = NULL; result[u]->nodetype = LYS_EXT; result[u]->module = mod; /* extensions */ result[u]->ext_size = orig[u]->ext_size; if (lys_ext_dup(ctx, mod, orig[u]->ext, orig[u]->ext_size, result[u], LYEXT_PAR_EXTINST, &result[u]->ext, shallow, unres)) { goto error; } /* in case of shallow copy (duplication for deviation), duplicate only the link to private data * in a new copy, otherwise (grouping instantiation) do not duplicate the private data */ if (shallow) { result[u]->priv = orig[u]->priv; } } else { /* original extension is not yet resolved, so duplicate it in unres */ i = unres_schema_find(unres, -1, &orig, UNRES_EXT); if (i == -1) { /* extension not found in unres */ LOGINT(ctx); goto error; } info_orig = unres->str_snode[i]; info = malloc(sizeof *info); LY_CHECK_ERR_GOTO(!info, LOGMEM(ctx), error); info->datatype = info_orig->datatype; if (info->datatype == LYS_IN_YIN) { info->data.yin = lyxml_dup_elem(ctx, info_orig->data.yin, NULL, 1, 0); } /* else TODO YANG */ info->parent = parent; info->mod = mod; info->parent_type = parent_type; info->ext_index = u; if (unres_schema_add_node(info->mod, unres, new, UNRES_EXT, (struct lys_node *)info) == -1) { goto error; } } } return EXIT_SUCCESS; error: (*new) = NULL; lys_extension_instances_free(ctx, result, u, NULL); return EXIT_FAILURE; } static struct lys_restr * lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres) { struct lys_restr *result; int i; if (!size) { return NULL; } result = calloc(size, sizeof *result); LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL); for (i = 0; i < size; i++) { result[i].ext_size = old[i].ext_size; lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres); result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0); result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0); result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0); result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0); result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0); } return result; } void lys_restr_free(struct ly_ctx *ctx, struct lys_restr *restr, void (*private_destructor)(const struct lys_node *node, void *priv)) { assert(ctx); if (!restr) { return; } lys_extension_instances_free(ctx, restr->ext, restr->ext_size, private_destructor); lydict_remove(ctx, restr->expr); lydict_remove(ctx, restr->dsc); lydict_remove(ctx, restr->ref); lydict_remove(ctx, restr->eapptag); lydict_remove(ctx, restr->emsg); } API void lys_iffeature_free(struct ly_ctx *ctx, struct lys_iffeature *iffeature, uint8_t iffeature_size, int shallow, void (*private_destructor)(const struct lys_node *node, void *priv)) { uint8_t i; for (i = 0; i < iffeature_size; ++i) { lys_extension_instances_free(ctx, iffeature[i].ext, iffeature[i].ext_size, private_destructor); if (!shallow) { free(iffeature[i].expr); free(iffeature[i].features); } } free(iffeature); } static int type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old, LY_DATA_TYPE base, int in_grp, int shallow, struct unres_schema *unres) { int i; unsigned int u; switch (base) { case LY_TYPE_BINARY: if (old->info.binary.length) { new->info.binary.length = lys_restr_dup(mod, old->info.binary.length, 1, shallow, unres); } break; case LY_TYPE_BITS: new->info.bits.count = old->info.bits.count; if (new->info.bits.count) { new->info.bits.bit = calloc(new->info.bits.count, sizeof *new->info.bits.bit); LY_CHECK_ERR_RETURN(!new->info.bits.bit, LOGMEM(mod->ctx), -1); for (u = 0; u < new->info.bits.count; u++) { new->info.bits.bit[u].name = lydict_insert(mod->ctx, old->info.bits.bit[u].name, 0); new->info.bits.bit[u].dsc = lydict_insert(mod->ctx, old->info.bits.bit[u].dsc, 0); new->info.bits.bit[u].ref = lydict_insert(mod->ctx, old->info.bits.bit[u].ref, 0); new->info.bits.bit[u].flags = old->info.bits.bit[u].flags; new->info.bits.bit[u].pos = old->info.bits.bit[u].pos; new->info.bits.bit[u].ext_size = old->info.bits.bit[u].ext_size; if (lys_ext_dup(mod->ctx, mod, old->info.bits.bit[u].ext, old->info.bits.bit[u].ext_size, &new->info.bits.bit[u], LYEXT_PAR_TYPE_BIT, &new->info.bits.bit[u].ext, shallow, unres)) { return -1; } } } break; case LY_TYPE_DEC64: new->info.dec64.dig = old->info.dec64.dig; new->info.dec64.div = old->info.dec64.div; if (old->info.dec64.range) { new->info.dec64.range = lys_restr_dup(mod, old->info.dec64.range, 1, shallow, unres); } break; case LY_TYPE_ENUM: new->info.enums.count = old->info.enums.count; if (new->info.enums.count) { new->info.enums.enm = calloc(new->info.enums.count, sizeof *new->info.enums.enm); LY_CHECK_ERR_RETURN(!new->info.enums.enm, LOGMEM(mod->ctx), -1); for (u = 0; u < new->info.enums.count; u++) { new->info.enums.enm[u].name = lydict_insert(mod->ctx, old->info.enums.enm[u].name, 0); new->info.enums.enm[u].dsc = lydict_insert(mod->ctx, old->info.enums.enm[u].dsc, 0); new->info.enums.enm[u].ref = lydict_insert(mod->ctx, old->info.enums.enm[u].ref, 0); new->info.enums.enm[u].flags = old->info.enums.enm[u].flags; new->info.enums.enm[u].value = old->info.enums.enm[u].value; new->info.enums.enm[u].ext_size = old->info.enums.enm[u].ext_size; if (lys_ext_dup(mod->ctx, mod, old->info.enums.enm[u].ext, old->info.enums.enm[u].ext_size, &new->info.enums.enm[u], LYEXT_PAR_TYPE_ENUM, &new->info.enums.enm[u].ext, shallow, unres)) { return -1; } } } break; case LY_TYPE_IDENT: new->info.ident.count = old->info.ident.count; if (old->info.ident.count) { new->info.ident.ref = malloc(old->info.ident.count * sizeof *new->info.ident.ref); LY_CHECK_ERR_RETURN(!new->info.ident.ref, LOGMEM(mod->ctx), -1); memcpy(new->info.ident.ref, old->info.ident.ref, old->info.ident.count * sizeof *new->info.ident.ref); } else { /* there can be several unresolved base identities, duplicate them all */ i = -1; do { i = unres_schema_find(unres, i, old, UNRES_TYPE_IDENTREF); if (i != -1) { if (unres_schema_add_str(mod, unres, new, UNRES_TYPE_IDENTREF, unres->str_snode[i]) == -1) { return -1; } } --i; } while (i > -1); } break; case LY_TYPE_INST: new->info.inst.req = old->info.inst.req; break; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: if (old->info.num.range) { new->info.num.range = lys_restr_dup(mod, old->info.num.range, 1, shallow, unres); } break; case LY_TYPE_LEAFREF: if (old->info.lref.path) { new->info.lref.path = lydict_insert(mod->ctx, old->info.lref.path, 0); new->info.lref.req = old->info.lref.req; if (!in_grp && unres_schema_add_node(mod, unres, new, UNRES_TYPE_LEAFREF, parent) == -1) { return -1; } } break; case LY_TYPE_STRING: if (old->info.str.length) { new->info.str.length = lys_restr_dup(mod, old->info.str.length, 1, shallow, unres); } if (old->info.str.pat_count) { new->info.str.patterns = lys_restr_dup(mod, old->info.str.patterns, old->info.str.pat_count, shallow, unres); new->info.str.pat_count = old->info.str.pat_count; #ifdef LY_ENABLED_CACHE if (!in_grp) { new->info.str.patterns_pcre = malloc(new->info.str.pat_count * 2 * sizeof *new->info.str.patterns_pcre); LY_CHECK_ERR_RETURN(!new->info.str.patterns_pcre, LOGMEM(mod->ctx), -1); for (u = 0; u < new->info.str.pat_count; u++) { if (lyp_precompile_pattern(mod->ctx, &new->info.str.patterns[u].expr[1], (pcre**)&new->info.str.patterns_pcre[2 * u], (pcre_extra**)&new->info.str.patterns_pcre[2 * u + 1])) { free(new->info.str.patterns_pcre); new->info.str.patterns_pcre = NULL; return -1; } } } #endif } break; case LY_TYPE_UNION: new->info.uni.has_ptr_type = old->info.uni.has_ptr_type; new->info.uni.count = old->info.uni.count; if (new->info.uni.count) { new->info.uni.types = calloc(new->info.uni.count, sizeof *new->info.uni.types); LY_CHECK_ERR_RETURN(!new->info.uni.types, LOGMEM(mod->ctx), -1); for (u = 0; u < new->info.uni.count; u++) { if (lys_type_dup(mod, parent, &(new->info.uni.types[u]), &(old->info.uni.types[u]), in_grp, shallow, unres)) { return -1; } } } break; default: /* nothing to do for LY_TYPE_BOOL, LY_TYPE_EMPTY */ break; } return EXIT_SUCCESS; } struct yang_type * lys_yang_type_dup(struct lys_module *module, struct lys_node *parent, struct yang_type *old, struct lys_type *type, int in_grp, int shallow, struct unres_schema *unres) { struct yang_type *new; new = calloc(1, sizeof *new); LY_CHECK_ERR_RETURN(!new, LOGMEM(module->ctx), NULL); new->flags = old->flags; new->base = old->base; new->name = lydict_insert(module->ctx, old->name, 0); new->type = type; if (!new->name) { LOGMEM(module->ctx); goto error; } if (type_dup(module, parent, type, old->type, new->base, in_grp, shallow, unres)) { new->type->base = new->base; lys_type_free(module->ctx, new->type, NULL); memset(&new->type->info, 0, sizeof new->type->info); goto error; } return new; error: free(new); return NULL; } int lys_copy_union_leafrefs(struct lys_module *mod, struct lys_node *parent, struct lys_type *type, struct lys_type *prev_new, struct unres_schema *unres) { struct lys_type new; unsigned int i, top_type; struct lys_ext_instance **ext; uint8_t ext_size; void *reloc; if (!prev_new) { /* this is the "top-level" type, meaning it is a real type and no typedef directly above */ top_type = 1; memset(&new, 0, sizeof new); new.base = type->base; new.parent = (struct lys_tpdf *)parent; prev_new = &new; } else { /* this is not top-level type, just a type of a typedef */ top_type = 0; } assert(type->der); if (type->der->module) { /* typedef, skip it, but keep the extensions */ ext_size = type->ext_size; if (lys_ext_dup(mod->ctx, mod, type->ext, type->ext_size, prev_new, LYEXT_PAR_TYPE, &ext, 0, unres)) { return -1; } if (prev_new->ext) { reloc = realloc(prev_new->ext, (prev_new->ext_size + ext_size) * sizeof *prev_new->ext); LY_CHECK_ERR_RETURN(!reloc, LOGMEM(mod->ctx), -1); prev_new->ext = reloc; memcpy(prev_new->ext + prev_new->ext_size, ext, ext_size * sizeof *ext); free(ext); prev_new->ext_size += ext_size; } else { prev_new->ext = ext; prev_new->ext_size = ext_size; } if (lys_copy_union_leafrefs(mod, parent, &type->der->type, prev_new, unres)) { return -1; } } else { /* type, just make a deep copy */ switch (type->base) { case LY_TYPE_UNION: prev_new->info.uni.has_ptr_type = type->info.uni.has_ptr_type; prev_new->info.uni.count = type->info.uni.count; /* this cannot be a typedef anymore */ assert(prev_new->info.uni.count); prev_new->info.uni.types = calloc(prev_new->info.uni.count, sizeof *prev_new->info.uni.types); LY_CHECK_ERR_RETURN(!prev_new->info.uni.types, LOGMEM(mod->ctx), -1); for (i = 0; i < prev_new->info.uni.count; i++) { if (lys_copy_union_leafrefs(mod, parent, &(type->info.uni.types[i]), &(prev_new->info.uni.types[i]), unres)) { return -1; } } prev_new->der = type->der; break; default: if (lys_type_dup(mod, parent, prev_new, type, 0, 0, unres)) { return -1; } break; } } if (top_type) { memcpy(type, prev_new, sizeof *type); } return EXIT_SUCCESS; } API const void * lys_ext_instance_substmt(const struct lys_ext_instance *ext) { if (!ext) { return NULL; } switch (ext->insubstmt) { case LYEXT_SUBSTMT_SELF: case LYEXT_SUBSTMT_MODIFIER: case LYEXT_SUBSTMT_VERSION: return NULL; case LYEXT_SUBSTMT_ARGUMENT: if (ext->parent_type == LYEXT_PAR_EXT) { return ((struct lys_ext_instance*)ext->parent)->arg_value; } break; case LYEXT_SUBSTMT_BASE: if (ext->parent_type == LYEXT_PAR_TYPE) { return ((struct lys_type*)ext->parent)->info.ident.ref[ext->insubstmt_index]; } else if (ext->parent_type == LYEXT_PAR_IDENT) { return ((struct lys_ident*)ext->parent)->base[ext->insubstmt_index]; } break; case LYEXT_SUBSTMT_BELONGSTO: if (ext->parent_type == LYEXT_PAR_MODULE && ((struct lys_module*)ext->parent)->type) { return ((struct lys_submodule*)ext->parent)->belongsto; } break; case LYEXT_SUBSTMT_CONFIG: case LYEXT_SUBSTMT_MANDATORY: if (ext->parent_type == LYEXT_PAR_NODE) { return &((struct lys_node*)ext->parent)->flags; } else if (ext->parent_type == LYEXT_PAR_DEVIATE) { return &((struct lys_deviate*)ext->parent)->flags; } else if (ext->parent_type == LYEXT_PAR_REFINE) { return &((struct lys_refine*)ext->parent)->flags; } break; case LYEXT_SUBSTMT_CONTACT: if (ext->parent_type == LYEXT_PAR_MODULE) { return ((struct lys_module*)ext->parent)->contact; } break; case LYEXT_SUBSTMT_DEFAULT: if (ext->parent_type == LYEXT_PAR_NODE) { switch (((struct lys_node*)ext->parent)->nodetype) { case LYS_LEAF: case LYS_LEAFLIST: /* in case of leaf, the index is supposed to be 0, so it will return the * correct pointer despite the leaf structure does not have dflt as array */ return ((struct lys_node_leaflist*)ext->parent)->dflt[ext->insubstmt_index]; case LYS_CHOICE: return ((struct lys_node_choice*)ext->parent)->dflt; default: /* internal error */ break; } } else if (ext->parent_type == LYEXT_PAR_TPDF) { return ((struct lys_tpdf*)ext->parent)->dflt; } else if (ext->parent_type == LYEXT_PAR_DEVIATE) { return ((struct lys_deviate*)ext->parent)->dflt[ext->insubstmt_index]; } else if (ext->parent_type == LYEXT_PAR_REFINE) { return &((struct lys_refine*)ext->parent)->dflt[ext->insubstmt_index]; } break; case LYEXT_SUBSTMT_DESCRIPTION: switch (ext->parent_type) { case LYEXT_PAR_NODE: return ((struct lys_node*)ext->parent)->dsc; case LYEXT_PAR_MODULE: return ((struct lys_module*)ext->parent)->dsc; case LYEXT_PAR_IMPORT: return ((struct lys_import*)ext->parent)->dsc; case LYEXT_PAR_INCLUDE: return ((struct lys_include*)ext->parent)->dsc; case LYEXT_PAR_EXT: return ((struct lys_ext*)ext->parent)->dsc; case LYEXT_PAR_FEATURE: return ((struct lys_feature*)ext->parent)->dsc; case LYEXT_PAR_TPDF: return ((struct lys_tpdf*)ext->parent)->dsc; case LYEXT_PAR_TYPE_BIT: return ((struct lys_type_bit*)ext->parent)->dsc; case LYEXT_PAR_TYPE_ENUM: return ((struct lys_type_enum*)ext->parent)->dsc; case LYEXT_PAR_RESTR: return ((struct lys_restr*)ext->parent)->dsc; case LYEXT_PAR_WHEN: return ((struct lys_when*)ext->parent)->dsc; case LYEXT_PAR_IDENT: return ((struct lys_ident*)ext->parent)->dsc; case LYEXT_PAR_DEVIATION: return ((struct lys_deviation*)ext->parent)->dsc; case LYEXT_PAR_REVISION: return ((struct lys_revision*)ext->parent)->dsc; case LYEXT_PAR_REFINE: return ((struct lys_refine*)ext->parent)->dsc; default: break; } break; case LYEXT_SUBSTMT_ERRTAG: if (ext->parent_type == LYEXT_PAR_RESTR) { return ((struct lys_restr*)ext->parent)->eapptag; } break; case LYEXT_SUBSTMT_ERRMSG: if (ext->parent_type == LYEXT_PAR_RESTR) { return ((struct lys_restr*)ext->parent)->emsg; } break; case LYEXT_SUBSTMT_DIGITS: if (ext->parent_type == LYEXT_PAR_TYPE && ((struct lys_type*)ext->parent)->base == LY_TYPE_DEC64) { return &((struct lys_type*)ext->parent)->info.dec64.dig; } break; case LYEXT_SUBSTMT_KEY: if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_LIST) { return ((struct lys_node_list*)ext->parent)->keys; } break; case LYEXT_SUBSTMT_MAX: if (ext->parent_type == LYEXT_PAR_NODE) { if (((struct lys_node*)ext->parent)->nodetype == LYS_LIST) { return &((struct lys_node_list*)ext->parent)->max; } else if (((struct lys_node*)ext->parent)->nodetype == LYS_LEAFLIST) { return &((struct lys_node_leaflist*)ext->parent)->max; } } else if (ext->parent_type == LYEXT_PAR_REFINE) { return &((struct lys_refine*)ext->parent)->mod.list.max; } break; case LYEXT_SUBSTMT_MIN: if (ext->parent_type == LYEXT_PAR_NODE) { if (((struct lys_node*)ext->parent)->nodetype == LYS_LIST) { return &((struct lys_node_list*)ext->parent)->min; } else if (((struct lys_node*)ext->parent)->nodetype == LYS_LEAFLIST) { return &((struct lys_node_leaflist*)ext->parent)->min; } } else if (ext->parent_type == LYEXT_PAR_REFINE) { return &((struct lys_refine*)ext->parent)->mod.list.min; } break; case LYEXT_SUBSTMT_NAMESPACE: if (ext->parent_type == LYEXT_PAR_MODULE && !((struct lys_module*)ext->parent)->type) { return ((struct lys_module*)ext->parent)->ns; } break; case LYEXT_SUBSTMT_ORDEREDBY: if (ext->parent_type == LYEXT_PAR_NODE && (((struct lys_node*)ext->parent)->nodetype & (LYS_LIST | LYS_LEAFLIST))) { return &((struct lys_node_list*)ext->parent)->flags; } break; case LYEXT_SUBSTMT_ORGANIZATION: if (ext->parent_type == LYEXT_PAR_MODULE) { return ((struct lys_module*)ext->parent)->org; } break; case LYEXT_SUBSTMT_PATH: if (ext->parent_type == LYEXT_PAR_TYPE && ((struct lys_type*)ext->parent)->base == LY_TYPE_LEAFREF) { return ((struct lys_type*)ext->parent)->info.lref.path; } break; case LYEXT_SUBSTMT_POSITION: if (ext->parent_type == LYEXT_PAR_TYPE_BIT) { return &((struct lys_type_bit*)ext->parent)->pos; } break; case LYEXT_SUBSTMT_PREFIX: if (ext->parent_type == LYEXT_PAR_MODULE) { /* covers also lys_submodule */ return ((struct lys_module*)ext->parent)->prefix; } else if (ext->parent_type == LYEXT_PAR_IMPORT) { return ((struct lys_import*)ext->parent)->prefix; } break; case LYEXT_SUBSTMT_PRESENCE: if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_CONTAINER) { return ((struct lys_node_container*)ext->parent)->presence; } else if (ext->parent_type == LYEXT_PAR_REFINE) { return ((struct lys_refine*)ext->parent)->mod.presence; } break; case LYEXT_SUBSTMT_REFERENCE: switch (ext->parent_type) { case LYEXT_PAR_NODE: return ((struct lys_node*)ext->parent)->ref; case LYEXT_PAR_MODULE: return ((struct lys_module*)ext->parent)->ref; case LYEXT_PAR_IMPORT: return ((struct lys_import*)ext->parent)->ref; case LYEXT_PAR_INCLUDE: return ((struct lys_include*)ext->parent)->ref; case LYEXT_PAR_EXT: return ((struct lys_ext*)ext->parent)->ref; case LYEXT_PAR_FEATURE: return ((struct lys_feature*)ext->parent)->ref; case LYEXT_PAR_TPDF: return ((struct lys_tpdf*)ext->parent)->ref; case LYEXT_PAR_TYPE_BIT: return ((struct lys_type_bit*)ext->parent)->ref; case LYEXT_PAR_TYPE_ENUM: return ((struct lys_type_enum*)ext->parent)->ref; case LYEXT_PAR_RESTR: return ((struct lys_restr*)ext->parent)->ref; case LYEXT_PAR_WHEN: return ((struct lys_when*)ext->parent)->ref; case LYEXT_PAR_IDENT: return ((struct lys_ident*)ext->parent)->ref; case LYEXT_PAR_DEVIATION: return ((struct lys_deviation*)ext->parent)->ref; case LYEXT_PAR_REVISION: return ((struct lys_revision*)ext->parent)->ref; case LYEXT_PAR_REFINE: return ((struct lys_refine*)ext->parent)->ref; default: break; } break; case LYEXT_SUBSTMT_REQINSTANCE: if (ext->parent_type == LYEXT_PAR_TYPE) { if (((struct lys_type*)ext->parent)->base == LY_TYPE_LEAFREF) { return &((struct lys_type*)ext->parent)->info.lref.req; } else if (((struct lys_type*)ext->parent)->base == LY_TYPE_INST) { return &((struct lys_type*)ext->parent)->info.inst.req; } } break; case LYEXT_SUBSTMT_REVISIONDATE: if (ext->parent_type == LYEXT_PAR_IMPORT) { return ((struct lys_import*)ext->parent)->rev; } else if (ext->parent_type == LYEXT_PAR_INCLUDE) { return ((struct lys_include*)ext->parent)->rev; } break; case LYEXT_SUBSTMT_STATUS: switch (ext->parent_type) { case LYEXT_PAR_NODE: case LYEXT_PAR_IDENT: case LYEXT_PAR_TPDF: case LYEXT_PAR_EXT: case LYEXT_PAR_FEATURE: case LYEXT_PAR_TYPE_ENUM: case LYEXT_PAR_TYPE_BIT: /* in all structures the flags member is at the same offset */ return &((struct lys_node*)ext->parent)->flags; default: break; } break; case LYEXT_SUBSTMT_UNIQUE: if (ext->parent_type == LYEXT_PAR_DEVIATE) { return &((struct lys_deviate*)ext->parent)->unique[ext->insubstmt_index]; } else if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_LIST) { return &((struct lys_node_list*)ext->parent)->unique[ext->insubstmt_index]; } break; case LYEXT_SUBSTMT_UNITS: if (ext->parent_type == LYEXT_PAR_NODE && (((struct lys_node*)ext->parent)->nodetype & (LYS_LEAF | LYS_LEAFLIST))) { /* units is at the same offset in both lys_node_leaf and lys_node_leaflist */ return ((struct lys_node_leaf*)ext->parent)->units; } else if (ext->parent_type == LYEXT_PAR_TPDF) { return ((struct lys_tpdf*)ext->parent)->units; } else if (ext->parent_type == LYEXT_PAR_DEVIATE) { return ((struct lys_deviate*)ext->parent)->units; } break; case LYEXT_SUBSTMT_VALUE: if (ext->parent_type == LYEXT_PAR_TYPE_ENUM) { return &((struct lys_type_enum*)ext->parent)->value; } break; case LYEXT_SUBSTMT_YINELEM: if (ext->parent_type == LYEXT_PAR_EXT) { return &((struct lys_ext*)ext->parent)->flags; } break; } LOGINT(ext->module->ctx); return NULL; } static int lys_type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old, int in_grp, int shallow, struct unres_schema *unres) { int i; new->base = old->base; new->der = old->der; new->parent = (struct lys_tpdf *)parent; new->ext_size = old->ext_size; if (lys_ext_dup(mod->ctx, mod, old->ext, old->ext_size, new, LYEXT_PAR_TYPE, &new->ext, shallow, unres)) { return -1; } i = unres_schema_find(unres, -1, old, UNRES_TYPE_DER); if (i != -1) { /* HACK (serious one) for unres */ /* nothing else we can do but duplicate it immediately */ if (((struct lyxml_elem *)old->der)->flags & LY_YANG_STRUCTURE_FLAG) { new->der = (struct lys_tpdf *)lys_yang_type_dup(mod, parent, (struct yang_type *)old->der, new, in_grp, shallow, unres); } else { new->der = (struct lys_tpdf *)lyxml_dup_elem(mod->ctx, (struct lyxml_elem *)old->der, NULL, 1, 0); } /* all these unres additions can fail even though they did not before */ if (!new->der || (unres_schema_add_node(mod, unres, new, UNRES_TYPE_DER, parent) == -1)) { return -1; } return EXIT_SUCCESS; } return type_dup(mod, parent, new, old, new->base, in_grp, shallow, unres); } void lys_type_free(struct ly_ctx *ctx, struct lys_type *type, void (*private_destructor)(const struct lys_node *node, void *priv)) { unsigned int i; assert(ctx); if (!type) { return; } lys_extension_instances_free(ctx, type->ext, type->ext_size, private_destructor); switch (type->base) { case LY_TYPE_BINARY: lys_restr_free(ctx, type->info.binary.length, private_destructor); free(type->info.binary.length); break; case LY_TYPE_BITS: for (i = 0; i < type->info.bits.count; i++) { lydict_remove(ctx, type->info.bits.bit[i].name); lydict_remove(ctx, type->info.bits.bit[i].dsc); lydict_remove(ctx, type->info.bits.bit[i].ref); lys_iffeature_free(ctx, type->info.bits.bit[i].iffeature, type->info.bits.bit[i].iffeature_size, 0, private_destructor); lys_extension_instances_free(ctx, type->info.bits.bit[i].ext, type->info.bits.bit[i].ext_size, private_destructor); } free(type->info.bits.bit); break; case LY_TYPE_DEC64: lys_restr_free(ctx, type->info.dec64.range, private_destructor); free(type->info.dec64.range); break; case LY_TYPE_ENUM: for (i = 0; i < type->info.enums.count; i++) { lydict_remove(ctx, type->info.enums.enm[i].name); lydict_remove(ctx, type->info.enums.enm[i].dsc); lydict_remove(ctx, type->info.enums.enm[i].ref); lys_iffeature_free(ctx, type->info.enums.enm[i].iffeature, type->info.enums.enm[i].iffeature_size, 0, private_destructor); lys_extension_instances_free(ctx, type->info.enums.enm[i].ext, type->info.enums.enm[i].ext_size, private_destructor); } free(type->info.enums.enm); break; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: lys_restr_free(ctx, type->info.num.range, private_destructor); free(type->info.num.range); break; case LY_TYPE_LEAFREF: lydict_remove(ctx, type->info.lref.path); break; case LY_TYPE_STRING: lys_restr_free(ctx, type->info.str.length, private_destructor); free(type->info.str.length); for (i = 0; i < type->info.str.pat_count; i++) { lys_restr_free(ctx, &type->info.str.patterns[i], private_destructor); #ifdef LY_ENABLED_CACHE if (type->info.str.patterns_pcre) { pcre_free((pcre*)type->info.str.patterns_pcre[2 * i]); pcre_free_study((pcre_extra*)type->info.str.patterns_pcre[2 * i + 1]); } #endif } free(type->info.str.patterns); #ifdef LY_ENABLED_CACHE free(type->info.str.patterns_pcre); #endif break; case LY_TYPE_UNION: for (i = 0; i < type->info.uni.count; i++) { lys_type_free(ctx, &type->info.uni.types[i], private_destructor); } free(type->info.uni.types); break; case LY_TYPE_IDENT: free(type->info.ident.ref); break; default: /* nothing to do for LY_TYPE_INST, LY_TYPE_BOOL, LY_TYPE_EMPTY */ break; } } static void lys_tpdf_free(struct ly_ctx *ctx, struct lys_tpdf *tpdf, void (*private_destructor)(const struct lys_node *node, void *priv)) { assert(ctx); if (!tpdf) { return; } lydict_remove(ctx, tpdf->name); lydict_remove(ctx, tpdf->dsc); lydict_remove(ctx, tpdf->ref); lys_type_free(ctx, &tpdf->type, private_destructor); lydict_remove(ctx, tpdf->units); lydict_remove(ctx, tpdf->dflt); lys_extension_instances_free(ctx, tpdf->ext, tpdf->ext_size, private_destructor); } static struct lys_when * lys_when_dup(struct lys_module *mod, struct lys_when *old, int shallow, struct unres_schema *unres) { struct lys_when *new; if (!old) { return NULL; } new = calloc(1, sizeof *new); LY_CHECK_ERR_RETURN(!new, LOGMEM(mod->ctx), NULL); new->cond = lydict_insert(mod->ctx, old->cond, 0); new->dsc = lydict_insert(mod->ctx, old->dsc, 0); new->ref = lydict_insert(mod->ctx, old->ref, 0); new->ext_size = old->ext_size; lys_ext_dup(mod->ctx, mod, old->ext, old->ext_size, new, LYEXT_PAR_WHEN, &new->ext, shallow, unres); return new; } void lys_when_free(struct ly_ctx *ctx, struct lys_when *w, void (*private_destructor)(const struct lys_node *node, void *priv)) { if (!w) { return; } lys_extension_instances_free(ctx, w->ext, w->ext_size, private_destructor); lydict_remove(ctx, w->cond); lydict_remove(ctx, w->dsc); lydict_remove(ctx, w->ref); free(w); } static void lys_augment_free(struct ly_ctx *ctx, struct lys_node_augment *aug, void (*private_destructor)(const struct lys_node *node, void *priv)) { struct lys_node *next, *sub; /* children from a resolved augment are freed under the target node */ if (!aug->target || (aug->flags & LYS_NOTAPPLIED)) { LY_TREE_FOR_SAFE(aug->child, next, sub) { lys_node_free(sub, private_destructor, 0); } } lydict_remove(ctx, aug->target_name); lydict_remove(ctx, aug->dsc); lydict_remove(ctx, aug->ref); lys_iffeature_free(ctx, aug->iffeature, aug->iffeature_size, 0, private_destructor); lys_extension_instances_free(ctx, aug->ext, aug->ext_size, private_destructor); lys_when_free(ctx, aug->when, private_destructor); } static void lys_ident_free(struct ly_ctx *ctx, struct lys_ident *ident, void (*private_destructor)(const struct lys_node *node, void *priv)) { assert(ctx); if (!ident) { return; } free(ident->base); ly_set_free(ident->der); lydict_remove(ctx, ident->name); lydict_remove(ctx, ident->dsc); lydict_remove(ctx, ident->ref); lys_iffeature_free(ctx, ident->iffeature, ident->iffeature_size, 0, private_destructor); lys_extension_instances_free(ctx, ident->ext, ident->ext_size, private_destructor); } static void lys_grp_free(struct ly_ctx *ctx, struct lys_node_grp *grp, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; /* handle only specific parts for LYS_GROUPING */ for (i = 0; i < grp->tpdf_size; i++) { lys_tpdf_free(ctx, &grp->tpdf[i], private_destructor); } free(grp->tpdf); } static void lys_rpc_action_free(struct ly_ctx *ctx, struct lys_node_rpc_action *rpc_act, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; /* handle only specific parts for LYS_GROUPING */ for (i = 0; i < rpc_act->tpdf_size; i++) { lys_tpdf_free(ctx, &rpc_act->tpdf[i], private_destructor); } free(rpc_act->tpdf); } static void lys_inout_free(struct ly_ctx *ctx, struct lys_node_inout *io, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; /* handle only specific parts for LYS_INPUT and LYS_OUTPUT */ for (i = 0; i < io->tpdf_size; i++) { lys_tpdf_free(ctx, &io->tpdf[i], private_destructor); } free(io->tpdf); for (i = 0; i < io->must_size; i++) { lys_restr_free(ctx, &io->must[i], private_destructor); } free(io->must); } static void lys_notif_free(struct ly_ctx *ctx, struct lys_node_notif *notif, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; for (i = 0; i < notif->must_size; i++) { lys_restr_free(ctx, &notif->must[i], private_destructor); } free(notif->must); for (i = 0; i < notif->tpdf_size; i++) { lys_tpdf_free(ctx, &notif->tpdf[i], private_destructor); } free(notif->tpdf); } static void lys_anydata_free(struct ly_ctx *ctx, struct lys_node_anydata *anyxml, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; for (i = 0; i < anyxml->must_size; i++) { lys_restr_free(ctx, &anyxml->must[i], private_destructor); } free(anyxml->must); lys_when_free(ctx, anyxml->when, private_destructor); } static void lys_leaf_free(struct ly_ctx *ctx, struct lys_node_leaf *leaf, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; /* leafref backlinks */ ly_set_free((struct ly_set *)leaf->backlinks); for (i = 0; i < leaf->must_size; i++) { lys_restr_free(ctx, &leaf->must[i], private_destructor); } free(leaf->must); lys_when_free(ctx, leaf->when, private_destructor); lys_type_free(ctx, &leaf->type, private_destructor); lydict_remove(ctx, leaf->units); lydict_remove(ctx, leaf->dflt); } static void lys_leaflist_free(struct ly_ctx *ctx, struct lys_node_leaflist *llist, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; if (llist->backlinks) { /* leafref backlinks */ ly_set_free(llist->backlinks); } for (i = 0; i < llist->must_size; i++) { lys_restr_free(ctx, &llist->must[i], private_destructor); } free(llist->must); for (i = 0; i < llist->dflt_size; i++) { lydict_remove(ctx, llist->dflt[i]); } free(llist->dflt); lys_when_free(ctx, llist->when, private_destructor); lys_type_free(ctx, &llist->type, private_destructor); lydict_remove(ctx, llist->units); } static void lys_list_free(struct ly_ctx *ctx, struct lys_node_list *list, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i, j; /* handle only specific parts for LY_NODE_LIST */ lys_when_free(ctx, list->when, private_destructor); for (i = 0; i < list->must_size; i++) { lys_restr_free(ctx, &list->must[i], private_destructor); } free(list->must); for (i = 0; i < list->tpdf_size; i++) { lys_tpdf_free(ctx, &list->tpdf[i], private_destructor); } free(list->tpdf); free(list->keys); for (i = 0; i < list->unique_size; i++) { for (j = 0; j < list->unique[i].expr_size; j++) { lydict_remove(ctx, list->unique[i].expr[j]); } free(list->unique[i].expr); } free(list->unique); lydict_remove(ctx, list->keys_str); } static void lys_container_free(struct ly_ctx *ctx, struct lys_node_container *cont, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; /* handle only specific parts for LY_NODE_CONTAINER */ lydict_remove(ctx, cont->presence); for (i = 0; i < cont->tpdf_size; i++) { lys_tpdf_free(ctx, &cont->tpdf[i], private_destructor); } free(cont->tpdf); for (i = 0; i < cont->must_size; i++) { lys_restr_free(ctx, &cont->must[i], private_destructor); } free(cont->must); lys_when_free(ctx, cont->when, private_destructor); } static void lys_feature_free(struct ly_ctx *ctx, struct lys_feature *f, void (*private_destructor)(const struct lys_node *node, void *priv)) { lydict_remove(ctx, f->name); lydict_remove(ctx, f->dsc); lydict_remove(ctx, f->ref); lys_iffeature_free(ctx, f->iffeature, f->iffeature_size, 0, private_destructor); ly_set_free(f->depfeatures); lys_extension_instances_free(ctx, f->ext, f->ext_size, private_destructor); } static void lys_extension_free(struct ly_ctx *ctx, struct lys_ext *e, void (*private_destructor)(const struct lys_node *node, void *priv)) { lydict_remove(ctx, e->name); lydict_remove(ctx, e->dsc); lydict_remove(ctx, e->ref); lydict_remove(ctx, e->argument); lys_extension_instances_free(ctx, e->ext, e->ext_size, private_destructor); } static void lys_deviation_free(struct lys_module *module, struct lys_deviation *dev, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i, j, k; struct ly_ctx *ctx; struct lys_node *next, *elem; ctx = module->ctx; lydict_remove(ctx, dev->target_name); lydict_remove(ctx, dev->dsc); lydict_remove(ctx, dev->ref); lys_extension_instances_free(ctx, dev->ext, dev->ext_size, private_destructor); if (!dev->deviate) { return; } /* it could not be applied because it failed to be applied */ if (dev->orig_node) { /* the module was freed, but we only need the context from orig_node, use ours */ if (dev->deviate[0].mod == LY_DEVIATE_NO) { /* it's actually a node subtree, we need to update modules on all the nodes :-/ */ LY_TREE_DFS_BEGIN(dev->orig_node, next, elem) { elem->module = module; LY_TREE_DFS_END(dev->orig_node, next, elem); } lys_node_free(dev->orig_node, NULL, 0); } else { /* it's just a shallow copy, freeing one node */ dev->orig_node->module = module; lys_node_free(dev->orig_node, NULL, 1); } } for (i = 0; i < dev->deviate_size; i++) { lys_extension_instances_free(ctx, dev->deviate[i].ext, dev->deviate[i].ext_size, private_destructor); for (j = 0; j < dev->deviate[i].dflt_size; j++) { lydict_remove(ctx, dev->deviate[i].dflt[j]); } free(dev->deviate[i].dflt); lydict_remove(ctx, dev->deviate[i].units); if (dev->deviate[i].mod == LY_DEVIATE_DEL) { for (j = 0; j < dev->deviate[i].must_size; j++) { lys_restr_free(ctx, &dev->deviate[i].must[j], private_destructor); } free(dev->deviate[i].must); for (j = 0; j < dev->deviate[i].unique_size; j++) { for (k = 0; k < dev->deviate[i].unique[j].expr_size; k++) { lydict_remove(ctx, dev->deviate[i].unique[j].expr[k]); } free(dev->deviate[i].unique[j].expr); } free(dev->deviate[i].unique); } } free(dev->deviate); } static void lys_uses_free(struct ly_ctx *ctx, struct lys_node_uses *uses, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i, j; for (i = 0; i < uses->refine_size; i++) { lydict_remove(ctx, uses->refine[i].target_name); lydict_remove(ctx, uses->refine[i].dsc); lydict_remove(ctx, uses->refine[i].ref); lys_iffeature_free(ctx, uses->refine[i].iffeature, uses->refine[i].iffeature_size, 0, private_destructor); for (j = 0; j < uses->refine[i].must_size; j++) { lys_restr_free(ctx, &uses->refine[i].must[j], private_destructor); } free(uses->refine[i].must); for (j = 0; j < uses->refine[i].dflt_size; j++) { lydict_remove(ctx, uses->refine[i].dflt[j]); } free(uses->refine[i].dflt); lys_extension_instances_free(ctx, uses->refine[i].ext, uses->refine[i].ext_size, private_destructor); if (uses->refine[i].target_type & LYS_CONTAINER) { lydict_remove(ctx, uses->refine[i].mod.presence); } } free(uses->refine); for (i = 0; i < uses->augment_size; i++) { lys_augment_free(ctx, &uses->augment[i], private_destructor); } free(uses->augment); lys_when_free(ctx, uses->when, private_destructor); } void lys_node_free(struct lys_node *node, void (*private_destructor)(const struct lys_node *node, void *priv), int shallow) { struct ly_ctx *ctx; struct lys_node *sub, *next; if (!node) { return; } assert(node->module); assert(node->module->ctx); ctx = node->module->ctx; /* remove private object */ if (node->priv && private_destructor) { private_destructor(node, node->priv); } /* common part */ lydict_remove(ctx, node->name); if (!(node->nodetype & (LYS_INPUT | LYS_OUTPUT))) { lys_iffeature_free(ctx, node->iffeature, node->iffeature_size, shallow, private_destructor); lydict_remove(ctx, node->dsc); lydict_remove(ctx, node->ref); } if (!shallow && !(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) { LY_TREE_FOR_SAFE(node->child, next, sub) { lys_node_free(sub, private_destructor, 0); } } lys_extension_instances_free(ctx, node->ext, node->ext_size, private_destructor); /* specific part */ switch (node->nodetype) { case LYS_CONTAINER: lys_container_free(ctx, (struct lys_node_container *)node, private_destructor); break; case LYS_CHOICE: lys_when_free(ctx, ((struct lys_node_choice *)node)->when, private_destructor); break; case LYS_LEAF: lys_leaf_free(ctx, (struct lys_node_leaf *)node, private_destructor); break; case LYS_LEAFLIST: lys_leaflist_free(ctx, (struct lys_node_leaflist *)node, private_destructor); break; case LYS_LIST: lys_list_free(ctx, (struct lys_node_list *)node, private_destructor); break; case LYS_ANYXML: case LYS_ANYDATA: lys_anydata_free(ctx, (struct lys_node_anydata *)node, private_destructor); break; case LYS_USES: lys_uses_free(ctx, (struct lys_node_uses *)node, private_destructor); break; case LYS_CASE: lys_when_free(ctx, ((struct lys_node_case *)node)->when, private_destructor); break; case LYS_AUGMENT: /* do nothing */ break; case LYS_GROUPING: lys_grp_free(ctx, (struct lys_node_grp *)node, private_destructor); break; case LYS_RPC: case LYS_ACTION: lys_rpc_action_free(ctx, (struct lys_node_rpc_action *)node, private_destructor); break; case LYS_NOTIF: lys_notif_free(ctx, (struct lys_node_notif *)node, private_destructor); break; case LYS_INPUT: case LYS_OUTPUT: lys_inout_free(ctx, (struct lys_node_inout *)node, private_destructor); break; case LYS_EXT: case LYS_UNKNOWN: LOGINT(ctx); break; } /* again common part */ lys_node_unlink(node); free(node); } API struct lys_module * lys_implemented_module(const struct lys_module *mod) { struct ly_ctx *ctx; int i; if (!mod || mod->implemented) { /* invalid argument or the module itself is implemented */ return (struct lys_module *)mod; } ctx = mod->ctx; for (i = 0; i < ctx->models.used; i++) { if (!ctx->models.list[i]->implemented) { continue; } if (ly_strequal(mod->name, ctx->models.list[i]->name, 1)) { /* we have some revision of the module implemented */ return ctx->models.list[i]; } } /* we have no revision of the module implemented, return the module itself, * it is up to the caller to set the module implemented when needed */ return (struct lys_module *)mod; } /* free_int_mods - flag whether to free the internal modules as well */ static void module_free_common(struct lys_module *module, void (*private_destructor)(const struct lys_node *node, void *priv)) { struct ly_ctx *ctx; struct lys_node *next, *iter; unsigned int i; assert(module->ctx); ctx = module->ctx; /* just free the import array, imported modules will stay in the context */ for (i = 0; i < module->imp_size; i++) { lydict_remove(ctx, module->imp[i].prefix); lydict_remove(ctx, module->imp[i].dsc); lydict_remove(ctx, module->imp[i].ref); lys_extension_instances_free(ctx, module->imp[i].ext, module->imp[i].ext_size, private_destructor); } free(module->imp); /* submodules don't have data tree, the data nodes * are placed in the main module altogether */ if (!module->type) { LY_TREE_FOR_SAFE(module->data, next, iter) { lys_node_free(iter, private_destructor, 0); } } lydict_remove(ctx, module->dsc); lydict_remove(ctx, module->ref); lydict_remove(ctx, module->org); lydict_remove(ctx, module->contact); lydict_remove(ctx, module->filepath); /* revisions */ for (i = 0; i < module->rev_size; i++) { lys_extension_instances_free(ctx, module->rev[i].ext, module->rev[i].ext_size, private_destructor); lydict_remove(ctx, module->rev[i].dsc); lydict_remove(ctx, module->rev[i].ref); } free(module->rev); /* identities */ for (i = 0; i < module->ident_size; i++) { lys_ident_free(ctx, &module->ident[i], private_destructor); } module->ident_size = 0; free(module->ident); /* typedefs */ for (i = 0; i < module->tpdf_size; i++) { lys_tpdf_free(ctx, &module->tpdf[i], private_destructor); } free(module->tpdf); /* extension instances */ lys_extension_instances_free(ctx, module->ext, module->ext_size, private_destructor); /* augment */ for (i = 0; i < module->augment_size; i++) { lys_augment_free(ctx, &module->augment[i], private_destructor); } free(module->augment); /* features */ for (i = 0; i < module->features_size; i++) { lys_feature_free(ctx, &module->features[i], private_destructor); } free(module->features); /* deviations */ for (i = 0; i < module->deviation_size; i++) { lys_deviation_free(module, &module->deviation[i], private_destructor); } free(module->deviation); /* extensions */ for (i = 0; i < module->extensions_size; i++) { lys_extension_free(ctx, &module->extensions[i], private_destructor); } free(module->extensions); lydict_remove(ctx, module->name); lydict_remove(ctx, module->prefix); } void lys_submodule_free(struct lys_submodule *submodule, void (*private_destructor)(const struct lys_node *node, void *priv)) { int i; if (!submodule) { return; } /* common part with struct ly_module */ module_free_common((struct lys_module *)submodule, private_destructor); /* include */ for (i = 0; i < submodule->inc_size; i++) { lydict_remove(submodule->ctx, submodule->inc[i].dsc); lydict_remove(submodule->ctx, submodule->inc[i].ref); lys_extension_instances_free(submodule->ctx, submodule->inc[i].ext, submodule->inc[i].ext_size, private_destructor); /* complete submodule free is done only from main module since * submodules propagate their includes to the main module */ } free(submodule->inc); free(submodule); } int lys_ingrouping(const struct lys_node *node) { const struct lys_node *iter = node; assert(node); for(iter = node; iter && iter->nodetype != LYS_GROUPING; iter = lys_parent(iter)); if (!iter) { return 0; } else { return 1; } } /* * final: 0 - do not change config flags; 1 - inherit config flags from the parent; 2 - remove config flags */ static struct lys_node * lys_node_dup_recursion(struct lys_module *module, struct lys_node *parent, const struct lys_node *node, struct unres_schema *unres, int shallow, int finalize) { struct lys_node *retval = NULL, *iter, *p; struct ly_ctx *ctx = module->ctx; int i, j, rc; unsigned int size, size1, size2; struct unres_list_uniq *unique_info; uint16_t flags; struct lys_node_container *cont = NULL; struct lys_node_container *cont_orig = (struct lys_node_container *)node; struct lys_node_choice *choice = NULL; struct lys_node_choice *choice_orig = (struct lys_node_choice *)node; struct lys_node_leaf *leaf = NULL; struct lys_node_leaf *leaf_orig = (struct lys_node_leaf *)node; struct lys_node_leaflist *llist = NULL; struct lys_node_leaflist *llist_orig = (struct lys_node_leaflist *)node; struct lys_node_list *list = NULL; struct lys_node_list *list_orig = (struct lys_node_list *)node; struct lys_node_anydata *any = NULL; struct lys_node_anydata *any_orig = (struct lys_node_anydata *)node; struct lys_node_uses *uses = NULL; struct lys_node_uses *uses_orig = (struct lys_node_uses *)node; struct lys_node_rpc_action *rpc = NULL; struct lys_node_inout *io = NULL; struct lys_node_notif *ntf = NULL; struct lys_node_case *cs = NULL; struct lys_node_case *cs_orig = (struct lys_node_case *)node; /* we cannot just duplicate memory since the strings are stored in * dictionary and we need to update dictionary counters. */ switch (node->nodetype) { case LYS_CONTAINER: cont = calloc(1, sizeof *cont); retval = (struct lys_node *)cont; break; case LYS_CHOICE: choice = calloc(1, sizeof *choice); retval = (struct lys_node *)choice; break; case LYS_LEAF: leaf = calloc(1, sizeof *leaf); retval = (struct lys_node *)leaf; break; case LYS_LEAFLIST: llist = calloc(1, sizeof *llist); retval = (struct lys_node *)llist; break; case LYS_LIST: list = calloc(1, sizeof *list); retval = (struct lys_node *)list; break; case LYS_ANYXML: case LYS_ANYDATA: any = calloc(1, sizeof *any); retval = (struct lys_node *)any; break; case LYS_USES: uses = calloc(1, sizeof *uses); retval = (struct lys_node *)uses; break; case LYS_CASE: cs = calloc(1, sizeof *cs); retval = (struct lys_node *)cs; break; case LYS_RPC: case LYS_ACTION: rpc = calloc(1, sizeof *rpc); retval = (struct lys_node *)rpc; break; case LYS_INPUT: case LYS_OUTPUT: io = calloc(1, sizeof *io); retval = (struct lys_node *)io; break; case LYS_NOTIF: ntf = calloc(1, sizeof *ntf); retval = (struct lys_node *)ntf; break; default: LOGINT(ctx); goto error; } LY_CHECK_ERR_RETURN(!retval, LOGMEM(ctx), NULL); /* * duplicate generic part of the structure */ retval->name = lydict_insert(ctx, node->name, 0); retval->dsc = lydict_insert(ctx, node->dsc, 0); retval->ref = lydict_insert(ctx, node->ref, 0); retval->flags = node->flags; retval->module = module; retval->nodetype = node->nodetype; retval->prev = retval; /* copying unresolved extensions is not supported */ if (unres_schema_find(unres, -1, (void *)&node->ext, UNRES_EXT) == -1) { retval->ext_size = node->ext_size; if (lys_ext_dup(ctx, module, node->ext, node->ext_size, retval, LYEXT_PAR_NODE, &retval->ext, shallow, unres)) { goto error; } } if (node->iffeature_size) { retval->iffeature_size = node->iffeature_size; retval->iffeature = calloc(retval->iffeature_size, sizeof *retval->iffeature); LY_CHECK_ERR_GOTO(!retval->iffeature, LOGMEM(ctx), error); } if (!shallow) { for (i = 0; i < node->iffeature_size; ++i) { resolve_iffeature_getsizes(&node->iffeature[i], &size1, &size2); if (size1) { /* there is something to duplicate */ /* duplicate compiled expression */ size = (size1 / 4) + (size1 % 4) ? 1 : 0; retval->iffeature[i].expr = malloc(size * sizeof *retval->iffeature[i].expr); LY_CHECK_ERR_GOTO(!retval->iffeature[i].expr, LOGMEM(ctx), error); memcpy(retval->iffeature[i].expr, node->iffeature[i].expr, size * sizeof *retval->iffeature[i].expr); /* list of feature pointer must be updated to point to the resulting tree */ retval->iffeature[i].features = calloc(size2, sizeof *retval->iffeature[i].features); LY_CHECK_ERR_GOTO(!retval->iffeature[i].features, LOGMEM(ctx); free(retval->iffeature[i].expr), error); for (j = 0; (unsigned int)j < size2; j++) { rc = unres_schema_dup(module, unres, &node->iffeature[i].features[j], UNRES_IFFEAT, &retval->iffeature[i].features[j]); if (rc == EXIT_FAILURE) { /* feature is resolved in origin, so copy it * - duplication is used for instantiating groupings * and if-feature inside grouping is supposed to be * resolved inside the original grouping, so we want * to keep pointers to features from the grouping * context */ retval->iffeature[i].features[j] = node->iffeature[i].features[j]; } else if (rc == -1) { goto error; } /* else unres was duplicated */ } } /* duplicate if-feature's extensions */ retval->iffeature[i].ext_size = node->iffeature[i].ext_size; if (lys_ext_dup(ctx, module, node->iffeature[i].ext, node->iffeature[i].ext_size, &retval->iffeature[i], LYEXT_PAR_IFFEATURE, &retval->iffeature[i].ext, shallow, unres)) { goto error; } } /* inherit config flags */ p = parent; do { for (iter = p; iter && (iter->nodetype == LYS_USES); iter = iter->parent); } while (iter && iter->nodetype == LYS_AUGMENT && (p = lys_parent(iter))); if (iter) { flags = iter->flags & LYS_CONFIG_MASK; } else { /* default */ flags = LYS_CONFIG_W; } switch (finalize) { case 1: /* inherit config flags */ if (retval->flags & LYS_CONFIG_SET) { /* skip nodes with an explicit config value */ if ((flags & LYS_CONFIG_R) && (retval->flags & LYS_CONFIG_W)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, "true", "config"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children."); goto error; } break; } if (retval->nodetype != LYS_USES) { retval->flags = (retval->flags & ~LYS_CONFIG_MASK) | flags; } /* inherit status */ if ((parent->flags & LYS_STATUS_MASK) > (retval->flags & LYS_STATUS_MASK)) { /* but do it only in case the parent has a stonger status */ retval->flags &= ~LYS_STATUS_MASK; retval->flags |= (parent->flags & LYS_STATUS_MASK); } break; case 2: /* erase config flags */ retval->flags &= ~LYS_CONFIG_MASK; retval->flags &= ~LYS_CONFIG_SET; break; } /* connect it to the parent */ if (lys_node_addchild(parent, retval->module, retval, 0)) { goto error; } /* go recursively */ if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) { LY_TREE_FOR(node->child, iter) { if (iter->nodetype & LYS_GROUPING) { /* do not instantiate groupings */ continue; } if (!lys_node_dup_recursion(module, retval, iter, unres, 0, finalize)) { goto error; } } } if (finalize == 1) { /* check that configuration lists have keys * - we really want to check keys_size in original node, because the keys are * not yet resolved here, it is done below in nodetype specific part */ if ((retval->nodetype == LYS_LIST) && (retval->flags & LYS_CONFIG_W) && !((struct lys_node_list *)node)->keys_size) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, "key", "list"); goto error; } } } else { memcpy(retval->iffeature, node->iffeature, retval->iffeature_size * sizeof *retval->iffeature); } /* * duplicate specific part of the structure */ switch (node->nodetype) { case LYS_CONTAINER: if (cont_orig->when) { cont->when = lys_when_dup(module, cont_orig->when, shallow, unres); LY_CHECK_GOTO(!cont->when, error); } cont->presence = lydict_insert(ctx, cont_orig->presence, 0); if (cont_orig->must) { cont->must = lys_restr_dup(module, cont_orig->must, cont_orig->must_size, shallow, unres); LY_CHECK_GOTO(!cont->must, error); cont->must_size = cont_orig->must_size; } /* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */ break; case LYS_CHOICE: if (choice_orig->when) { choice->when = lys_when_dup(module, choice_orig->when, shallow, unres); LY_CHECK_GOTO(!choice->when, error); } if (!shallow) { if (choice_orig->dflt) { rc = lys_get_sibling(choice->child, lys_node_module(retval)->name, 0, choice_orig->dflt->name, 0, LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST, (const struct lys_node **)&choice->dflt); if (rc) { if (rc == EXIT_FAILURE) { LOGINT(ctx); } goto error; } } else { /* useless to check return value, we don't know whether * there really wasn't any default defined or it just hasn't * been resolved, we just hope for the best :) */ unres_schema_dup(module, unres, choice_orig, UNRES_CHOICE_DFLT, choice); } } else { choice->dflt = choice_orig->dflt; } break; case LYS_LEAF: if (lys_type_dup(module, retval, &(leaf->type), &(leaf_orig->type), lys_ingrouping(retval), shallow, unres)) { goto error; } leaf->units = lydict_insert(module->ctx, leaf_orig->units, 0); if (leaf_orig->dflt) { leaf->dflt = lydict_insert(ctx, leaf_orig->dflt, 0); } if (leaf_orig->must) { leaf->must = lys_restr_dup(module, leaf_orig->must, leaf_orig->must_size, shallow, unres); LY_CHECK_GOTO(!leaf->must, error); leaf->must_size = leaf_orig->must_size; } if (leaf_orig->when) { leaf->when = lys_when_dup(module, leaf_orig->when, shallow, unres); LY_CHECK_GOTO(!leaf->when, error); } break; case LYS_LEAFLIST: if (lys_type_dup(module, retval, &(llist->type), &(llist_orig->type), lys_ingrouping(retval), shallow, unres)) { goto error; } llist->units = lydict_insert(module->ctx, llist_orig->units, 0); llist->min = llist_orig->min; llist->max = llist_orig->max; if (llist_orig->must) { llist->must = lys_restr_dup(module, llist_orig->must, llist_orig->must_size, shallow, unres); LY_CHECK_GOTO(!llist->must, error); llist->must_size = llist_orig->must_size; } if (llist_orig->dflt) { llist->dflt = malloc(llist_orig->dflt_size * sizeof *llist->dflt); LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), error); llist->dflt_size = llist_orig->dflt_size; for (i = 0; i < llist->dflt_size; i++) { llist->dflt[i] = lydict_insert(ctx, llist_orig->dflt[i], 0); } } if (llist_orig->when) { llist->when = lys_when_dup(module, llist_orig->when, shallow, unres); } break; case LYS_LIST: list->min = list_orig->min; list->max = list_orig->max; if (list_orig->must) { list->must = lys_restr_dup(module, list_orig->must, list_orig->must_size, shallow, unres); LY_CHECK_GOTO(!list->must, error); list->must_size = list_orig->must_size; } /* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */ if (list_orig->keys_size) { list->keys = calloc(list_orig->keys_size, sizeof *list->keys); LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error); list->keys_str = lydict_insert(ctx, list_orig->keys_str, 0); list->keys_size = list_orig->keys_size; if (!shallow) { if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) { goto error; } } else { memcpy(list->keys, list_orig->keys, list_orig->keys_size * sizeof *list->keys); } } if (list_orig->unique) { list->unique = malloc(list_orig->unique_size * sizeof *list->unique); LY_CHECK_ERR_GOTO(!list->unique, LOGMEM(ctx), error); list->unique_size = list_orig->unique_size; for (i = 0; i < list->unique_size; ++i) { list->unique[i].expr = malloc(list_orig->unique[i].expr_size * sizeof *list->unique[i].expr); LY_CHECK_ERR_GOTO(!list->unique[i].expr, LOGMEM(ctx), error); list->unique[i].expr_size = list_orig->unique[i].expr_size; for (j = 0; j < list->unique[i].expr_size; j++) { list->unique[i].expr[j] = lydict_insert(ctx, list_orig->unique[i].expr[j], 0); /* if it stays in unres list, duplicate it also there */ unique_info = malloc(sizeof *unique_info); LY_CHECK_ERR_GOTO(!unique_info, LOGMEM(ctx), error); unique_info->list = (struct lys_node *)list; unique_info->expr = list->unique[i].expr[j]; unique_info->trg_type = &list->unique[i].trg_type; unres_schema_dup(module, unres, &list_orig, UNRES_LIST_UNIQ, unique_info); } } } if (list_orig->when) { list->when = lys_when_dup(module, list_orig->when, shallow, unres); LY_CHECK_GOTO(!list->when, error); } break; case LYS_ANYXML: case LYS_ANYDATA: if (any_orig->must) { any->must = lys_restr_dup(module, any_orig->must, any_orig->must_size, shallow, unres); LY_CHECK_GOTO(!any->must, error); any->must_size = any_orig->must_size; } if (any_orig->when) { any->when = lys_when_dup(module, any_orig->when, shallow, unres); LY_CHECK_GOTO(!any->when, error); } break; case LYS_USES: uses->grp = uses_orig->grp; if (uses_orig->when) { uses->when = lys_when_dup(module, uses_orig->when, shallow, unres); LY_CHECK_GOTO(!uses->when, error); } /* it is not needed to duplicate refine, nor augment. They are already applied to the uses children */ break; case LYS_CASE: if (cs_orig->when) { cs->when = lys_when_dup(module, cs_orig->when, shallow, unres); LY_CHECK_GOTO(!cs->when, error); } break; case LYS_ACTION: case LYS_RPC: case LYS_INPUT: case LYS_OUTPUT: case LYS_NOTIF: /* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */ break; default: /* LY_NODE_AUGMENT */ LOGINT(ctx); goto error; } return retval; error: lys_node_free(retval, NULL, 0); return NULL; } int lys_has_xpath(const struct lys_node *node) { assert(node); switch (node->nodetype) { case LYS_AUGMENT: if (((struct lys_node_augment *)node)->when) { return 1; } break; case LYS_CASE: if (((struct lys_node_case *)node)->when) { return 1; } break; case LYS_CHOICE: if (((struct lys_node_choice *)node)->when) { return 1; } break; case LYS_ANYDATA: if (((struct lys_node_anydata *)node)->when || ((struct lys_node_anydata *)node)->must_size) { return 1; } break; case LYS_LEAF: if (((struct lys_node_leaf *)node)->when || ((struct lys_node_leaf *)node)->must_size) { return 1; } break; case LYS_LEAFLIST: if (((struct lys_node_leaflist *)node)->when || ((struct lys_node_leaflist *)node)->must_size) { return 1; } break; case LYS_LIST: if (((struct lys_node_list *)node)->when || ((struct lys_node_list *)node)->must_size) { return 1; } break; case LYS_CONTAINER: if (((struct lys_node_container *)node)->when || ((struct lys_node_container *)node)->must_size) { return 1; } break; case LYS_INPUT: case LYS_OUTPUT: if (((struct lys_node_inout *)node)->must_size) { return 1; } break; case LYS_NOTIF: if (((struct lys_node_notif *)node)->must_size) { return 1; } break; case LYS_USES: if (((struct lys_node_uses *)node)->when) { return 1; } break; default: /* does not have XPath */ break; } return 0; } int lys_type_is_local(const struct lys_type *type) { if (!type->der->module) { /* build-in type */ return 1; } /* type->parent can be either a typedef or leaf/leaf-list, but module pointers are compatible */ return (lys_main_module(type->der->module) == lys_main_module(((struct lys_tpdf *)type->parent)->module)); } /* * shallow - * - do not inherit status from the parent */ struct lys_node * lys_node_dup(struct lys_module *module, struct lys_node *parent, const struct lys_node *node, struct unres_schema *unres, int shallow) { struct lys_node *p = NULL; int finalize = 0; struct lys_node *result, *iter, *next; if (!shallow) { /* get know where in schema tree we are to know what should be done during instantiation of the grouping */ for (p = parent; p && !(p->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC | LYS_ACTION | LYS_GROUPING)); p = lys_parent(p)); finalize = p ? ((p->nodetype == LYS_GROUPING) ? 0 : 2) : 1; } result = lys_node_dup_recursion(module, parent, node, unres, shallow, finalize); if (finalize) { /* check xpath expressions in the instantiated tree */ for (iter = next = result; iter; iter = next) { if (lys_has_xpath(iter) && unres_schema_add_node(module, unres, iter, UNRES_XPATH, NULL) == -1) { /* invalid xpath */ return NULL; } /* select next item */ if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA | LYS_GROUPING)) { /* child exception for leafs, leaflists and anyxml without children, ignore groupings */ next = NULL; } else { next = iter->child; } if (!next) { /* no children, try siblings */ if (iter == result) { /* we are done, no next element to process */ break; } next = iter->next; } while (!next) { /* parent is already processed, go to its sibling */ iter = lys_parent(iter); if (lys_parent(iter) == lys_parent(result)) { /* we are done, no next element to process */ break; } next = iter->next; } } } return result; } /** * @brief Switch contents of two same schema nodes. One of the nodes * is expected to be ashallow copy of the other. * * @param[in] node1 Node whose contents will be switched with \p node2. * @param[in] node2 Node whose contents will be switched with \p node1. */ static void lys_node_switch(struct lys_node *node1, struct lys_node *node2) { const size_t mem_size = 104; uint8_t mem[mem_size]; size_t offset, size; assert((node1->module == node2->module) && ly_strequal(node1->name, node2->name, 1) && (node1->nodetype == node2->nodetype)); /* * Initially, the nodes were really switched in the tree which * caused problems for some other nodes with pointers (augments, leafrefs, ...) * because their pointers were not being updated. Code kept in case there is * a use of it in future (it took some debugging to cover all the cases). * sibling next * if (node1->prev->next) { node1->prev->next = node2; } * sibling prev * if (node1->next) { node1->next->prev = node2; } else { for (child = node1->prev; child->prev->next; child = child->prev); child->prev = node2; } * next * node2->next = node1->next; node1->next = NULL; * prev * if (node1->prev != node1) { node2->prev = node1->prev; } node1->prev = node1; * parent child * if (node1->parent) { if (node1->parent->child == node1) { node1->parent->child = node2; } } else if (lys_main_module(node1->module)->data == node1) { lys_main_module(node1->module)->data = node2; } * parent * node2->parent = node1->parent; node1->parent = NULL; * child parent * LY_TREE_FOR(node1->child, child) { if (child->parent == node1) { child->parent = node2; } } * child * node2->child = node1->child; node1->child = NULL; */ /* switch common node part */ offset = 3 * sizeof(char *); size = sizeof(uint16_t) + 6 * sizeof(uint8_t) + sizeof(struct lys_ext_instance **) + sizeof(struct lys_iffeature *); memcpy(mem, ((uint8_t *)node1) + offset, size); memcpy(((uint8_t *)node1) + offset, ((uint8_t *)node2) + offset, size); memcpy(((uint8_t *)node2) + offset, mem, size); /* switch node-specific data */ offset = sizeof(struct lys_node); switch (node1->nodetype) { case LYS_CONTAINER: size = sizeof(struct lys_node_container) - offset; break; case LYS_CHOICE: size = sizeof(struct lys_node_choice) - offset; break; case LYS_LEAF: size = sizeof(struct lys_node_leaf) - offset; break; case LYS_LEAFLIST: size = sizeof(struct lys_node_leaflist) - offset; break; case LYS_LIST: size = sizeof(struct lys_node_list) - offset; break; case LYS_ANYDATA: case LYS_ANYXML: size = sizeof(struct lys_node_anydata) - offset; break; case LYS_CASE: size = sizeof(struct lys_node_case) - offset; break; case LYS_INPUT: case LYS_OUTPUT: size = sizeof(struct lys_node_inout) - offset; break; case LYS_NOTIF: size = sizeof(struct lys_node_notif) - offset; break; case LYS_RPC: case LYS_ACTION: size = sizeof(struct lys_node_rpc_action) - offset; break; default: assert(0); LOGINT(node1->module->ctx); return; } assert(size <= mem_size); memcpy(mem, ((uint8_t *)node1) + offset, size); memcpy(((uint8_t *)node1) + offset, ((uint8_t *)node2) + offset, size); memcpy(((uint8_t *)node2) + offset, mem, size); /* typedefs were not copied to the backup node, so always reuse them, * in leaves/leaf-lists we must correct the type parent pointer */ switch (node1->nodetype) { case LYS_CONTAINER: ((struct lys_node_container *)node1)->tpdf_size = ((struct lys_node_container *)node2)->tpdf_size; ((struct lys_node_container *)node1)->tpdf = ((struct lys_node_container *)node2)->tpdf; ((struct lys_node_container *)node2)->tpdf_size = 0; ((struct lys_node_container *)node2)->tpdf = NULL; break; case LYS_LIST: ((struct lys_node_list *)node1)->tpdf_size = ((struct lys_node_list *)node2)->tpdf_size; ((struct lys_node_list *)node1)->tpdf = ((struct lys_node_list *)node2)->tpdf; ((struct lys_node_list *)node2)->tpdf_size = 0; ((struct lys_node_list *)node2)->tpdf = NULL; break; case LYS_RPC: case LYS_ACTION: ((struct lys_node_rpc_action *)node1)->tpdf_size = ((struct lys_node_rpc_action *)node2)->tpdf_size; ((struct lys_node_rpc_action *)node1)->tpdf = ((struct lys_node_rpc_action *)node2)->tpdf; ((struct lys_node_rpc_action *)node2)->tpdf_size = 0; ((struct lys_node_rpc_action *)node2)->tpdf = NULL; break; case LYS_NOTIF: ((struct lys_node_notif *)node1)->tpdf_size = ((struct lys_node_notif *)node2)->tpdf_size; ((struct lys_node_notif *)node1)->tpdf = ((struct lys_node_notif *)node2)->tpdf; ((struct lys_node_notif *)node2)->tpdf_size = 0; ((struct lys_node_notif *)node2)->tpdf = NULL; break; case LYS_INPUT: case LYS_OUTPUT: ((struct lys_node_inout *)node1)->tpdf_size = ((struct lys_node_inout *)node2)->tpdf_size; ((struct lys_node_inout *)node1)->tpdf = ((struct lys_node_inout *)node2)->tpdf; ((struct lys_node_inout *)node2)->tpdf_size = 0; ((struct lys_node_inout *)node2)->tpdf = NULL; break; case LYS_LEAF: case LYS_LEAFLIST: ((struct lys_node_leaf *)node1)->type.parent = (struct lys_tpdf *)node1; ((struct lys_node_leaf *)node2)->type.parent = (struct lys_tpdf *)node2; default: break; } } void lys_free(struct lys_module *module, void (*private_destructor)(const struct lys_node *node, void *priv), int free_subs, int remove_from_ctx) { struct ly_ctx *ctx; int i; if (!module) { return; } /* remove schema from the context */ ctx = module->ctx; if (remove_from_ctx && ctx->models.used) { for (i = 0; i < ctx->models.used; i++) { if (ctx->models.list[i] == module) { /* move all the models to not change the order in the list */ ctx->models.used--; memmove(&ctx->models.list[i], ctx->models.list[i + 1], (ctx->models.used - i) * sizeof *ctx->models.list); ctx->models.list[ctx->models.used] = NULL; /* we are done */ break; } } } /* common part with struct ly_submodule */ module_free_common(module, private_destructor); /* include */ for (i = 0; i < module->inc_size; i++) { lydict_remove(ctx, module->inc[i].dsc); lydict_remove(ctx, module->inc[i].ref); lys_extension_instances_free(ctx, module->inc[i].ext, module->inc[i].ext_size, private_destructor); /* complete submodule free is done only from main module since * submodules propagate their includes to the main module */ if (free_subs) { lys_submodule_free(module->inc[i].submodule, private_destructor); } } free(module->inc); /* specific items to free */ lydict_remove(ctx, module->ns); free(module); } static void lys_features_disable_recursive(struct lys_feature *f) { unsigned int i; struct lys_feature *depf; /* disable the feature */ f->flags &= ~LYS_FENABLED; /* by disabling feature we have to disable also all features that depends on this feature */ if (f->depfeatures) { for (i = 0; i < f->depfeatures->number; i++) { depf = (struct lys_feature *)f->depfeatures->set.g[i]; if (depf->flags & LYS_FENABLED) { lys_features_disable_recursive(depf); } } } } /* * op: 1 - enable, 0 - disable */ static int lys_features_change(const struct lys_module *module, const char *name, int op) { int all = 0; int i, j, k; int progress, faili, failj, failk; uint8_t fsize; struct lys_feature *f; if (!module || !name || !strlen(name)) { LOGARG; return EXIT_FAILURE; } if (!strcmp(name, "*")) { /* enable all */ all = 1; } progress = failk = 1; while (progress && failk) { for (i = -1, failk = progress = 0; i < module->inc_size; i++) { if (i == -1) { fsize = module->features_size; f = module->features; } else { fsize = module->inc[i].submodule->features_size; f = module->inc[i].submodule->features; } for (j = 0; j < fsize; j++) { if (all || !strcmp(f[j].name, name)) { if ((op && (f[j].flags & LYS_FENABLED)) || (!op && !(f[j].flags & LYS_FENABLED))) { if (all) { /* skip already set features */ continue; } else { /* feature already set correctly */ return EXIT_SUCCESS; } } if (op) { /* check referenced features if they are enabled */ for (k = 0; k < f[j].iffeature_size; k++) { if (!resolve_iffeature(&f[j].iffeature[k])) { if (all) { faili = i; failj = j; failk = k + 1; break; } else { LOGERR(module->ctx, LY_EINVAL, "Feature \"%s\" is disabled by its %d. if-feature condition.", f[j].name, k + 1); return EXIT_FAILURE; } } } if (k == f[j].iffeature_size) { /* the last check passed, do the change */ f[j].flags |= LYS_FENABLED; progress++; } } else { lys_features_disable_recursive(&f[j]); progress++; } if (!all) { /* stop in case changing a single feature */ return EXIT_SUCCESS; } } } } } if (failk) { /* print info about the last failing feature */ LOGERR(module->ctx, LY_EINVAL, "Feature \"%s\" is disabled by its %d. if-feature condition.", faili == -1 ? module->features[failj].name : module->inc[faili].submodule->features[failj].name, failk); return EXIT_FAILURE; } if (all) { return EXIT_SUCCESS; } else { /* the specified feature not found */ return EXIT_FAILURE; } } API int lys_features_enable(const struct lys_module *module, const char *feature) { return lys_features_change(module, feature, 1); } API int lys_features_disable(const struct lys_module *module, const char *feature) { return lys_features_change(module, feature, 0); } API int lys_features_state(const struct lys_module *module, const char *feature) { int i, j; if (!module || !feature) { return -1; } /* search for the specified feature */ /* module itself */ for (i = 0; i < module->features_size; i++) { if (!strcmp(feature, module->features[i].name)) { if (module->features[i].flags & LYS_FENABLED) { return 1; } else { return 0; } } } /* submodules */ for (j = 0; j < module->inc_size; j++) { for (i = 0; i < module->inc[j].submodule->features_size; i++) { if (!strcmp(feature, module->inc[j].submodule->features[i].name)) { if (module->inc[j].submodule->features[i].flags & LYS_FENABLED) { return 1; } else { return 0; } } } } /* feature definition not found */ return -1; } API const char ** lys_features_list(const struct lys_module *module, uint8_t **states) { const char **result = NULL; int i, j; unsigned int count; if (!module) { return NULL; } count = module->features_size; for (i = 0; i < module->inc_size; i++) { count += module->inc[i].submodule->features_size; } result = malloc((count + 1) * sizeof *result); LY_CHECK_ERR_RETURN(!result, LOGMEM(module->ctx), NULL); if (states) { *states = malloc((count + 1) * sizeof **states); LY_CHECK_ERR_RETURN(!(*states), LOGMEM(module->ctx); free(result), NULL); } count = 0; /* module itself */ for (i = 0; i < module->features_size; i++) { result[count] = module->features[i].name; if (states) { if (module->features[i].flags & LYS_FENABLED) { (*states)[count] = 1; } else { (*states)[count] = 0; } } count++; } /* submodules */ for (j = 0; j < module->inc_size; j++) { for (i = 0; i < module->inc[j].submodule->features_size; i++) { result[count] = module->inc[j].submodule->features[i].name; if (states) { if (module->inc[j].submodule->features[i].flags & LYS_FENABLED) { (*states)[count] = 1; } else { (*states)[count] = 0; } } count++; } } /* terminating NULL byte */ result[count] = NULL; return result; } API struct lys_module * lys_node_module(const struct lys_node *node) { if (!node) { return NULL; } return node->module->type ? ((struct lys_submodule *)node->module)->belongsto : node->module; } API struct lys_module * lys_main_module(const struct lys_module *module) { if (!module) { return NULL; } return (module->type ? ((struct lys_submodule *)module)->belongsto : (struct lys_module *)module); } API struct lys_node * lys_parent(const struct lys_node *node) { struct lys_node *parent; if (!node) { return NULL; } if (node->nodetype == LYS_EXT) { if (((struct lys_ext_instance_complex*)node)->parent_type != LYEXT_PAR_NODE) { return NULL; } parent = (struct lys_node*)((struct lys_ext_instance_complex*)node)->parent; } else if (!node->parent) { return NULL; } else { parent = node->parent; } if (parent->nodetype == LYS_AUGMENT) { return ((struct lys_node_augment *)parent)->target; } else { return parent; } } struct lys_node ** lys_child(const struct lys_node *node, LYS_NODE nodetype) { void *pp; assert(node); if (node->nodetype == LYS_EXT) { pp = lys_ext_complex_get_substmt(lys_snode2stmt(nodetype), (struct lys_ext_instance_complex*)node, NULL); if (!pp) { return NULL; } return (struct lys_node **)pp; } else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { return NULL; } else { return (struct lys_node **)&node->child; } } API void * lys_set_private(const struct lys_node *node, void *priv) { void *prev; if (!node) { LOGARG; return NULL; } prev = node->priv; ((struct lys_node *)node)->priv = priv; return prev; } int lys_leaf_add_leafref_target(struct lys_node_leaf *leafref_target, struct lys_node *leafref) { struct lys_node_leaf *iter; struct ly_ctx *ctx = leafref_target->module->ctx; if (!(leafref_target->nodetype & (LYS_LEAF | LYS_LEAFLIST))) { LOGINT(ctx); return -1; } /* check for config flag */ if (((struct lys_node_leaf*)leafref)->type.info.lref.req != -1 && (leafref->flags & LYS_CONFIG_W) && (leafref_target->flags & LYS_CONFIG_R)) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, leafref, "The leafref %s is config but refers to a non-config %s.", strnodetype(leafref->nodetype), strnodetype(leafref_target->nodetype)); return -1; } /* check for cycles */ for (iter = leafref_target; iter && iter->type.base == LY_TYPE_LEAFREF; iter = iter->type.info.lref.target) { if ((void *)iter == (void *)leafref) { /* cycle detected */ LOGVAL(ctx, LYE_CIRC_LEAFREFS, LY_VLOG_LYS, leafref); return -1; } } /* create fake child - the ly_set structure to hold the list of * leafrefs referencing the leaf(-list) */ if (!leafref_target->backlinks) { leafref_target->backlinks = (void *)ly_set_new(); if (!leafref_target->backlinks) { LOGMEM(ctx); return -1; } } ly_set_add(leafref_target->backlinks, leafref, 0); return 0; } /* not needed currently */ #if 0 static const char * lys_data_path_reverse(const struct lys_node *node, char * const buf, uint32_t buf_len) { struct lys_module *prev_mod; uint32_t str_len, mod_len, buf_idx; if (!(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { LOGINT; return NULL; } buf_idx = buf_len - 1; buf[buf_idx] = '\0'; while (node) { if (lys_parent(node)) { prev_mod = lys_node_module(lys_parent(node)); } else { prev_mod = NULL; } if (node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { str_len = strlen(node->name); if (prev_mod != node->module) { mod_len = strlen(node->module->name); } else { mod_len = 0; } if (buf_idx < 1 + (mod_len ? mod_len + 1 : 0) + str_len) { LOGINT; return NULL; } buf_idx -= 1 + (mod_len ? mod_len + 1 : 0) + str_len; buf[buf_idx] = '/'; if (mod_len) { memcpy(buf + buf_idx + 1, node->module->name, mod_len); buf[buf_idx + 1 + mod_len] = ':'; } memcpy(buf + buf_idx + 1 + (mod_len ? mod_len + 1 : 0), node->name, str_len); } node = lys_parent(node); } return buf + buf_idx; } #endif API struct ly_set * lys_xpath_atomize(const struct lys_node *ctx_node, enum lyxp_node_type ctx_node_type, const char *expr, int options) { struct lyxp_set set; struct ly_set *ret_set; uint32_t i; if (!ctx_node || !expr) { LOGARG; return NULL; } /* adjust the root */ if ((ctx_node_type == LYXP_NODE_ROOT) || (ctx_node_type == LYXP_NODE_ROOT_CONFIG)) { do { ctx_node = lys_getnext(NULL, NULL, lys_node_module(ctx_node), LYS_GETNEXT_NOSTATECHECK); } while ((ctx_node_type == LYXP_NODE_ROOT_CONFIG) && (ctx_node->flags & LYS_CONFIG_R)); } memset(&set, 0, sizeof set); if (options & LYXP_MUST) { options &= ~LYXP_MUST; options |= LYXP_SNODE_MUST; } else if (options & LYXP_WHEN) { options &= ~LYXP_WHEN; options |= LYXP_SNODE_WHEN; } else { options |= LYXP_SNODE; } if (lyxp_atomize(expr, ctx_node, ctx_node_type, &set, options, NULL)) { free(set.val.snodes); LOGVAL(ctx_node->module->ctx, LYE_SPEC, LY_VLOG_LYS, ctx_node, "Resolving XPath expression \"%s\" failed.", expr); return NULL; } ret_set = ly_set_new(); for (i = 0; i < set.used; ++i) { switch (set.val.snodes[i].type) { case LYXP_NODE_ELEM: if (ly_set_add(ret_set, set.val.snodes[i].snode, LY_SET_OPT_USEASLIST) == -1) { ly_set_free(ret_set); free(set.val.snodes); return NULL; } break; default: /* ignore roots, text and attr should not ever appear */ break; } } free(set.val.snodes); return ret_set; } API struct ly_set * lys_node_xpath_atomize(const struct lys_node *node, int options) { const struct lys_node *next, *elem, *parent, *tmp; struct lyxp_set set; struct ly_set *ret_set; uint16_t i; if (!node) { LOGARG; return NULL; } for (parent = node; parent && !(parent->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent)); if (!parent) { /* not in input, output, or notification */ return NULL; } ret_set = ly_set_new(); if (!ret_set) { return NULL; } LY_TREE_DFS_BEGIN(node, next, elem) { if ((options & LYXP_NO_LOCAL) && !(elem->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))) { /* elem has no dependencies from other subtrees and local nodes get discarded */ goto next_iter; } if (lyxp_node_atomize(elem, &set, 0)) { ly_set_free(ret_set); free(set.val.snodes); return NULL; } for (i = 0; i < set.used; ++i) { switch (set.val.snodes[i].type) { case LYXP_NODE_ELEM: if (options & LYXP_NO_LOCAL) { for (tmp = set.val.snodes[i].snode; tmp && (tmp != parent); tmp = lys_parent(tmp)); if (tmp) { /* in local subtree, discard */ break; } } if (ly_set_add(ret_set, set.val.snodes[i].snode, 0) == -1) { ly_set_free(ret_set); free(set.val.snodes); return NULL; } break; default: /* ignore roots, text and attr should not ever appear */ break; } } free(set.val.snodes); if (!(options & LYXP_RECURSIVE)) { break; } next_iter: LY_TREE_DFS_END(node, next, elem); } return ret_set; } /* logs */ int apply_aug(struct lys_node_augment *augment, struct unres_schema *unres) { struct lys_node *child, *parent; int clear_config; unsigned int u; uint8_t *v; struct lys_ext_instance *ext; assert(augment->target && (augment->flags & LYS_NOTAPPLIED)); if (!augment->child) { /* nothing to apply */ goto success; } /* inherit config information from actual parent */ for (parent = augment->target; parent && !(parent->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC)); parent = lys_parent(parent)); clear_config = (parent) ? 1 : 0; LY_TREE_FOR(augment->child, child) { if (inherit_config_flag(child, augment->target->flags & LYS_CONFIG_MASK, clear_config)) { return -1; } } /* inherit extensions if any */ for (u = 0; u < augment->target->ext_size; u++) { ext = augment->target->ext[u]; /* shortcut */ if (ext && ext->def->plugin && (ext->def->plugin->flags & LYEXT_OPT_INHERIT)) { v = malloc(sizeof *v); LY_CHECK_ERR_RETURN(!v, LOGMEM(augment->module->ctx), -1); *v = u; if (unres_schema_add_node(lys_main_module(augment->module), unres, &augment->target->ext, UNRES_EXT_FINALIZE, (struct lys_node *)v) == -1) { /* something really bad happend since the extension finalization is not actually * being resolved while adding into unres, so something more serious with the unres * list itself must happened */ return -1; } } } /* reconnect augmenting data into the target - add them to the target child list */ if (augment->target->child) { child = augment->target->child->prev; child->next = augment->child; augment->target->child->prev = augment->child->prev; augment->child->prev = child; } else { augment->target->child = augment->child; } success: /* remove the flag about not applicability */ augment->flags &= ~LYS_NOTAPPLIED; return EXIT_SUCCESS; } static void remove_aug(struct lys_node_augment *augment) { struct lys_node *last, *elem; if ((augment->flags & LYS_NOTAPPLIED) || !augment->target) { /* skip already not applied augment */ return; } elem = augment->child; if (elem) { LY_TREE_FOR(elem, last) { if (!last->next || (last->next->parent != (struct lys_node *)augment)) { break; } } /* elem is first augment child, last is the last child */ /* parent child ptr */ if (augment->target->child == elem) { augment->target->child = last->next; } /* parent child next ptr */ if (elem->prev->next) { elem->prev->next = last->next; } /* parent child prev ptr */ if (last->next) { last->next->prev = elem->prev; } else if (augment->target->child) { augment->target->child->prev = elem->prev; } /* update augment children themselves */ elem->prev = last; last->next = NULL; } /* augment->target still keeps the resolved target, but for lys_augment_free() * we have to keep information that this augment is not applied to free its data */ augment->flags |= LYS_NOTAPPLIED; } /* * @param[in] module - the module where the deviation is defined */ static void lys_switch_deviation(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres) { int ret, reapply = 0; char *parent_path; struct lys_node *target = NULL, *parent; struct lys_node_inout *inout; struct ly_set *set; if (!dev->deviate) { return; } if (dev->deviate[0].mod == LY_DEVIATE_NO) { if (dev->orig_node) { /* removing not-supported deviation ... */ if (strrchr(dev->target_name, '/') != dev->target_name) { /* ... from a parent */ /* reconnect to its previous position */ parent = dev->orig_node->parent; if (parent && (parent->nodetype == LYS_AUGMENT)) { dev->orig_node->parent = NULL; /* the original node was actually from augment, we have to get know if the augment is * applied (its module is enabled and implemented). If yes, the node will be connected * to the augment and the linkage with the target will be fixed if needed, otherwise * it will be connected only to the augment */ if (!(parent->flags & LYS_NOTAPPLIED)) { /* start with removing augment if applied before adding nodes, we have to make sure * that everything will be connect correctly */ remove_aug((struct lys_node_augment *)parent); reapply = 1; } /* connect the deviated node back into the augment */ lys_node_addchild(parent, NULL, dev->orig_node, 0); if (reapply) { /* augment is supposed to be applied, so fix pointers in target and the status of the original node */ assert(lys_node_module(parent)->implemented); parent->flags |= LYS_NOTAPPLIED; /* allow apply_aug() */ apply_aug((struct lys_node_augment *)parent, unres); } } else if (parent && (parent->nodetype == LYS_USES)) { /* uses child */ lys_node_addchild(parent, NULL, dev->orig_node, 0); } else { /* non-augment, non-toplevel */ parent_path = strndup(dev->target_name, strrchr(dev->target_name, '/') - dev->target_name); ret = resolve_schema_nodeid(parent_path, NULL, module, &set, 0, 1); free(parent_path); if (ret == -1) { LOGINT(module->ctx); ly_set_free(set); return; } target = set->set.s[0]; ly_set_free(set); lys_node_addchild(target, NULL, dev->orig_node, 0); } } else { /* ... from top-level data */ lys_node_addchild(NULL, lys_node_module(dev->orig_node), dev->orig_node, 0); } dev->orig_node = NULL; } else { /* adding not-supported deviation */ ret = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1); if (ret == -1) { LOGINT(module->ctx); ly_set_free(set); return; } target = set->set.s[0]; ly_set_free(set); /* unlink and store the original node */ parent = target->parent; lys_node_unlink(target); if (parent) { if (parent->nodetype & (LYS_AUGMENT | LYS_USES)) { /* hack for augment, because when the original will be sometime reconnected back, we actually need * to reconnect it to both - the augment and its target (which is deduced from the deviations target * path), so we need to remember the augment as an addition */ /* we also need to remember the parent uses so that we connect it back to it when switching deviation state */ target->parent = parent; } else if (parent->nodetype & (LYS_RPC | LYS_ACTION)) { /* re-create implicit node */ inout = calloc(1, sizeof *inout); LY_CHECK_ERR_RETURN(!inout, LOGMEM(module->ctx), ); inout->nodetype = target->nodetype; inout->name = lydict_insert(module->ctx, (inout->nodetype == LYS_INPUT) ? "input" : "output", 0); inout->module = target->module; inout->flags = LYS_IMPLICIT; /* insert it manually */ assert(parent->child && !parent->child->next && (parent->child->nodetype == (inout->nodetype == LYS_INPUT ? LYS_OUTPUT : LYS_INPUT))); parent->child->next = (struct lys_node *)inout; inout->prev = parent->child; parent->child->prev = (struct lys_node *)inout; inout->parent = parent; } } dev->orig_node = target; } } else { ret = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1); if (ret == -1) { LOGINT(module->ctx); ly_set_free(set); return; } target = set->set.s[0]; ly_set_free(set); /* contents are switched */ lys_node_switch(target, dev->orig_node); } } /* temporarily removes or applies deviations, updates module deviation flag accordingly */ void lys_enable_deviations(struct lys_module *module) { uint32_t i = 0, j; const struct lys_module *mod; const char *ptr; struct unres_schema *unres; if (module->deviated) { unres = calloc(1, sizeof *unres); LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), ); while ((mod = ly_ctx_get_module_iter(module->ctx, &i))) { if (mod == module) { continue; } for (j = 0; j < mod->deviation_size; ++j) { ptr = strstr(mod->deviation[j].target_name, module->name); if (ptr && ptr[strlen(module->name)] == ':') { lys_switch_deviation(&mod->deviation[j], mod, unres); } } } assert(module->deviated == 2); module->deviated = 1; for (j = 0; j < module->inc_size; j++) { if (module->inc[j].submodule->deviated) { module->inc[j].submodule->deviated = module->deviated; } } if (unres->count) { resolve_unres_schema(module, unres); } unres_schema_free(module, &unres, 1); } } void lys_disable_deviations(struct lys_module *module) { uint32_t i, j; const struct lys_module *mod; const char *ptr; struct unres_schema *unres; if (module->deviated) { unres = calloc(1, sizeof *unres); LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), ); i = module->ctx->models.used; while (i--) { mod = module->ctx->models.list[i]; if (mod == module) { continue; } j = mod->deviation_size; while (j--) { ptr = strstr(mod->deviation[j].target_name, module->name); if (ptr && ptr[strlen(module->name)] == ':') { lys_switch_deviation(&mod->deviation[j], mod, unres); } } } assert(module->deviated == 1); module->deviated = 2; for (j = 0; j < module->inc_size; j++) { if (module->inc[j].submodule->deviated) { module->inc[j].submodule->deviated = module->deviated; } } if (unres->count) { resolve_unres_schema(module, unres); } unres_schema_free(module, &unres, 1); } } static void apply_dev(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres) { lys_switch_deviation(dev, module, unres); assert(dev->orig_node); lys_node_module(dev->orig_node)->deviated = 1; /* main module */ dev->orig_node->module->deviated = 1; /* possible submodule */ } static void remove_dev(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres) { uint32_t idx = 0, j; const struct lys_module *mod; struct lys_module *target_mod, *target_submod; const char *ptr; if (dev->orig_node) { target_mod = lys_node_module(dev->orig_node); target_submod = dev->orig_node->module; } else { LOGINT(module->ctx); return; } lys_switch_deviation(dev, module, unres); /* clear the deviation flag if possible */ while ((mod = ly_ctx_get_module_iter(module->ctx, &idx))) { if ((mod == module) || (mod == target_mod)) { continue; } for (j = 0; j < mod->deviation_size; ++j) { ptr = strstr(mod->deviation[j].target_name, target_mod->name); if (ptr && (ptr[strlen(target_mod->name)] == ':')) { /* some other module deviation targets the inspected module, flag remains */ break; } } if (j < mod->deviation_size) { break; } } if (!mod) { target_mod->deviated = 0; /* main module */ target_submod->deviated = 0; /* possible submodule */ } } void lys_sub_module_apply_devs_augs(struct lys_module *module) { uint8_t u, v; struct unres_schema *unres; assert(module->implemented); unres = calloc(1, sizeof *unres); LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), ); /* apply deviations */ for (u = 0; u < module->deviation_size; ++u) { apply_dev(&module->deviation[u], module, unres); } /* apply augments */ for (u = 0; u < module->augment_size; ++u) { apply_aug(&module->augment[u], unres); } /* apply deviations and augments defined in submodules */ for (v = 0; v < module->inc_size; ++v) { for (u = 0; u < module->inc[v].submodule->deviation_size; ++u) { apply_dev(&module->inc[v].submodule->deviation[u], module, unres); } for (u = 0; u < module->inc[v].submodule->augment_size; ++u) { apply_aug(&module->inc[v].submodule->augment[u], unres); } } if (unres->count) { resolve_unres_schema(module, unres); } /* nothing else left to do even if something is not resolved */ unres_schema_free(module, &unres, 1); } void lys_sub_module_remove_devs_augs(struct lys_module *module) { uint8_t u, v, w; struct unres_schema *unres; unres = calloc(1, sizeof *unres); LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), ); /* remove applied deviations */ for (u = 0; u < module->deviation_size; ++u) { /* the deviation could not be applied because it failed to be applied in the first place*/ if (module->deviation[u].orig_node) { remove_dev(&module->deviation[u], module, unres); } /* Free the deviation's must array(s). These are shallow copies of the arrays on the target node(s), so a deep free is not needed. */ for (v = 0; v < module->deviation[u].deviate_size; ++v) { if (module->deviation[u].deviate[v].mod == LY_DEVIATE_ADD) { free(module->deviation[u].deviate[v].must); } } } /* remove applied augments */ for (u = 0; u < module->augment_size; ++u) { remove_aug(&module->augment[u]); } /* remove deviation and augments defined in submodules */ for (v = 0; v < module->inc_size && module->inc[v].submodule; ++v) { for (u = 0; u < module->inc[v].submodule->deviation_size; ++u) { if (module->inc[v].submodule->deviation[u].orig_node) { remove_dev(&module->inc[v].submodule->deviation[u], module, unres); } /* Free the deviation's must array(s). These are shallow copies of the arrays on the target node(s), so a deep free is not needed. */ for (w = 0; w < module->inc[v].submodule->deviation[u].deviate_size; ++w) { if (module->inc[v].submodule->deviation[u].deviate[w].mod == LY_DEVIATE_ADD) { free(module->inc[v].submodule->deviation[u].deviate[w].must); } } } for (u = 0; u < module->inc[v].submodule->augment_size; ++u) { remove_aug(&module->inc[v].submodule->augment[u]); } } if (unres->count) { resolve_unres_schema(module, unres); } /* nothing else left to do even if something is not resolved */ unres_schema_free(module, &unres, 1); } int lys_make_implemented_r(struct lys_module *module, struct unres_schema *unres) { struct ly_ctx *ctx; struct lys_node *root, *next, *node; struct lys_module *target_module; uint16_t i, j, k; assert(module->implemented); ctx = module->ctx; for (i = 0; i < ctx->models.used; ++i) { if (module == ctx->models.list[i]) { continue; } if (!strcmp(module->name, ctx->models.list[i]->name) && ctx->models.list[i]->implemented) { LOGERR(ctx, LY_EINVAL, "Module \"%s\" in another revision already implemented.", module->name); return EXIT_FAILURE; } } for (i = 0; i < module->augment_size; i++) { /* make target module implemented if was not */ assert(module->augment[i].target); target_module = lys_node_module(module->augment[i].target); if (!target_module->implemented) { target_module->implemented = 1; if (unres_schema_add_node(target_module, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { return -1; } } /* apply augment */ if ((module->augment[i].flags & LYS_NOTAPPLIED) && apply_aug(&module->augment[i], unres)) { return -1; } } /* identities */ for (i = 0; i < module->ident_size; i++) { for (j = 0; j < module->ident[i].base_size; j++) { resolve_identity_backlink_update(&module->ident[i], module->ident[i].base[j]); } } /* process augments in submodules */ for (i = 0; i < module->inc_size && module->inc[i].submodule; ++i) { module->inc[i].submodule->implemented = 1; for (j = 0; j < module->inc[i].submodule->augment_size; j++) { /* make target module implemented if it was not */ assert(module->inc[i].submodule->augment[j].target); target_module = lys_node_module(module->inc[i].submodule->augment[j].target); if (!target_module->implemented) { target_module->implemented = 1; if (unres_schema_add_node(target_module, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { return -1; } } /* apply augment */ if ((module->inc[i].submodule->augment[j].flags & LYS_NOTAPPLIED) && apply_aug(&module->inc[i].submodule->augment[j], unres)) { return -1; } } /* identities */ for (j = 0; j < module->inc[i].submodule->ident_size; j++) { for (k = 0; k < module->inc[i].submodule->ident[j].base_size; k++) { resolve_identity_backlink_update(&module->inc[i].submodule->ident[j], module->inc[i].submodule->ident[j].base[k]); } } } LY_TREE_FOR(module->data, root) { /* handle leafrefs and recursively change the implemented flags in the leafref targets */ LY_TREE_DFS_BEGIN(root, next, node) { if (node->nodetype == LYS_GROUPING) { goto nextsibling; } if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) { if (((struct lys_node_leaf *)node)->type.base == LY_TYPE_LEAFREF) { if (unres_schema_add_node(module, unres, &((struct lys_node_leaf *)node)->type, UNRES_TYPE_LEAFREF, node) == -1) { return -1; } } } /* modified LY_TREE_DFS_END */ next = node->child; /* child exception for leafs, leaflists and anyxml without children */ if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { next = NULL; } if (!next) { nextsibling: /* no children */ if (node == root) { /* we are done, root has no children */ break; } /* try siblings */ next = node->next; } while (!next) { /* parent is already processed, go to its sibling */ node = lys_parent(node); /* no siblings, go back through parents */ if (lys_parent(node) == lys_parent(root)) { /* we are done, no next element to process */ break; } next = node->next; } } } return EXIT_SUCCESS; } API int lys_set_implemented(const struct lys_module *module) { struct unres_schema *unres; int disabled = 0; if (!module) { LOGARG; return EXIT_FAILURE; } module = lys_main_module(module); if (module->disabled) { disabled = 1; lys_set_enabled(module); } if (module->implemented) { return EXIT_SUCCESS; } unres = calloc(1, sizeof *unres); if (!unres) { LOGMEM(module->ctx); if (disabled) { /* set it back disabled */ lys_set_disabled(module); } return EXIT_FAILURE; } /* recursively make the module implemented */ ((struct lys_module *)module)->implemented = 1; if (lys_make_implemented_r((struct lys_module *)module, unres)) { goto error; } /* try again resolve augments in other modules possibly augmenting this one, * since we have just enabled it */ /* resolve rest of unres items */ if (unres->count && resolve_unres_schema((struct lys_module *)module, unres)) { goto error; } unres_schema_free(NULL, &unres, 0); LOGVRB("Module \"%s%s%s\" now implemented.", module->name, (module->rev_size ? "@" : ""), (module->rev_size ? module->rev[0].date : "")); return EXIT_SUCCESS; error: if (disabled) { /* set it back disabled */ lys_set_disabled(module); } ((struct lys_module *)module)->implemented = 0; unres_schema_free((struct lys_module *)module, &unres, 1); return EXIT_FAILURE; } void lys_submodule_module_data_free(struct lys_submodule *submodule) { struct lys_node *next, *elem; /* remove parsed data */ LY_TREE_FOR_SAFE(submodule->belongsto->data, next, elem) { if (elem->module == (struct lys_module *)submodule) { lys_node_free(elem, NULL, 0); } } } API char * lys_path(const struct lys_node *node, int options) { char *buf = NULL; if (!node) { LOGARG; return NULL; } if (ly_vlog_build_path(LY_VLOG_LYS, node, &buf, (options & LYS_PATH_FIRST_PREFIX) ? 0 : 1, 0)) { return NULL; } return buf; } API char * lys_data_path(const struct lys_node *node) { char *result = NULL, buf[1024]; const char *separator, *name; int i, used; struct ly_set *set; const struct lys_module *prev_mod; if (!node) { LOGARG; return NULL; } buf[0] = '\0'; set = ly_set_new(); LY_CHECK_ERR_GOTO(!set, LOGMEM(node->module->ctx), cleanup); while (node) { ly_set_add(set, (void *)node, 0); do { node = lys_parent(node); } while (node && (node->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT))); } prev_mod = NULL; used = 0; for (i = set->number - 1; i > -1; --i) { node = set->set.s[i]; if (node->nodetype == LYS_EXT) { if (strcmp(((struct lys_ext_instance *)node)->def->name, "yang-data")) { continue; } name = ((struct lys_ext_instance *)node)->arg_value; separator = ":#"; } else { name = node->name; separator = ":"; } used += sprintf(buf + used, "/%s%s%s", (lys_node_module(node) == prev_mod ? "" : lys_node_module(node)->name), (lys_node_module(node) == prev_mod ? "" : separator), name); prev_mod = lys_node_module(node); } result = strdup(buf); LY_CHECK_ERR_GOTO(!result, LOGMEM(node->module->ctx), cleanup); cleanup: ly_set_free(set); return result; } struct lys_node_augment * lys_getnext_target_aug(struct lys_node_augment *last, const struct lys_module *mod, const struct lys_node *aug_target) { struct lys_node *child; struct lys_node_augment *aug; int i, j, last_found; assert(mod && aug_target); if (!last) { last_found = 1; } else { last_found = 0; } /* search module augments */ for (i = 0; i < mod->augment_size; ++i) { if (!mod->augment[i].target) { /* still unresolved, skip */ continue; } if (mod->augment[i].target == aug_target) { if (last_found) { /* next match after last */ return &mod->augment[i]; } if (&mod->augment[i] == last) { last_found = 1; } } } /* search submodule augments */ for (i = 0; i < mod->inc_size; ++i) { for (j = 0; j < mod->inc[i].submodule->augment_size; ++j) { if (!mod->inc[i].submodule->augment[j].target) { continue; } if (mod->inc[i].submodule->augment[j].target == aug_target) { if (last_found) { /* next match after last */ return &mod->inc[i].submodule->augment[j]; } if (&mod->inc[i].submodule->augment[j] == last) { last_found = 1; } } } } /* we also need to check possible augments to choices */ LY_TREE_FOR(aug_target->child, child) { if (child->nodetype == LYS_CHOICE) { aug = lys_getnext_target_aug(last, mod, child); if (aug) { return aug; } } } return NULL; } API struct ly_set * lys_find_path(const struct lys_module *cur_module, const struct lys_node *cur_node, const char *path) { struct ly_set *ret; int rc; if ((!cur_module && !cur_node) || !path) { return NULL; } rc = resolve_schema_nodeid(path, cur_node, cur_module, &ret, 1, 1); if (rc == -1) { return NULL; } return ret; } static void lys_extcomplex_free_str(struct ly_ctx *ctx, struct lys_ext_instance_complex *ext, LY_STMT stmt) { struct lyext_substmt *info; const char **str, ***a; int c; str = lys_ext_complex_get_substmt(stmt, ext, &info); if (!str || !(*str)) { return; } if (info->cardinality >= LY_STMT_CARD_SOME) { /* we have array */ a = (const char ***)str; for (str = (*(const char ***)str), c = 0; str[c]; c++) { lydict_remove(ctx, str[c]); } free(a[0]); if (stmt == LY_STMT_BELONGSTO) { for (str = a[1], c = 0; str[c]; c++) { lydict_remove(ctx, str[c]); } free(a[1]); } else if (stmt == LY_STMT_ARGUMENT) { free(a[1]); } } else { lydict_remove(ctx, str[0]); if (stmt == LY_STMT_BELONGSTO) { lydict_remove(ctx, str[1]); } } } void lys_extension_instances_free(struct ly_ctx *ctx, struct lys_ext_instance **e, unsigned int size, void (*private_destructor)(const struct lys_node *node, void *priv)) { unsigned int i, j, k; struct lyext_substmt *substmt; void **pp, **start; struct lys_node *siter, *snext; #define EXTCOMPLEX_FREE_STRUCT(STMT, TYPE, FUNC, FREE, ARGS...) \ pp = lys_ext_complex_get_substmt(STMT, (struct lys_ext_instance_complex *)e[i], NULL); \ if (!pp || !(*pp)) { break; } \ if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */ \ for (start = pp = *pp; *pp; pp++) { \ FUNC(ctx, (TYPE *)(*pp), ##ARGS, private_destructor); \ if (FREE) { free(*pp); } \ } \ free(start); \ } else { /* single item */ \ FUNC(ctx, (TYPE *)(*pp), ##ARGS, private_destructor); \ if (FREE) { free(*pp); } \ } if (!size || !e) { return; } for (i = 0; i < size; i++) { if (!e[i]) { continue; } if (e[i]->flags & (LYEXT_OPT_INHERIT)) { /* no free, this is just a shadow copy of the original extension instance */ } else { if (e[i]->flags & (LYEXT_OPT_YANG)) { free(e[i]->def); /* remove name of instance extension */ e[i]->def = NULL; yang_free_ext_data((struct yang_ext_substmt *)e[i]->parent); /* remove backup part of yang file */ } /* remove private object */ if (e[i]->priv && private_destructor) { private_destructor((struct lys_node*)e[i], e[i]->priv); } lys_extension_instances_free(ctx, e[i]->ext, e[i]->ext_size, private_destructor); lydict_remove(ctx, e[i]->arg_value); } if (e[i]->def && e[i]->def->plugin && e[i]->def->plugin->type == LYEXT_COMPLEX && ((e[i]->flags & LYEXT_OPT_CONTENT) == 0)) { substmt = ((struct lys_ext_instance_complex *)e[i])->substmt; for (j = 0; substmt[j].stmt; j++) { switch(substmt[j].stmt) { case LY_STMT_DESCRIPTION: case LY_STMT_REFERENCE: case LY_STMT_UNITS: case LY_STMT_ARGUMENT: case LY_STMT_DEFAULT: case LY_STMT_ERRTAG: case LY_STMT_ERRMSG: case LY_STMT_PREFIX: case LY_STMT_NAMESPACE: case LY_STMT_PRESENCE: case LY_STMT_REVISIONDATE: case LY_STMT_KEY: case LY_STMT_BASE: case LY_STMT_BELONGSTO: case LY_STMT_CONTACT: case LY_STMT_ORGANIZATION: case LY_STMT_PATH: lys_extcomplex_free_str(ctx, (struct lys_ext_instance_complex *)e[i], substmt[j].stmt); break; case LY_STMT_TYPE: EXTCOMPLEX_FREE_STRUCT(LY_STMT_TYPE, struct lys_type, lys_type_free, 1); break; case LY_STMT_TYPEDEF: EXTCOMPLEX_FREE_STRUCT(LY_STMT_TYPEDEF, struct lys_tpdf, lys_tpdf_free, 1); break; case LY_STMT_IFFEATURE: EXTCOMPLEX_FREE_STRUCT(LY_STMT_IFFEATURE, struct lys_iffeature, lys_iffeature_free, 0, 1, 0); break; case LY_STMT_MAX: case LY_STMT_MIN: case LY_STMT_POSITION: case LY_STMT_VALUE: pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset]; if (substmt[j].cardinality >= LY_STMT_CARD_SOME && *pp) { for(k = 0; ((uint32_t**)(*pp))[k]; k++) { free(((uint32_t**)(*pp))[k]); } } free(*pp); break; case LY_STMT_DIGITS: if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* free the array */ pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset]; free(*pp); } break; case LY_STMT_MODULE: /* modules are part of the context, so they will be freed there */ if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* free the array */ pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset]; free(*pp); } break; case LY_STMT_ACTION: case LY_STMT_ANYDATA: case LY_STMT_ANYXML: case LY_STMT_CASE: case LY_STMT_CHOICE: case LY_STMT_CONTAINER: case LY_STMT_GROUPING: case LY_STMT_INPUT: case LY_STMT_LEAF: case LY_STMT_LEAFLIST: case LY_STMT_LIST: case LY_STMT_NOTIFICATION: case LY_STMT_OUTPUT: case LY_STMT_RPC: case LY_STMT_USES: pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset]; LY_TREE_FOR_SAFE((struct lys_node *)(*pp), snext, siter) { lys_node_free(siter, NULL, 0); } *pp = NULL; break; case LY_STMT_UNIQUE: pp = lys_ext_complex_get_substmt(LY_STMT_UNIQUE, (struct lys_ext_instance_complex *)e[i], NULL); if (!pp || !(*pp)) { break; } if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */ for (start = pp = *pp; *pp; pp++) { for (k = 0; k < (*(struct lys_unique**)pp)->expr_size; k++) { lydict_remove(ctx, (*(struct lys_unique**)pp)->expr[k]); } free((*(struct lys_unique**)pp)->expr); free(*pp); } free(start); } else { /* single item */ for (k = 0; k < (*(struct lys_unique**)pp)->expr_size; k++) { lydict_remove(ctx, (*(struct lys_unique**)pp)->expr[k]); } free((*(struct lys_unique**)pp)->expr); free(*pp); } break; case LY_STMT_LENGTH: case LY_STMT_MUST: case LY_STMT_PATTERN: case LY_STMT_RANGE: EXTCOMPLEX_FREE_STRUCT(substmt[j].stmt, struct lys_restr, lys_restr_free, 1); break; case LY_STMT_WHEN: EXTCOMPLEX_FREE_STRUCT(LY_STMT_WHEN, struct lys_when, lys_when_free, 0); break; case LY_STMT_REVISION: pp = lys_ext_complex_get_substmt(LY_STMT_REVISION, (struct lys_ext_instance_complex *)e[i], NULL); if (!pp || !(*pp)) { break; } if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */ for (start = pp = *pp; *pp; pp++) { lydict_remove(ctx, (*(struct lys_revision**)pp)->dsc); lydict_remove(ctx, (*(struct lys_revision**)pp)->ref); lys_extension_instances_free(ctx, (*(struct lys_revision**)pp)->ext, (*(struct lys_revision**)pp)->ext_size, private_destructor); free(*pp); } free(start); } else { /* single item */ lydict_remove(ctx, (*(struct lys_revision**)pp)->dsc); lydict_remove(ctx, (*(struct lys_revision**)pp)->ref); lys_extension_instances_free(ctx, (*(struct lys_revision**)pp)->ext, (*(struct lys_revision**)pp)->ext_size, private_destructor); free(*pp); } break; default: /* nothing to free */ break; } } } free(e[i]); } free(e); #undef EXTCOMPLEX_FREE_STRUCT }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_1365_0
crossvul-cpp_data_good_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, version_length; u8 lto_length, wks_length, miux_length; u8 *version_tlv = NULL, *lto_tlv = NULL, *wks_tlv = NULL, *miux_tlv = NULL; __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); if (!version_tlv) { ret = -ENOMEM; goto out; } gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); if (!lto_tlv) { ret = -ENOMEM; goto out; } 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); if (!wks_tlv) { ret = -ENOMEM; goto out; } gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); if (!miux_tlv) { ret = -ENOMEM; goto out; } 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/good_887_1
crossvul-cpp_data_bad_5217_0
/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2014 Nexenta Systems, Inc. All rights reserved. */ /* * Dispatch function for SMB2_FLUSH */ #include <smbsrv/smb2_kproto.h> #include <smbsrv/smb_fsops.h> smb_sdrc_t smb2_flush(smb_request_t *sr) { smb_ofile_t *of = NULL; uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, "wwlqq", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } of = sr->fid_ofile; /* * XXX - todo: * Flush named pipe should drain writes. */ if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0) (void) smb_fsop_commit(sr, of->f_cr, of->f_node); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, "wwl", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_5217_0
crossvul-cpp_data_good_1275_3
/* ** 2015-06-06 ** ** 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 module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. ** ** This file was split off from where.c on 2015-06-06 in order to reduce the ** size of where.c and make it easier to edit. This file contains the routines ** that actually generate the bulk of the WHERE loop code. The original where.c ** file retains the code that does query planning and analysis. */ #include "sqliteInt.h" #include "whereInt.h" #ifndef SQLITE_OMIT_EXPLAIN /* ** Return the name of the i-th column of the pIdx index. */ static const char *explainIndexColumnName(Index *pIdx, int i){ i = pIdx->aiColumn[i]; if( i==XN_EXPR ) return "<expr>"; if( i==XN_ROWID ) return "rowid"; return pIdx->pTable->aCol[i].zName; } /* ** This routine is a helper for explainIndexRange() below ** ** pStr holds the text of an expression that we are building up one term ** at a time. This routine adds a new term to the end of the expression. ** Terms are separated by AND so add the "AND" text for second and subsequent ** terms only. */ static void explainAppendTerm( StrAccum *pStr, /* The text expression being built */ Index *pIdx, /* Index to read column names from */ int nTerm, /* Number of terms */ int iTerm, /* Zero-based index of first term. */ int bAnd, /* Non-zero to append " AND " */ const char *zOp /* Name of the operator */ ){ int i; assert( nTerm>=1 ); if( bAnd ) sqlite3_str_append(pStr, " AND ", 5); if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); for(i=0; i<nTerm; i++){ if( i ) sqlite3_str_append(pStr, ",", 1); sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i)); } if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1); sqlite3_str_append(pStr, zOp, 1); if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); for(i=0; i<nTerm; i++){ if( i ) sqlite3_str_append(pStr, ",", 1); sqlite3_str_append(pStr, "?", 1); } if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1); } /* ** Argument pLevel describes a strategy for scanning table pTab. This ** function appends text to pStr that describes the subset of table ** rows scanned by the strategy in the form of an SQL expression. ** ** For example, if the query: ** ** SELECT * FROM t1 WHERE a=1 AND b>2; ** ** is run and there is an index on (a, b), then this function returns a ** string similar to: ** ** "a=? AND b>?" */ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ Index *pIndex = pLoop->u.btree.pIndex; u16 nEq = pLoop->u.btree.nEq; u16 nSkip = pLoop->nSkip; int i, j; if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; sqlite3_str_append(pStr, " (", 2); for(i=0; i<nEq; i++){ const char *z = explainIndexColumnName(pIndex, i); if( i ) sqlite3_str_append(pStr, " AND ", 5); sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); } j = i; if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); i = 1; } if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); } sqlite3_str_append(pStr, ")", 1); } /* ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode ** is added to the output to describe the table scan strategy in pLevel. ** ** If an OP_Explain opcode is added to the VM, its address is returned. ** Otherwise, if no OP_Explain is coded, zero is returned. */ int sqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ ){ int ret = 0; #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) if( sqlite3ParseToplevel(pParse)->explain==2 ) #endif { struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; Vdbe *v = pParse->pVdbe; /* VM being constructed */ sqlite3 *db = pParse->db; /* Database handle */ int isSearch; /* True for a SEARCH. False for SCAN. */ WhereLoop *pLoop; /* The controlling WhereLoop object */ u32 flags; /* Flags that describe this loop */ char *zMsg; /* Text to add to EQP output */ StrAccum str; /* EQP output string */ char zBuf[100]; /* Initial space for EQP output string */ pLoop = pLevel->pWLoop; flags = pLoop->wsFlags; if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN"); if( pItem->pSelect ){ sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId); }else{ sqlite3_str_appendf(&str, " TABLE %s", pItem->zName); } if( pItem->zAlias ){ sqlite3_str_appendf(&str, " AS %s", pItem->zAlias); } if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ const char *zFmt = 0; Index *pIdx; assert( pLoop->u.btree.pIndex!=0 ); pIdx = pLoop->u.btree.pIndex; assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ if( isSearch ){ zFmt = "PRIMARY KEY"; } }else if( flags & WHERE_PARTIALIDX ){ zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; }else if( flags & WHERE_AUTO_INDEX ){ zFmt = "AUTOMATIC COVERING INDEX"; }else if( flags & WHERE_IDX_ONLY ){ zFmt = "COVERING INDEX %s"; }else{ zFmt = "INDEX %s"; } if( zFmt ){ sqlite3_str_append(&str, " USING ", 7); sqlite3_str_appendf(&str, zFmt, pIdx->zName); explainIndexRange(&str, pLoop); } }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ const char *zRangeOp; if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ zRangeOp = "="; }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ zRangeOp = ">? AND rowid<"; }else if( flags&WHERE_BTM_LIMIT ){ zRangeOp = ">"; }else{ assert( flags&WHERE_TOP_LIMIT); zRangeOp = "<"; } sqlite3_str_appendf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); } #ifndef SQLITE_OMIT_VIRTUALTABLE else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s", pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); } #endif #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS if( pLoop->nOut>=10 ){ sqlite3_str_appendf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); }else{ sqlite3_str_append(&str, " (~1 row)", 9); } #endif zMsg = sqlite3StrAccumFinish(&str); sqlite3ExplainBreakpoint("",zMsg); ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v), pParse->addrExplain, 0, zMsg,P4_DYNAMIC); } return ret; } #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS /* ** Configure the VM passed as the first argument with an ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to ** implement level pLvl. Argument pSrclist is a pointer to the FROM ** clause that the scan reads data from. ** ** If argument addrExplain is not 0, it must be the address of an ** OP_Explain instruction that describes the same loop. */ void sqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ int addrExplain /* Address of OP_Explain (or 0) */ ){ const char *zObj = 0; WhereLoop *pLoop = pLvl->pWLoop; if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ zObj = pLoop->u.btree.pIndex->zName; }else{ zObj = pSrclist->a[pLvl->iFrom].zName; } sqlite3VdbeScanStatus( v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj ); } #endif /* ** Disable a term in the WHERE clause. Except, do not disable the term ** if it controls a LEFT OUTER JOIN and it did not originate in the ON ** or USING clause of that join. ** ** Consider the term t2.z='ok' in the following queries: ** ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' ** ** The t2.z='ok' is disabled in the in (2) because it originates ** in the ON clause. The term is disabled in (3) because it is not part ** of a LEFT OUTER JOIN. In (1), the term is not disabled. ** ** Disabling a term causes that term to not be tested in the inner loop ** of the join. Disabling is an optimization. When terms are satisfied ** by indices, we disable them to prevent redundant tests in the inner ** loop. We would get the correct results if nothing were ever disabled, ** but joins might run a little slower. The trick is to disable as much ** as we can without disabling too much. If we disabled in (1), we'd get ** the wrong answer. See ticket #813. ** ** If all the children of a term are disabled, then that term is also ** automatically disabled. In this way, terms get disabled if derived ** virtual terms are tested first. For example: ** ** x GLOB 'abc*' AND x>='abc' AND x<'acd' ** \___________/ \______/ \_____/ ** parent child1 child2 ** ** Only the parent term was in the original WHERE clause. The child1 ** and child2 terms were added by the LIKE optimization. If both of ** the virtual child terms are valid, then testing of the parent can be ** skipped. ** ** Usually the parent term is marked as TERM_CODED. But if the parent ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. ** The TERM_LIKECOND marking indicates that the term should be coded inside ** a conditional such that is only evaluated on the second pass of a ** LIKE-optimization loop, when scanning BLOBs instead of strings. */ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ int nLoop = 0; assert( pTerm!=0 ); while( (pTerm->wtFlags & TERM_CODED)==0 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) && (pLevel->notReady & pTerm->prereqAll)==0 ){ if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ pTerm->wtFlags |= TERM_LIKECOND; }else{ pTerm->wtFlags |= TERM_CODED; } if( pTerm->iParent<0 ) break; pTerm = &pTerm->pWC->a[pTerm->iParent]; assert( pTerm!=0 ); pTerm->nChild--; if( pTerm->nChild!=0 ) break; nLoop++; } } /* ** Code an OP_Affinity opcode to apply the column affinity string zAff ** to the n registers starting at base. ** ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which ** are no-ops) at the beginning and end of zAff are ignored. If all entries ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated. ** ** This routine makes its own copy of zAff so that the caller is free ** to modify zAff after this routine returns. */ static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ Vdbe *v = pParse->pVdbe; if( zAff==0 ){ assert( pParse->db->mallocFailed ); return; } assert( v!=0 ); /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE ** entries at the beginning and end of the affinity string. */ assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB ); while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){ n--; base++; zAff++; } while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){ n--; } /* Code the OP_Affinity opcode if there is anything left to do. */ if( n>0 ){ sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); } } /* ** Expression pRight, which is the RHS of a comparison operation, is ** either a vector of n elements or, if n==1, a scalar expression. ** Before the comparison operation, affinity zAff is to be applied ** to the pRight values. This function modifies characters within the ** affinity string to SQLITE_AFF_BLOB if either: ** ** * the comparison will be performed with no affinity, or ** * the affinity change in zAff is guaranteed not to change the value. */ static void updateRangeAffinityStr( Expr *pRight, /* RHS of comparison */ int n, /* Number of vector elements in comparison */ char *zAff /* Affinity string to modify */ ){ int i; for(i=0; i<n; i++){ Expr *p = sqlite3VectorFieldSubexpr(pRight, i); if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) ){ zAff[i] = SQLITE_AFF_BLOB; } } } /* ** pX is an expression of the form: (vector) IN (SELECT ...) ** In other words, it is a vector IN operator with a SELECT clause on the ** LHS. But not all terms in the vector are indexable and the terms might ** not be in the correct order for indexing. ** ** This routine makes a copy of the input pX expression and then adjusts ** the vector on the LHS with corresponding changes to the SELECT so that ** the vector contains only index terms and those terms are in the correct ** order. The modified IN expression is returned. The caller is responsible ** for deleting the returned expression. ** ** Example: ** ** CREATE TABLE t1(a,b,c,d,e,f); ** CREATE INDEX t1x1 ON t1(e,c); ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2) ** \_______________________________________/ ** The pX expression ** ** Since only columns e and c can be used with the index, in that order, ** the modified IN expression that is returned will be: ** ** (e,c) IN (SELECT z,x FROM t2) ** ** The reduced pX is different from the original (obviously) and thus is ** only used for indexing, to improve performance. The original unaltered ** IN expression must also be run on each output row for correctness. */ static Expr *removeUnindexableInClauseTerms( Parse *pParse, /* The parsing context */ int iEq, /* Look at loop terms starting here */ WhereLoop *pLoop, /* The current loop */ Expr *pX /* The IN expression to be reduced */ ){ sqlite3 *db = pParse->db; Expr *pNew = sqlite3ExprDup(db, pX, 0); if( db->mallocFailed==0 ){ ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */ ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */ ExprList *pRhs = 0; /* New RHS after modifications */ ExprList *pLhs = 0; /* New LHS after mods */ int i; /* Loop counter */ Select *pSelect; /* Pointer to the SELECT on the RHS */ for(i=iEq; i<pLoop->nLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iField = pLoop->aLTerm[i]->iField - 1; if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */ pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr); pOrigRhs->a[iField].pExpr = 0; assert( pOrigLhs->a[iField].pExpr!=0 ); pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr); pOrigLhs->a[iField].pExpr = 0; } } sqlite3ExprListDelete(db, pOrigRhs); sqlite3ExprListDelete(db, pOrigLhs); pNew->pLeft->x.pList = pLhs; pNew->x.pSelect->pEList = pRhs; if( pLhs && pLhs->nExpr==1 ){ /* Take care here not to generate a TK_VECTOR containing only a ** single value. Since the parser never creates such a vector, some ** of the subroutines do not handle this case. */ Expr *p = pLhs->a[0].pExpr; pLhs->a[0].pExpr = 0; sqlite3ExprDelete(db, pNew->pLeft); pNew->pLeft = p; } pSelect = pNew->x.pSelect; if( pSelect->pOrderBy ){ /* If the SELECT statement has an ORDER BY clause, zero the ** iOrderByCol variables. These are set to non-zero when an ** ORDER BY term exactly matches one of the terms of the ** result-set. Since the result-set of the SELECT statement may ** have been modified or reordered, these variables are no longer ** set correctly. Since setting them is just an optimization, ** it's easiest just to zero them here. */ ExprList *pOrderBy = pSelect->pOrderBy; for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } } #if 0 printf("For indexing, change the IN expr:\n"); sqlite3TreeViewExpr(0, pX, 0); printf("Into:\n"); sqlite3TreeViewExpr(0, pNew, 0); #endif } return pNew; } /* ** Generate code for a single equality term of the WHERE clause. An equality ** term can be either X=expr or X IN (...). pTerm is the term to be ** coded. ** ** The current value for the constraint is left in a register, the index ** of which is returned. An attempt is made store the result in iTarget but ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the ** constraint is a TK_EQ or TK_IS, then the current value might be left in ** some other register and it is the caller's responsibility to compensate. ** ** For a constraint of the form X=expr, the expression is evaluated in ** straight-line code. For constraints of the form X IN (...) ** this routine sets up a loop that will iterate over all values of X. */ static int codeEqualityTerm( Parse *pParse, /* The parsing context */ WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ WhereLevel *pLevel, /* The level of the FROM clause we are working on */ int iEq, /* Index of the equality term within this level */ int bRev, /* True for reverse-order IN operations */ int iTarget /* Attempt to leave results in this register */ ){ Expr *pX = pTerm->pExpr; Vdbe *v = pParse->pVdbe; int iReg; /* Register holding results */ assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); assert( iTarget>0 ); if( pX->op==TK_EQ || pX->op==TK_IS ){ iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); }else if( pX->op==TK_ISNULL ){ iReg = iTarget; sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); #ifndef SQLITE_OMIT_SUBQUERY }else{ int eType = IN_INDEX_NOOP; int iTab; struct InLoop *pIn; WhereLoop *pLoop = pLevel->pWLoop; int i; int nEq = 0; int *aiMap = 0; if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 && pLoop->u.btree.pIndex->aSortOrder[iEq] ){ testcase( iEq==0 ); testcase( bRev ); bRev = !bRev; } assert( pX->op==TK_IN ); iReg = iTarget; for(i=0; i<iEq; i++){ if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ disableTerm(pLevel, pTerm); return iTarget; } } for(i=iEq;i<pLoop->nLTerm; i++){ assert( pLoop->aLTerm[i]!=0 ); if( pLoop->aLTerm[i]->pExpr==pX ) nEq++; } iTab = 0; if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab); }else{ sqlite3 *db = pParse->db; pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); if( !db->mallocFailed ){ aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq); eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab); pTerm->pExpr->iTable = iTab; } sqlite3ExprDelete(db, pX); pX = pTerm->pExpr; } if( eType==IN_INDEX_INDEX_DESC ){ testcase( bRev ); bRev = !bRev; } sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); VdbeCoverageIf(v, bRev); VdbeCoverageIf(v, !bRev); assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); pLoop->wsFlags |= WHERE_IN_ABLE; if( pLevel->u.in.nIn==0 ){ pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); } i = pLevel->u.in.nIn; pLevel->u.in.nIn += nEq; pLevel->u.in.aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); pIn = pLevel->u.in.aInLoop; if( pIn ){ int iMap = 0; /* Index in aiMap[] */ pIn += i; for(i=iEq;i<pLoop->nLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iOut = iReg + i - iEq; if( eType==IN_INDEX_ROWID ){ pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); }else{ int iCol = aiMap ? aiMap[iMap++] : 0; pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); } sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); if( i==iEq ){ pIn->iCur = iTab; pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; if( iEq>0 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){ pIn->iBase = iReg - i; pIn->nPrefix = i; pLoop->wsFlags |= WHERE_IN_EARLYOUT; }else{ pIn->nPrefix = 0; } }else{ pIn->eEndLoopOp = OP_Noop; } pIn++; } } }else{ pLevel->u.in.nIn = 0; } sqlite3DbFree(pParse->db, aiMap); #endif } disableTerm(pLevel, pTerm); return iReg; } /* ** Generate code that will evaluate all == and IN constraints for an ** index scan. ** ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 ** The index has as many as three equality constraints, but in this ** example, the third "c" value is an inequality. So only two ** constraints are coded. This routine will generate code to evaluate ** a==5 and b IN (1,2,3). The current values for a and b will be stored ** in consecutive registers and the index of the first register is returned. ** ** In the example above nEq==2. But this subroutine works for any value ** of nEq including 0. If nEq==0, this routine is nearly a no-op. ** The only thing it does is allocate the pLevel->iMem memory cell and ** compute the affinity string. ** ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that ** occurs after the nEq quality constraints. ** ** This routine allocates a range of nEq+nExtraReg memory cells and returns ** the index of the first memory cell in that range. The code that ** calls this routine will use that memory range to store keys for ** start and termination conditions of the loop. ** key value of the loop. If one or more IN operators appear, then ** this routine allocates an additional nEq memory cells for internal ** use. ** ** Before returning, *pzAff is set to point to a buffer containing a ** copy of the column affinity string of the index allocated using ** sqlite3DbMalloc(). Except, entries in the copy of the string associated ** with equality constraints that use BLOB or NONE affinity are set to ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: ** ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; ** ** In the example above, the index on t1(a) has TEXT affinity. But since ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, ** no conversion should be attempted before using a t2.b value as part of ** a key to search the index. Hence the first byte in the returned affinity ** string in this example would be set to SQLITE_AFF_BLOB. */ static int codeAllEqualityTerms( Parse *pParse, /* Parsing context */ WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ int bRev, /* Reverse the order of IN operators */ int nExtraReg, /* Number of extra registers to allocate */ char **pzAff /* OUT: Set to point to affinity string */ ){ u16 nEq; /* The number of == or IN constraints to code */ u16 nSkip; /* Number of left-most columns to skip */ Vdbe *v = pParse->pVdbe; /* The vm under construction */ Index *pIdx; /* The index being used for this loop */ WhereTerm *pTerm; /* A single constraint term */ WhereLoop *pLoop; /* The WhereLoop object */ int j; /* Loop counter */ int regBase; /* Base register */ int nReg; /* Number of registers to allocate */ char *zAff; /* Affinity string to return */ /* This module is only called on query plans that use an index. */ pLoop = pLevel->pWLoop; assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); nEq = pLoop->u.btree.nEq; nSkip = pLoop->nSkip; pIdx = pLoop->u.btree.pIndex; assert( pIdx!=0 ); /* Figure out how many memory cells we will need then allocate them. */ regBase = pParse->nMem + 1; nReg = pLoop->u.btree.nEq + nExtraReg; pParse->nMem += nReg; zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); assert( zAff!=0 || pParse->db->mallocFailed ); if( nSkip ){ int iIdxCur = pLevel->iIdxCur; sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); j = sqlite3VdbeAddOp0(v, OP_Goto); pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), iIdxCur, 0, regBase, nSkip); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); sqlite3VdbeJumpHere(v, j); for(j=0; j<nSkip; j++){ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); testcase( pIdx->aiColumn[j]==XN_EXPR ); VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); } } /* Evaluate the equality constraints */ assert( zAff==0 || (int)strlen(zAff)>=nEq ); for(j=nSkip; j<nEq; j++){ int r1; pTerm = pLoop->aLTerm[j]; assert( pTerm!=0 ); /* The following testcase is true for indices with redundant columns. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); if( r1!=regBase+j ){ if( nReg==1 ){ sqlite3ReleaseTempReg(pParse, regBase); regBase = r1; }else{ sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); } } if( pTerm->eOperator & WO_IN ){ if( pTerm->pExpr->flags & EP_xIsSelect ){ /* No affinity ever needs to be (or should be) applied to a value ** from the RHS of an "? IN (SELECT ...)" expression. The ** sqlite3FindInIndex() routine has already ensured that the ** affinity of the comparison has been applied to the value. */ if( zAff ) zAff[j] = SQLITE_AFF_BLOB; } }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ Expr *pRight = pTerm->pExpr->pRight; if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); VdbeCoverage(v); } if( zAff ){ if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ zAff[j] = SQLITE_AFF_BLOB; } if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ zAff[j] = SQLITE_AFF_BLOB; } } } } *pzAff = zAff; return regBase; } #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS /* ** If the most recently coded instruction is a constant range constraint ** (a string literal) that originated from the LIKE optimization, then ** set P3 and P5 on the OP_String opcode so that the string will be cast ** to a BLOB at appropriate times. ** ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range ** expression: "x>='ABC' AND x<'abd'". But this requires that the range ** scan loop run twice, once for strings and a second time for BLOBs. ** The OP_String opcodes on the second pass convert the upper and lower ** bound string constants to blobs. This routine makes the necessary changes ** to the OP_String opcodes for that to happen. ** ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then ** only the one pass through the string space is required, so this routine ** becomes a no-op. */ static void whereLikeOptimizationStringFixup( Vdbe *v, /* prepared statement under construction */ WhereLevel *pLevel, /* The loop that contains the LIKE operator */ WhereTerm *pTerm /* The upper or lower bound just coded */ ){ if( pTerm->wtFlags & TERM_LIKEOPT ){ VdbeOp *pOp; assert( pLevel->iLikeRepCntr>0 ); pOp = sqlite3VdbeGetOp(v, -1); assert( pOp!=0 ); assert( pOp->opcode==OP_String8 || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ } } #else # define whereLikeOptimizationStringFixup(A,B,C) #endif #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Information is passed from codeCursorHint() down to individual nodes of ** the expression tree (by sqlite3WalkExpr()) using an instance of this ** structure. */ struct CCurHint { int iTabCur; /* Cursor for the main table */ int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ Index *pIdx; /* The index used to access the table */ }; /* ** This function is called for every node of an expression that is a candidate ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference ** the table CCurHint.iTabCur, verify that the same column can be ** accessed through the index. If it cannot, then set pWalker->eCode to 1. */ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ struct CCurHint *pHint = pWalker->u.pCCurHint; assert( pHint->pIdx!=0 ); if( pExpr->op==TK_COLUMN && pExpr->iTable==pHint->iTabCur && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; } return WRC_Continue; } /* ** Test whether or not expression pExpr, which was part of a WHERE clause, ** should be included in the cursor-hint for a table that is on the rhs ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the ** expression is not suitable. ** ** An expression is unsuitable if it might evaluate to non NULL even if ** a TK_COLUMN node that does affect the value of the expression is set ** to NULL. For example: ** ** col IS NULL ** col IS NOT NULL ** coalesce(col, 1) ** CASE WHEN col THEN 0 ELSE 1 END */ static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_IS || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE ){ pWalker->eCode = 1; }else if( pExpr->op==TK_FUNCTION ){ int d1; char d2[4]; if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ pWalker->eCode = 1; } } return WRC_Continue; } /* ** This function is called on every node of an expression tree used as an ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN ** that accesses any table other than the one identified by ** CCurHint.iTabCur, then do the following: ** ** 1) allocate a register and code an OP_Column instruction to read ** the specified column into the new register, and ** ** 2) transform the expression node to a TK_REGISTER node that reads ** from the newly populated register. ** ** Also, if the node is a TK_COLUMN that does access the table idenified ** by pCCurHint.iTabCur, and an index is being used (which we will ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into ** an access of the index rather than the original table. */ static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ int rc = WRC_Continue; struct CCurHint *pHint = pWalker->u.pCCurHint; if( pExpr->op==TK_COLUMN ){ if( pExpr->iTable!=pHint->iTabCur ){ int reg = ++pWalker->pParse->nMem; /* Register for column value */ sqlite3ExprCode(pWalker->pParse, pExpr, reg); pExpr->op = TK_REGISTER; pExpr->iTable = reg; }else if( pHint->pIdx!=0 ){ pExpr->iTable = pHint->iIdxCur; pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn); assert( pExpr->iColumn>=0 ); } }else if( pExpr->op==TK_AGG_FUNCTION ){ /* An aggregate function in the WHERE clause of a query means this must ** be a correlated sub-query, and expression pExpr is an aggregate from ** the parent context. Do not walk the function arguments in this case. ** ** todo: It should be possible to replace this node with a TK_REGISTER ** expression, as the result of the expression must be stored in a ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ rc = WRC_Prune; } return rc; } /* ** Insert an OP_CursorHint instruction if it is appropriate to do so. */ static void codeCursorHint( struct SrcList_item *pTabItem, /* FROM clause item */ WhereInfo *pWInfo, /* The where clause */ WhereLevel *pLevel, /* Which loop to provide hints for */ WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ ){ Parse *pParse = pWInfo->pParse; sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; Expr *pExpr = 0; WhereLoop *pLoop = pLevel->pWLoop; int iCur; WhereClause *pWC; WhereTerm *pTerm; int i, j; struct CCurHint sHint; Walker sWalker; if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; iCur = pLevel->iTabCur; assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); sHint.iTabCur = iCur; sHint.iIdxCur = pLevel->iIdxCur; sHint.pIdx = pLoop->u.btree.pIndex; memset(&sWalker, 0, sizeof(sWalker)); sWalker.pParse = pParse; sWalker.u.pCCurHint = &sHint; pWC = &pWInfo->sWC; for(i=0; i<pWC->nTerm; i++){ pTerm = &pWC->a[i]; if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( pTerm->prereqAll & pLevel->notReady ) continue; /* Any terms specified as part of the ON(...) clause for any LEFT ** JOIN for which the current table is not the rhs are omitted ** from the cursor-hint. ** ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms ** that were specified as part of the WHERE clause must be excluded. ** This is to address the following: ** ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; ** ** Say there is a single row in t2 that matches (t1.a=t2.b), but its ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is ** pushed down to the cursor, this row is filtered out, causing ** SQLite to synthesize a row of NULL values. Which does match the ** WHERE clause, and so the query returns a row. Which is incorrect. ** ** For the same reason, WHERE terms such as: ** ** WHERE 1 = (t2.c IS NULL) ** ** are also excluded. See codeCursorHintIsOrFunction() for details. */ if( pTabItem->fg.jointype & JT_LEFT ){ Expr *pExpr = pTerm->pExpr; if( !ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable!=pTabItem->iCursor ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintIsOrFunction; sqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } }else{ if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; } /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize ** the cursor. These terms are not needed as hints for a pure range ** scan (that has no == terms) so omit them. */ if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} if( j<pLoop->nLTerm ) continue; } /* No subqueries or non-deterministic functions allowed */ if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; /* For an index scan, make sure referenced columns are actually in ** the index. */ if( sHint.pIdx!=0 ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintCheckExpr; sqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } /* If we survive all prior tests, that means this term is worth hinting */ pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); } if( pExpr!=0 ){ sWalker.xExprCallback = codeCursorHintFixExpr; sqlite3WalkExpr(&sWalker, pExpr); sqlite3VdbeAddOp4(v, OP_CursorHint, (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, (const char*)pExpr, P4_EXPR); } } #else # define codeCursorHint(A,B,C,D) /* No-op */ #endif /* SQLITE_ENABLE_CURSOR_HINTS */ /* ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains ** a rowid value just read from cursor iIdxCur, open on index pIdx. This ** function generates code to do a deferred seek of cursor iCur to the ** rowid stored in register iRowid. ** ** Normally, this is just: ** ** OP_DeferredSeek $iCur $iRowid ** ** However, if the scan currently being coded is a branch of an OR-loop and ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek ** is set to iIdxCur and P4 is set to point to an array of integers ** containing one entry for each column of the table cursor iCur is open ** on. For each table column, if the column is the i'th column of the ** index, then the corresponding array entry is set to (i+1). If the column ** does not appear in the index at all, the array entry is set to 0. */ static void codeDeferredSeek( WhereInfo *pWInfo, /* Where clause context */ Index *pIdx, /* Index scan is using */ int iCur, /* Cursor for IPK b-tree */ int iIdxCur /* Index cursor */ ){ Parse *pParse = pWInfo->pParse; /* Parse context */ Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ assert( iIdxCur>0 ); assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) ){ int i; Table *pTab = pIdx->pTable; int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); if( ai ){ ai[0] = pTab->nCol; for(i=0; i<pIdx->nColumn-1; i++){ int x1, x2; assert( pIdx->aiColumn[i]<pTab->nCol ); x1 = pIdx->aiColumn[i]; x2 = sqlite3TableColumnToStorage(pTab, x1); testcase( x1!=x2 ); if( x1>=0 ) ai[x2+1] = i+1; } sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); } } } /* ** If the expression passed as the second argument is a vector, generate ** code to write the first nReg elements of the vector into an array ** of registers starting with iReg. ** ** If the expression is not a vector, then nReg must be passed 1. In ** this case, generate code to evaluate the expression and leave the ** result in register iReg. */ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ assert( nReg>0 ); if( p && sqlite3ExprIsVector(p) ){ #ifndef SQLITE_OMIT_SUBQUERY if( (p->flags & EP_xIsSelect) ){ Vdbe *v = pParse->pVdbe; int iSelect; assert( p->op==TK_SELECT ); iSelect = sqlite3CodeSubselect(pParse, p); sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); }else #endif { int i; ExprList *pList = p->x.pList; assert( nReg<=pList->nExpr ); for(i=0; i<nReg; i++){ sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); } } }else{ assert( nReg==1 ); sqlite3ExprCode(pParse, p, iReg); } } /* An instance of the IdxExprTrans object carries information about a ** mapping from an expression on table columns into a column in an index ** down through the Walker. */ typedef struct IdxExprTrans { Expr *pIdxExpr; /* The index expression */ int iTabCur; /* The cursor of the corresponding table */ int iIdxCur; /* The cursor for the index */ int iIdxCol; /* The column for the index */ int iTabCol; /* The column for the table */ } IdxExprTrans; /* The walker node callback used to transform matching expressions into ** a reference to an index column for an index on an expression. ** ** If pExpr matches, then transform it into a reference to the index column ** that contains the value of pExpr. */ static int whereIndexExprTransNode(Walker *p, Expr *pExpr){ IdxExprTrans *pX = p->u.pIdxTrans; if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){ pExpr->affExpr = sqlite3ExprAffinity(pExpr); pExpr->op = TK_COLUMN; pExpr->iTable = pX->iIdxCur; pExpr->iColumn = pX->iIdxCol; pExpr->y.pTab = 0; return WRC_Prune; }else{ return WRC_Continue; } } #ifndef SQLITE_OMIT_GENERATED_COLUMNS /* A walker node callback that translates a column reference to a table ** into a corresponding column reference of an index. */ static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){ if( pExpr->op==TK_COLUMN ){ IdxExprTrans *pX = p->u.pIdxTrans; if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){ assert( pExpr->y.pTab!=0 ); pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn); pExpr->iTable = pX->iIdxCur; pExpr->iColumn = pX->iIdxCol; pExpr->y.pTab = 0; } } return WRC_Continue; } #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ /* ** For an indexes on expression X, locate every instance of expression X ** in pExpr and change that subexpression into a reference to the appropriate ** column of the index. ** ** 2019-10-24: Updated to also translate references to a VIRTUAL column in ** the table into references to the corresponding (stored) column of the ** index. */ static void whereIndexExprTrans( Index *pIdx, /* The Index */ int iTabCur, /* Cursor of the table that is being indexed */ int iIdxCur, /* Cursor of the index itself */ WhereInfo *pWInfo /* Transform expressions in this WHERE clause */ ){ int iIdxCol; /* Column number of the index */ ExprList *aColExpr; /* Expressions that are indexed */ Table *pTab; Walker w; IdxExprTrans x; aColExpr = pIdx->aColExpr; if( aColExpr==0 && !pIdx->bHasVCol ){ /* The index does not reference any expressions or virtual columns ** so no translations are needed. */ return; } pTab = pIdx->pTable; memset(&w, 0, sizeof(w)); w.u.pIdxTrans = &x; x.iTabCur = iTabCur; x.iIdxCur = iIdxCur; for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){ i16 iRef = pIdx->aiColumn[iIdxCol]; if( iRef==XN_EXPR ){ assert( aColExpr->a[iIdxCol].pExpr!=0 ); x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; w.xExprCallback = whereIndexExprTransNode; #ifndef SQLITE_OMIT_GENERATED_COLUMNS }else if( iRef>=0 && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0 ){ x.iTabCol = iRef; w.xExprCallback = whereIndexExprTransColumn; #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ }else{ continue; } x.iIdxCol = iIdxCol; sqlite3WalkExpr(&w, pWInfo->pWhere); sqlite3WalkExprList(&w, pWInfo->pOrderBy); sqlite3WalkExprList(&w, pWInfo->pResultSet); } } /* ** The pTruth expression is always true because it is the WHERE clause ** a partial index that is driving a query loop. Look through all of the ** WHERE clause terms on the query, and if any of those terms must be ** true because pTruth is true, then mark those WHERE clause terms as ** coded. */ static void whereApplyPartialIndexConstraints( Expr *pTruth, int iTabCur, WhereClause *pWC ){ int i; WhereTerm *pTerm; while( pTruth->op==TK_AND ){ whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC); pTruth = pTruth->pRight; } for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ Expr *pExpr; if( pTerm->wtFlags & TERM_CODED ) continue; pExpr = pTerm->pExpr; if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){ pTerm->wtFlags |= TERM_CODED; } } } /* ** Generate code for the start of the iLevel-th loop in the WHERE clause ** implementation described by pWInfo. */ Bitmask sqlite3WhereCodeOneLoopStart( Parse *pParse, /* Parsing context */ Vdbe *v, /* Prepared statement under construction */ WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ WhereLevel *pLevel, /* The current level pointer */ Bitmask notReady /* Which tables are currently available */ ){ int j, k; /* Loop counters */ int iCur; /* The VDBE cursor for the table */ int addrNxt; /* Where to jump to continue with the next IN case */ int bRev; /* True if we need to scan in reverse order */ WhereLoop *pLoop; /* The WhereLoop object being coded */ WhereClause *pWC; /* Decomposition of the entire WHERE clause */ WhereTerm *pTerm; /* A WHERE clause term */ sqlite3 *db; /* Database connection */ struct SrcList_item *pTabItem; /* FROM clause term being coded */ int addrBrk; /* Jump here to break out of the loop */ int addrHalt; /* addrBrk for the outermost loop */ int addrCont; /* Jump here to continue with next cycle */ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ int iReleaseReg = 0; /* Temp register to free before returning */ Index *pIdx = 0; /* Index used by loop (if any) */ int iLoop; /* Iteration of constraint generator loop */ pWC = &pWInfo->sWC; db = pParse->db; pLoop = pLevel->pWLoop; pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; iCur = pTabItem->iCursor; pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); bRev = (pWInfo->revMask>>iLevel)&1; VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); /* Create labels for the "break" and "continue" instructions ** for the current loop. Jump to addrBrk to break out of a loop. ** Jump to cont to go immediately to the next iteration of the ** loop. ** ** When there is an IN operator, we also have a "addrNxt" label that ** means to continue with the next IN value combination. When ** there are no IN operators in the constraints, the "addrNxt" label ** is the same as "addrBrk". */ addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); /* If this is the right table of a LEFT OUTER JOIN, allocate and ** initialize a memory cell that records if this table matches any ** row of the left table of the join. */ assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0 ); if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ pLevel->iLeftJoin = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); VdbeComment((v, "init LEFT JOIN no-match flag")); } /* Compute a safe address to jump to if we discover that the table for ** this loop is empty and can never contribute content. */ for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){} addrHalt = pWInfo->a[j].addrBrk; /* Special case of a FROM clause subquery implemented as a co-routine */ if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); VdbeCoverage(v); VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); pLevel->op = OP_Goto; }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ /* Case 1: The table is a virtual-table. Use the VFilter and VNext ** to access the data. */ int iReg; /* P3 Value for OP_VFilter */ int addrNotFound; int nConstraint = pLoop->nLTerm; int iIn; /* Counter for IN constraints */ iReg = sqlite3GetTempRange(pParse, nConstraint+2); addrNotFound = pLevel->addrBrk; for(j=0; j<nConstraint; j++){ int iTarget = iReg+j+2; pTerm = pLoop->aLTerm[j]; if( NEVER(pTerm==0) ) continue; if( pTerm->eOperator & WO_IN ){ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); addrNotFound = pLevel->addrNxt; }else{ Expr *pRight = pTerm->pExpr->pRight; codeExprOrVector(pParse, pRight, iTarget, 1); } } sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pLoop->u.vtab.idxStr, pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); VdbeCoverage(v); pLoop->u.vtab.needFree = 0; pLevel->p1 = iCur; pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; pLevel->p2 = sqlite3VdbeCurrentAddr(v); iIn = pLevel->u.in.nIn; for(j=nConstraint-1; j>=0; j--){ pTerm = pLoop->aLTerm[j]; if( (pTerm->eOperator & WO_IN)!=0 ) iIn--; if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ disableTerm(pLevel, pTerm); }else if( (pTerm->eOperator & WO_IN)!=0 && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1 ){ Expr *pCompare; /* The comparison operator */ Expr *pRight; /* RHS of the comparison */ VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ /* Reload the constraint value into reg[iReg+j+2]. The same value ** was loaded into the same register prior to the OP_VFilter, but ** the xFilter implementation might have changed the datatype or ** encoding of the value in the register, so it *must* be reloaded. */ assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); if( !db->mallocFailed ){ assert( iIn>=0 && iIn<pLevel->u.in.nIn ); pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop); assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); testcase( pOp->opcode==OP_Rowid ); sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); } /* Generate code that will continue to the next row if ** the IN constraint is not satisfied */ pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); assert( pCompare!=0 || db->mallocFailed ); if( pCompare ){ pCompare->pLeft = pTerm->pExpr->pLeft; pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); if( pRight ){ pRight->iTable = iReg+j+2; sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); } pCompare->pLeft = 0; sqlite3ExprDelete(db, pCompare); } } } assert( iIn==0 || db->mallocFailed ); /* These registers need to be preserved in case there is an IN operator ** loop. So we could deallocate the registers here (and potentially ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems ** simpler and safer to simply not reuse the registers. ** ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); */ }else #endif /* SQLITE_OMIT_VIRTUALTABLE */ if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 ){ /* Case 2: We can directly reference a single row using an ** equality comparison against the ROWID field. Or ** we reference multiple rows using a "rowid IN (...)" ** construct. */ assert( pLoop->u.btree.nEq==1 ); pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->pExpr!=0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); iReleaseReg = ++pParse->nMem; iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); addrNxt = pLevel->addrNxt; sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); VdbeCoverage(v); pLevel->op = OP_Noop; if( (pTerm->prereqAll & pLevel->notReady)==0 ){ pTerm->wtFlags |= TERM_CODED; } }else if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 ){ /* Case 3: We have an inequality comparison against the ROWID field. */ int testOp = OP_Noop; int start; int memEndValue = 0; WhereTerm *pStart, *pEnd; j = 0; pStart = pEnd = 0; if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; assert( pStart!=0 || pEnd!=0 ); if( bRev ){ pTerm = pStart; pStart = pEnd; pEnd = pTerm; } codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); if( pStart ){ Expr *pX; /* The expression that defines the start bound */ int r1, rTemp; /* Registers for holding the start boundary */ int op; /* Cursor seek operation */ /* The following constant maps TK_xx codes into corresponding ** seek opcodes. It depends on a particular ordering of TK_xx */ const u8 aMoveOp[] = { /* TK_GT */ OP_SeekGT, /* TK_LE */ OP_SeekLE, /* TK_LT */ OP_SeekLT, /* TK_GE */ OP_SeekGE }; assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ assert( (pStart->wtFlags & TERM_VNULL)==0 ); testcase( pStart->wtFlags & TERM_VIRTUAL ); pX = pStart->pExpr; assert( pX!=0 ); testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ if( sqlite3ExprIsVector(pX->pRight) ){ r1 = rTemp = sqlite3GetTempReg(pParse); codeExprOrVector(pParse, pX->pRight, r1, 1); testcase( pX->op==TK_GT ); testcase( pX->op==TK_GE ); testcase( pX->op==TK_LT ); testcase( pX->op==TK_LE ); op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1]; assert( pX->op!=TK_GT || op==OP_SeekGE ); assert( pX->op!=TK_GE || op==OP_SeekGE ); assert( pX->op!=TK_LT || op==OP_SeekLE ); assert( pX->op!=TK_LE || op==OP_SeekLE ); }else{ r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); disableTerm(pLevel, pStart); op = aMoveOp[(pX->op - TK_GT)]; } sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); VdbeComment((v, "pk")); VdbeCoverageIf(v, pX->op==TK_GT); VdbeCoverageIf(v, pX->op==TK_LE); VdbeCoverageIf(v, pX->op==TK_LT); VdbeCoverageIf(v, pX->op==TK_GE); sqlite3ReleaseTempReg(pParse, rTemp); }else{ sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); } if( pEnd ){ Expr *pX; pX = pEnd->pExpr; assert( pX!=0 ); assert( (pEnd->wtFlags & TERM_VNULL)==0 ); testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ testcase( pEnd->wtFlags & TERM_VIRTUAL ); memEndValue = ++pParse->nMem; codeExprOrVector(pParse, pX->pRight, memEndValue, 1); if( 0==sqlite3ExprIsVector(pX->pRight) && (pX->op==TK_LT || pX->op==TK_GT) ){ testOp = bRev ? OP_Le : OP_Ge; }else{ testOp = bRev ? OP_Lt : OP_Gt; } if( 0==sqlite3ExprIsVector(pX->pRight) ){ disableTerm(pLevel, pEnd); } } start = sqlite3VdbeCurrentAddr(v); pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iCur; pLevel->p2 = start; assert( pLevel->p5==0 ); if( testOp!=OP_Noop ){ iRowidReg = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); VdbeCoverageIf(v, testOp==OP_Le); VdbeCoverageIf(v, testOp==OP_Lt); VdbeCoverageIf(v, testOp==OP_Ge); VdbeCoverageIf(v, testOp==OP_Gt); sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); } }else if( pLoop->wsFlags & WHERE_INDEXED ){ /* Case 4: A scan using an index. ** ** The WHERE clause may contain zero or more equality ** terms ("==" or "IN" operators) that refer to the N ** left-most columns of the index. It may also contain ** inequality constraints (>, <, >= or <=) on the indexed ** column that immediately follows the N equalities. Only ** the right-most column can be an inequality - the rest must ** use the "==" and "IN" operators. For example, if the ** index is on (x,y,z), then the following clauses are all ** optimized: ** ** x=5 ** x=5 AND y=10 ** x=5 AND y<10 ** x=5 AND y>5 AND y<10 ** x=5 AND y=5 AND z<=10 ** ** The z<10 term of the following cannot be used, only ** the x=5 term: ** ** x=5 AND z<10 ** ** N may be zero if there are inequality constraints. ** If there are no inequality constraints, then N is at ** least one. ** ** This case is also used when there are no WHERE clause ** constraints but an index is selected anyway, in order ** to force the output order to conform to an ORDER BY. */ static const u8 aStartOp[] = { 0, 0, OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ OP_Last, /* 3: (!start_constraints && startEq && bRev) */ OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ }; static const u8 aEndOp[] = { OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ }; u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ int regBase; /* Base register holding constraint values */ WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ int startEq; /* True if range start uses ==, >= or <= */ int endEq; /* True if range end uses ==, >= or <= */ int start_constraints; /* Start of range is constrained */ int nConstraint; /* Number of constraint terms */ int iIdxCur; /* The VDBE cursor for the index */ int nExtraReg = 0; /* Number of extra registers needed */ int op; /* Instruction opcode */ char *zStartAff; /* Affinity for start of range constraint */ char *zEndAff = 0; /* Affinity for end of range constraint */ u8 bSeekPastNull = 0; /* True to seek past initial nulls */ u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ int omitTable; /* True if we use the index only */ int regBignull = 0; /* big-null flag register */ pIdx = pLoop->u.btree.pIndex; iIdxCur = pLevel->iIdxCur; assert( nEq>=pLoop->nSkip ); /* Find any inequality constraint terms for the start and end ** of the range. */ j = nEq; if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ pRangeStart = pLoop->aLTerm[j++]; nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); /* Like optimization range constraints always occur in pairs */ assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); } if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ pRangeEnd = pLoop->aLTerm[j++]; nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ assert( pRangeStart!=0 ); /* LIKE opt constraints */ assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ pLevel->iLikeRepCntr = (u32)++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); VdbeComment((v, "LIKE loop counter")); pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); /* iLikeRepCntr actually stores 2x the counter register number. The ** bottom bit indicates whether the search order is ASC or DESC. */ testcase( bRev ); testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); assert( (bRev & ~1)==0 ); pLevel->iLikeRepCntr <<=1; pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); } #endif if( pRangeStart==0 ){ j = pIdx->aiColumn[nEq]; if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ bSeekPastNull = 1; } } } assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS ** FIRST). In both cases separate ordered scans are made of those ** index entries for which the column is null and for those for which ** it is not. For an ASC sort, the non-NULL entries are scanned first. ** For DESC, NULL entries are scanned first. */ if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0 ){ assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 ); assert( pRangeEnd==0 && pRangeStart==0 ); assert( pLoop->nSkip==0 ); nExtraReg = 1; bSeekPastNull = 1; pLevel->regBignull = regBignull = ++pParse->nMem; pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse); } /* If we are doing a reverse order scan on an ascending index, or ** a forward order scan on a descending index, interchange the ** start and end terms (pRangeStart and pRangeEnd). */ if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) || (bRev && pIdx->nKeyCol==nEq) ){ SWAP(WhereTerm *, pRangeEnd, pRangeStart); SWAP(u8, bSeekPastNull, bStopAtNull); SWAP(u8, nBtm, nTop); } /* Generate code to evaluate all constraint terms using == or IN ** and store the values of those terms in an array of registers ** starting at regBase. */ codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); if( zStartAff && nTop ){ zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); } addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt); testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); start_constraints = pRangeStart || nEq>0; /* Seek the index cursor to the start of the range. */ nConstraint = nEq; if( pRangeStart ){ Expr *pRight = pRangeStart->pExpr->pRight; codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); if( (pRangeStart->wtFlags & TERM_VNULL)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zStartAff ){ updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); } nConstraint += nBtm; testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); if( sqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeStart); }else{ startEq = 1; } bSeekPastNull = 0; }else if( bSeekPastNull ){ startEq = 0; sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); start_constraints = 1; nConstraint++; }else if( regBignull ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); start_constraints = 1; nConstraint++; } codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ /* The skip-scan logic inside the call to codeAllEqualityConstraints() ** above has already left the cursor sitting on the correct row, ** so no further seeking is needed */ }else{ if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){ sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur); } if( regBignull ){ sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull); VdbeComment((v, "NULL-scan pass ctr")); } op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; assert( op!=0 ); sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); VdbeCoverage(v); VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); assert( bSeekPastNull==0 || bStopAtNull==0 ); if( regBignull ){ assert( bSeekPastNull==1 || bStopAtNull==1 ); assert( bSeekPastNull==!bStopAtNull ); assert( bStopAtNull==startEq ); sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); op = aStartOp[(nConstraint>1)*4 + 2 + bRev]; sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint-startEq); VdbeCoverage(v); VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE); } } /* Load the value for the inequality constraint at the end of the ** range (if any). */ nConstraint = nEq; if( pRangeEnd ){ Expr *pRight = pRangeEnd->pExpr->pRight; codeExprOrVector(pParse, pRight, regBase+nEq, nTop); whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); if( (pRangeEnd->wtFlags & TERM_VNULL)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zEndAff ){ updateRangeAffinityStr(pRight, nTop, zEndAff); codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); }else{ assert( pParse->db->mallocFailed ); } nConstraint += nTop; testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); if( sqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeEnd); }else{ endEq = 1; } }else if( bStopAtNull ){ if( regBignull==0 ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); endEq = 0; } nConstraint++; } sqlite3DbFree(db, zStartAff); sqlite3DbFree(db, zEndAff); /* Top of the loop body */ pLevel->p2 = sqlite3VdbeCurrentAddr(v); /* Check if the index cursor is past the end of the range. */ if( nConstraint ){ if( regBignull ){ /* Except, skip the end-of-range check while doing the NULL-scan */ sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3); VdbeComment((v, "If NULL-scan 2nd pass")); VdbeCoverage(v); } op = aEndOp[bRev*2 + endEq]; sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); } if( regBignull ){ /* During a NULL-scan, check to see if we have reached the end of ** the NULLs */ assert( bSeekPastNull==!bStopAtNull ); assert( bSeekPastNull+bStopAtNull==1 ); assert( nConstraint+bSeekPastNull>0 ); sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2); VdbeComment((v, "If NULL-scan 1st pass")); VdbeCoverage(v); op = aEndOp[bRev*2 + bSeekPastNull]; sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint+bSeekPastNull); testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); } if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){ sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1); } /* Seek the table cursor, if required */ omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; if( omitTable ){ /* pIdx is a covering index. No need to access the main table. */ }else if( HasRowid(pIdx->pTable) ){ if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || ( (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) && (pWInfo->eOnePass==ONEPASS_SINGLE) )){ iRowidReg = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); VdbeCoverage(v); }else{ codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); } }else if( iCur!=iIdxCur ){ Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; j<pPk->nKeyCol; j++){ k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); } sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, iRowidReg, pPk->nKeyCol); VdbeCoverage(v); } if( pLevel->iLeftJoin==0 ){ /* If pIdx is an index on one or more expressions, then look through ** all the expressions in pWInfo and try to transform matching expressions ** into reference to index columns. Also attempt to translate references ** to virtual columns in the table into references to (stored) columns ** of the index. ** ** Do not do this for the RHS of a LEFT JOIN. This is because the ** expression may be evaluated after OP_NullRow has been executed on ** the cursor. In this case it is important to do the full evaluation, ** as the result of the expression may not be NULL, even if all table ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a ** ** Also, do not do this when processing one index an a multi-index ** OR clause, since the transformation will become invalid once we ** move forward to the next index. ** https://sqlite.org/src/info/4e8e4857d32d401f */ if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); } /* If a partial index is driving the loop, try to eliminate WHERE clause ** terms from the query that must be true due to the WHERE clause of ** the partial index. ** ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work ** for a LEFT JOIN. */ if( pIdx->pPartIdxWhere ){ whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC); } }else{ testcase( pIdx->pPartIdxWhere ); /* The following assert() is not a requirement, merely an observation: ** The OR-optimization doesn't work for the right hand table of ** a LEFT JOIN: */ assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ); } /* Record the instruction used to terminate the loop. */ if( pLoop->wsFlags & WHERE_ONEROW ){ pLevel->op = OP_Noop; }else if( bRev ){ pLevel->op = OP_Prev; }else{ pLevel->op = OP_Next; } pLevel->p1 = iIdxCur; pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; }else{ assert( pLevel->p5==0 ); } if( omitTable ) pIdx = 0; }else #ifndef SQLITE_OMIT_OR_OPTIMIZATION if( pLoop->wsFlags & WHERE_MULTI_OR ){ /* Case 5: Two or more separately indexed terms connected by OR ** ** Example: ** ** CREATE TABLE t1(a,b,c,d); ** CREATE INDEX i1 ON t1(a); ** CREATE INDEX i2 ON t1(b); ** CREATE INDEX i3 ON t1(c); ** ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) ** ** In the example, there are three indexed terms connected by OR. ** The top of the loop looks like this: ** ** Null 1 # Zero the rowset in reg 1 ** ** Then, for each indexed term, the following. The arguments to ** RowSetTest are such that the rowid of the current row is inserted ** into the RowSet. If it is already present, control skips the ** Gosub opcode and jumps straight to the code generated by WhereEnd(). ** ** sqlite3WhereBegin(<term>) ** RowSetTest # Insert rowid into rowset ** Gosub 2 A ** sqlite3WhereEnd() ** ** Following the above, code to terminate the loop. Label A, the target ** of the Gosub above, jumps to the instruction right after the Goto. ** ** Null 1 # Zero the rowset in reg 1 ** Goto B # The loop is finished. ** ** A: <loop body> # Return data, whatever. ** ** Return 2 # Jump back to the Gosub ** ** B: <after the loop> ** ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then ** use an ephemeral index instead of a RowSet to record the primary ** keys of the rows we have already seen. ** */ WhereClause *pOrWc; /* The OR-clause broken out into subterms */ SrcList *pOrTab; /* Shortened table list or OR-clause generation */ Index *pCov = 0; /* Potential covering index (or NULL) */ int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ int regRowset = 0; /* Register for RowSet object */ int regRowid = 0; /* Register holding rowid */ int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */ int iRetInit; /* Address of regReturn init */ int untestedTerms = 0; /* Some terms not completely tested */ int ii; /* Loop counter */ u16 wctrlFlags; /* Flags for sub-WHERE clause */ Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ Table *pTab = pTabItem->pTab; pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->eOperator & WO_OR ); assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); pOrWc = &pTerm->u.pOrInfo->wc; pLevel->op = OP_Return; pLevel->p1 = regReturn; /* Set up a new SrcList in pOrTab containing the table being scanned ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). */ if( pWInfo->nLevel>1 ){ int nNotReady; /* The number of notReady tables */ struct SrcList_item *origSrc; /* Original list of tables */ nNotReady = pWInfo->nLevel - iLevel - 1; pOrTab = sqlite3StackAllocRaw(db, sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); if( pOrTab==0 ) return notReady; pOrTab->nAlloc = (u8)(nNotReady + 1); pOrTab->nSrc = pOrTab->nAlloc; memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); origSrc = pWInfo->pTabList->a; for(k=1; k<=nNotReady; k++){ memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); } }else{ pOrTab = pWInfo->pTabList; } /* Initialize the rowset register to contain NULL. An SQL NULL is ** equivalent to an empty rowset. Or, create an ephemeral index ** capable of holding primary keys in the case of a WITHOUT ROWID. ** ** Also initialize regReturn to contain the address of the instruction ** immediately following the OP_Return at the bottom of the loop. This ** is required in a few obscure LEFT JOIN cases where control jumps ** over the top of the loop into the body of it. In this case the ** correct response for the end-of-loop code (the OP_Return) is to ** fall through to the next instruction, just as an OP_Next does if ** called on an uninitialized cursor. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ if( HasRowid(pTab) ){ regRowset = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); regRowset = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); sqlite3VdbeSetP4KeyInfo(pParse, pPk); } regRowid = ++pParse->nMem; } iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y ** Then for every term xN, evaluate as the subexpression: xN AND z ** That way, terms in y that are factored into the disjunction will ** be picked up by the recursive calls to sqlite3WhereBegin() below. ** ** Actually, each subexpression is converted to "xN AND w" where w is ** the "interesting" terms of z - terms that did not originate in the ** ON or USING clause of a LEFT JOIN, and terms that are usable as ** indices. ** ** This optimization also only applies if the (x1 OR x2 OR ...) term ** is not contained in the ON clause of a LEFT JOIN. ** See ticket http://www.sqlite.org/src/info/f2369304e4 */ if( pWC->nTerm>1 ){ int iTerm; for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ Expr *pExpr = pWC->a[iTerm].pExpr; if( &pWC->a[iTerm] == pTerm ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); pExpr = sqlite3ExprDup(db, pExpr, 0); pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr); } if( pAndExpr ){ /* The extra 0x10000 bit on the opcode is masked off and does not ** become part of the new Expr.op. However, it does make the ** op==TK_AND comparison inside of sqlite3PExpr() false, and this ** prevents sqlite3PExpr() from implementing AND short-circuit ** optimization, which we do not want here. */ pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr); } } /* Run a separate WHERE clause for each term of the OR clause. After ** eliminating duplicates from other WHERE clauses, the action for each ** sub-WHERE clause is to to invoke the main loop body as a subroutine. */ wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR")); for(ii=0; ii<pOrWc->nTerm; ii++){ WhereTerm *pOrTerm = &pOrWc->a[ii]; if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ WhereInfo *pSubWInfo; /* Info for single OR-term scan */ Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ int jmp1 = 0; /* Address of jump operation */ assert( (pTabItem[0].fg.jointype & JT_LEFT)==0 || ExprHasProperty(pOrExpr, EP_FromJoin) ); if( pAndExpr ){ pAndExpr->pLeft = pOrExpr; pOrExpr = pAndExpr; } /* Loop through table entries that match term pOrTerm. */ ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1)); WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, wctrlFlags, iCovCur); assert( pSubWInfo || pParse->nErr || db->mallocFailed ); if( pSubWInfo ){ WhereLoop *pSubLoop; int addrExplain = sqlite3WhereExplainOneScan( pParse, pOrTab, &pSubWInfo->a[0], 0 ); sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); /* This is the sub-WHERE clause body. First skip over ** duplicate rows from prior sub-WHERE clauses, and record the ** rowid (or PRIMARY KEY) for the current row so that the same ** row will be skipped in subsequent sub-WHERE clauses. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); if( HasRowid(pTab) ){ sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid); jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, regRowid, iSet); VdbeCoverage(v); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); int nPk = pPk->nKeyCol; int iPk; int r; /* Read the PK into an array of temp registers. */ r = sqlite3GetTempRange(pParse, nPk); for(iPk=0; iPk<nPk; iPk++){ int iCol = pPk->aiColumn[iPk]; sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk); } /* Check if the temp table already contains this key. If so, ** the row has already been included in the result set and ** can be ignored (by jumping past the Gosub below). Otherwise, ** insert the key into the temp table and proceed with processing ** the row. ** ** Use some of the same optimizations as OP_RowSetTest: If iSet ** is zero, assume that the key cannot already be present in ** the temp table. And if iSet is -1, assume that there is no ** need to insert the key into the temp table, as it will never ** be tested for. */ if( iSet ){ jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); VdbeCoverage(v); } if( iSet>=0 ){ sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, r, nPk); if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } /* Release the array of temp registers */ sqlite3ReleaseTempRange(pParse, r, nPk); } } /* Invoke the main loop body as a subroutine */ sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); /* Jump here (skipping the main loop body subroutine) if the ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); /* The pSubWInfo->untestedTerms flag means that this OR term ** contained one or more AND term from a notReady table. The ** terms from the notReady table could not be tested and will ** need to be tested later. */ if( pSubWInfo->untestedTerms ) untestedTerms = 1; /* If all of the OR-connected terms are optimized using the same ** index, and the index is opened using the same cursor number ** by each call to sqlite3WhereBegin() made by this loop, it may ** be possible to use that index as a covering index. ** ** If the call to sqlite3WhereBegin() above resulted in a scan that ** uses an index, and this is either the first OR-connected term ** processed or the index is the same as that used by all previous ** terms, set pCov to the candidate covering index. Otherwise, set ** pCov to NULL to indicate that no candidate covering index will ** be available. */ pSubLoop = pSubWInfo->a[0].pWLoop; assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) ){ assert( pSubWInfo->a[0].iIdxCur==iCovCur ); pCov = pSubLoop->u.btree.pIndex; }else{ pCov = 0; } /* Finish the loop through table entries that match term pOrTerm. */ sqlite3WhereEnd(pSubWInfo); ExplainQueryPlanPop(pParse); } } } ExplainQueryPlanPop(pParse); pLevel->u.pCovidx = pCov; if( pCov ) pLevel->iIdxCur = iCovCur; if( pAndExpr ){ pAndExpr->pLeft = 0; sqlite3ExprDelete(db, pAndExpr); } sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); sqlite3VdbeGoto(v, pLevel->addrBrk); sqlite3VdbeResolveLabel(v, iLoopBody); if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); } if( !untestedTerms ) disableTerm(pLevel, pTerm); }else #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ { /* Case 6: There is no usable index. We must do a complete ** scan of the entire table. */ static const u8 aStep[] = { OP_Next, OP_Prev }; static const u8 aStart[] = { OP_Rewind, OP_Last }; assert( bRev==0 || bRev==1 ); if( pTabItem->fg.isRecursive ){ /* Tables marked isRecursive have only a single row that is stored in ** a pseudo-cursor. No need to Rewind or Next such cursors. */ pLevel->op = OP_Noop; }else{ codeCursorHint(pTabItem, pWInfo, pLevel, 0); pLevel->op = aStep[bRev]; pLevel->p1 = iCur; pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; } } #ifdef SQLITE_ENABLE_STMT_SCANSTATUS pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); #endif /* Insert code to test every subexpression that can be completely ** computed using the current set of tables. ** ** This loop may run between one and three times, depending on the ** constraints to be generated. The value of stack variable iLoop ** determines the constraints coded by each iteration, as follows: ** ** iLoop==1: Code only expressions that are entirely covered by pIdx. ** iLoop==2: Code remaining expressions that do not contain correlated ** sub-queries. ** iLoop==3: Code all remaining expressions. ** ** An effort is made to skip unnecessary iterations of the loop. */ iLoop = (pIdx ? 1 : 2); do{ int iNext = 0; /* Next value for iLoop */ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ Expr *pE; int skipLikeAddr = 0; testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ testcase( pWInfo->untestedTerms==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); pWInfo->untestedTerms = 1; continue; } pE = pTerm->pExpr; assert( pE!=0 ); if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){ continue; } if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ iNext = 2; continue; } if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){ if( iNext==0 ) iNext = 3; continue; } if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){ /* If the TERM_LIKECOND flag is set, that means that the range search ** is sufficient to guarantee that the LIKE operator is true, so we ** can skip the call to the like(A,B) function. But this only works ** for strings. So do not skip the call to the function on the pass ** that compares BLOBs. */ #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS continue; #else u32 x = pLevel->iLikeRepCntr; if( x>0 ){ skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1)); VdbeCoverageIf(v, (x&1)==1); VdbeCoverageIf(v, (x&1)==0); } #endif } #ifdef WHERETRACE_ENABLED /* 0xffff */ if( sqlite3WhereTrace ){ VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", pWC->nTerm-j, pTerm, iLoop)); } #endif sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); pTerm->wtFlags |= TERM_CODED; } iLoop = iNext; }while( iLoop>0 ); /* Insert code to test for implied constraints based on transitivity ** of the "==" operator. ** ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" ** and we are coding the t1 loop and the t2 loop has not yet coded, ** then we cannot use the "t1.a=t2.b" constraint, but we can code ** the implied "t1.a=123" constraint. */ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ Expr *pE, sEAlt; WhereTerm *pAlt; if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; if( pTerm->leftCursor!=iCur ) continue; if( pLevel->iLeftJoin ) continue; pE = pTerm->pExpr; assert( !ExprHasProperty(pE, EP_FromJoin) ); assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN|WO_IS, 0); if( pAlt==0 ) continue; if( pAlt->wtFlags & (TERM_CODED) ) continue; if( (pAlt->eOperator & WO_IN) && (pAlt->pExpr->flags & EP_xIsSelect) && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) ){ continue; } testcase( pAlt->eOperator & WO_EQ ); testcase( pAlt->eOperator & WO_IS ); testcase( pAlt->eOperator & WO_IN ); VdbeModuleComment((v, "begin transitive constraint")); sEAlt = *pAlt->pExpr; sEAlt.pLeft = pE->pLeft; sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); } /* For a LEFT OUTER JOIN, generate code that will record the fact that ** at least one row of the right table has matched the left table. */ if( pLevel->iLeftJoin ){ pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); VdbeComment((v, "record LEFT JOIN hit")); for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ assert( pWInfo->untestedTerms ); continue; } assert( pTerm->pExpr ); sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); pTerm->wtFlags |= TERM_CODED; } } return pLevel->notReady; }
./CrossVul/dataset_final_sorted/CWE-476/c/good_1275_3
crossvul-cpp_data_bad_1223_3
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2007 Oracle. All rights reserved. */ #include <linux/sched.h> #include <linux/bio.h> #include <linux/slab.h> #include <linux/buffer_head.h> #include <linux/blkdev.h> #include <linux/ratelimit.h> #include <linux/kthread.h> #include <linux/raid/pq.h> #include <linux/semaphore.h> #include <linux/uuid.h> #include <linux/list_sort.h> #include "ctree.h" #include "extent_map.h" #include "disk-io.h" #include "transaction.h" #include "print-tree.h" #include "volumes.h" #include "raid56.h" #include "async-thread.h" #include "check-integrity.h" #include "rcu-string.h" #include "math.h" #include "dev-replace.h" #include "sysfs.h" const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = { [BTRFS_RAID_RAID10] = { .sub_stripes = 2, .dev_stripes = 1, .devs_max = 0, /* 0 == as many as possible */ .devs_min = 4, .tolerated_failures = 1, .devs_increment = 2, .ncopies = 2, .nparity = 0, .raid_name = "raid10", .bg_flag = BTRFS_BLOCK_GROUP_RAID10, .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET, }, [BTRFS_RAID_RAID1] = { .sub_stripes = 1, .dev_stripes = 1, .devs_max = 2, .devs_min = 2, .tolerated_failures = 1, .devs_increment = 2, .ncopies = 2, .nparity = 0, .raid_name = "raid1", .bg_flag = BTRFS_BLOCK_GROUP_RAID1, .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET, }, [BTRFS_RAID_DUP] = { .sub_stripes = 1, .dev_stripes = 2, .devs_max = 1, .devs_min = 1, .tolerated_failures = 0, .devs_increment = 1, .ncopies = 2, .nparity = 0, .raid_name = "dup", .bg_flag = BTRFS_BLOCK_GROUP_DUP, .mindev_error = 0, }, [BTRFS_RAID_RAID0] = { .sub_stripes = 1, .dev_stripes = 1, .devs_max = 0, .devs_min = 2, .tolerated_failures = 0, .devs_increment = 1, .ncopies = 1, .nparity = 0, .raid_name = "raid0", .bg_flag = BTRFS_BLOCK_GROUP_RAID0, .mindev_error = 0, }, [BTRFS_RAID_SINGLE] = { .sub_stripes = 1, .dev_stripes = 1, .devs_max = 1, .devs_min = 1, .tolerated_failures = 0, .devs_increment = 1, .ncopies = 1, .nparity = 0, .raid_name = "single", .bg_flag = 0, .mindev_error = 0, }, [BTRFS_RAID_RAID5] = { .sub_stripes = 1, .dev_stripes = 1, .devs_max = 0, .devs_min = 2, .tolerated_failures = 1, .devs_increment = 1, .ncopies = 1, .nparity = 1, .raid_name = "raid5", .bg_flag = BTRFS_BLOCK_GROUP_RAID5, .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET, }, [BTRFS_RAID_RAID6] = { .sub_stripes = 1, .dev_stripes = 1, .devs_max = 0, .devs_min = 3, .tolerated_failures = 2, .devs_increment = 1, .ncopies = 1, .nparity = 2, .raid_name = "raid6", .bg_flag = BTRFS_BLOCK_GROUP_RAID6, .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET, }, }; const char *get_raid_name(enum btrfs_raid_types type) { if (type >= BTRFS_NR_RAID_TYPES) return NULL; return btrfs_raid_array[type].raid_name; } /* * Fill @buf with textual description of @bg_flags, no more than @size_buf * bytes including terminating null byte. */ void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf) { int i; int ret; char *bp = buf; u64 flags = bg_flags; u32 size_bp = size_buf; if (!flags) { strcpy(bp, "NONE"); return; } #define DESCRIBE_FLAG(flag, desc) \ do { \ if (flags & (flag)) { \ ret = snprintf(bp, size_bp, "%s|", (desc)); \ if (ret < 0 || ret >= size_bp) \ goto out_overflow; \ size_bp -= ret; \ bp += ret; \ flags &= ~(flag); \ } \ } while (0) DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data"); DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system"); DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata"); DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single"); for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag, btrfs_raid_array[i].raid_name); #undef DESCRIBE_FLAG if (flags) { ret = snprintf(bp, size_bp, "0x%llx|", flags); size_bp -= ret; } if (size_bp < size_buf) buf[size_buf - size_bp - 1] = '\0'; /* remove last | */ /* * The text is trimmed, it's up to the caller to provide sufficiently * large buffer */ out_overflow:; } static int init_first_rw_device(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info); static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info); static void __btrfs_reset_dev_stats(struct btrfs_device *dev); static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev); static void btrfs_dev_stat_print_on_load(struct btrfs_device *device); static int __btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op, u64 logical, u64 *length, struct btrfs_bio **bbio_ret, int mirror_num, int need_raid_map); /* * Device locking * ============== * * There are several mutexes that protect manipulation of devices and low-level * structures like chunks but not block groups, extents or files * * uuid_mutex (global lock) * ------------------------ * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from * the SCAN_DEV ioctl registration or from mount either implicitly (the first * device) or requested by the device= mount option * * the mutex can be very coarse and can cover long-running operations * * protects: updates to fs_devices counters like missing devices, rw devices, * seeding, structure cloning, opening/closing devices at mount/umount time * * global::fs_devs - add, remove, updates to the global list * * does not protect: manipulation of the fs_devices::devices list! * * btrfs_device::name - renames (write side), read is RCU * * fs_devices::device_list_mutex (per-fs, with RCU) * ------------------------------------------------ * protects updates to fs_devices::devices, ie. adding and deleting * * simple list traversal with read-only actions can be done with RCU protection * * may be used to exclude some operations from running concurrently without any * modifications to the list (see write_all_supers) * * balance_mutex * ------------- * protects balance structures (status, state) and context accessed from * several places (internally, ioctl) * * chunk_mutex * ----------- * protects chunks, adding or removing during allocation, trim or when a new * device is added/removed * * cleaner_mutex * ------------- * a big lock that is held by the cleaner thread and prevents running subvolume * cleaning together with relocation or delayed iputs * * * Lock nesting * ============ * * uuid_mutex * volume_mutex * device_list_mutex * chunk_mutex * balance_mutex * * * Exclusive operations, BTRFS_FS_EXCL_OP * ====================================== * * Maintains the exclusivity of the following operations that apply to the * whole filesystem and cannot run in parallel. * * - Balance (*) * - Device add * - Device remove * - Device replace (*) * - Resize * * The device operations (as above) can be in one of the following states: * * - Running state * - Paused state * - Completed state * * Only device operations marked with (*) can go into the Paused state for the * following reasons: * * - ioctl (only Balance can be Paused through ioctl) * - filesystem remounted as read-only * - filesystem unmounted and mounted as read-only * - system power-cycle and filesystem mounted as read-only * - filesystem or device errors leading to forced read-only * * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations. * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set. * A device operation in Paused or Running state can be canceled or resumed * either by ioctl (Balance only) or when remounted as read-write. * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or * completed. */ DEFINE_MUTEX(uuid_mutex); static LIST_HEAD(fs_uuids); struct list_head *btrfs_get_fs_uuids(void) { return &fs_uuids; } /* * alloc_fs_devices - allocate struct btrfs_fs_devices * @fsid: if not NULL, copy the UUID to fs_devices::fsid * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid * * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR(). * The returned struct is not linked onto any lists and can be destroyed with * kfree() right away. */ static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid, const u8 *metadata_fsid) { struct btrfs_fs_devices *fs_devs; fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL); if (!fs_devs) return ERR_PTR(-ENOMEM); mutex_init(&fs_devs->device_list_mutex); INIT_LIST_HEAD(&fs_devs->devices); INIT_LIST_HEAD(&fs_devs->resized_devices); INIT_LIST_HEAD(&fs_devs->alloc_list); INIT_LIST_HEAD(&fs_devs->fs_list); if (fsid) memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE); if (metadata_fsid) memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE); else if (fsid) memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE); return fs_devs; } void btrfs_free_device(struct btrfs_device *device) { rcu_string_free(device->name); bio_put(device->flush_bio); kfree(device); } static void free_fs_devices(struct btrfs_fs_devices *fs_devices) { struct btrfs_device *device; WARN_ON(fs_devices->opened); while (!list_empty(&fs_devices->devices)) { device = list_entry(fs_devices->devices.next, struct btrfs_device, dev_list); list_del(&device->dev_list); btrfs_free_device(device); } kfree(fs_devices); } static void btrfs_kobject_uevent(struct block_device *bdev, enum kobject_action action) { int ret; ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action); if (ret) pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n", action, kobject_name(&disk_to_dev(bdev->bd_disk)->kobj), &disk_to_dev(bdev->bd_disk)->kobj); } void __exit btrfs_cleanup_fs_uuids(void) { struct btrfs_fs_devices *fs_devices; while (!list_empty(&fs_uuids)) { fs_devices = list_entry(fs_uuids.next, struct btrfs_fs_devices, fs_list); list_del(&fs_devices->fs_list); free_fs_devices(fs_devices); } } /* * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error. * Returned struct is not linked onto any lists and must be destroyed using * btrfs_free_device. */ static struct btrfs_device *__alloc_device(void) { struct btrfs_device *dev; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return ERR_PTR(-ENOMEM); /* * Preallocate a bio that's always going to be used for flushing device * barriers and matches the device lifespan */ dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL); if (!dev->flush_bio) { kfree(dev); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&dev->dev_list); INIT_LIST_HEAD(&dev->dev_alloc_list); INIT_LIST_HEAD(&dev->resized_list); spin_lock_init(&dev->io_lock); atomic_set(&dev->reada_in_flight, 0); atomic_set(&dev->dev_stats_ccnt, 0); btrfs_device_data_ordered_init(dev); INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM); INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM); return dev; } /* * Find a device specified by @devid or @uuid in the list of @fs_devices, or * return NULL. * * If devid and uuid are both specified, the match must be exact, otherwise * only devid is used. */ static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices, u64 devid, const u8 *uuid) { struct btrfs_device *dev; list_for_each_entry(dev, &fs_devices->devices, dev_list) { if (dev->devid == devid && (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) { return dev; } } return NULL; } static noinline struct btrfs_fs_devices *find_fsid( const u8 *fsid, const u8 *metadata_fsid) { struct btrfs_fs_devices *fs_devices; ASSERT(fsid); if (metadata_fsid) { /* * Handle scanned device having completed its fsid change but * belonging to a fs_devices that was created by first scanning * a device which didn't have its fsid/metadata_uuid changed * at all and the CHANGING_FSID_V2 flag set. */ list_for_each_entry(fs_devices, &fs_uuids, fs_list) { if (fs_devices->fsid_change && memcmp(metadata_fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0 && memcmp(fs_devices->fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0) { return fs_devices; } } /* * Handle scanned device having completed its fsid change but * belonging to a fs_devices that was created by a device that * has an outdated pair of fsid/metadata_uuid and * CHANGING_FSID_V2 flag set. */ list_for_each_entry(fs_devices, &fs_uuids, fs_list) { if (fs_devices->fsid_change && memcmp(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0 && memcmp(metadata_fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0) { return fs_devices; } } } /* Handle non-split brain cases */ list_for_each_entry(fs_devices, &fs_uuids, fs_list) { if (metadata_fsid) { if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0 && memcmp(metadata_fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0) return fs_devices; } else { if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0) return fs_devices; } } return NULL; } static int btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder, int flush, struct block_device **bdev, struct buffer_head **bh) { int ret; *bdev = blkdev_get_by_path(device_path, flags, holder); if (IS_ERR(*bdev)) { ret = PTR_ERR(*bdev); goto error; } if (flush) filemap_write_and_wait((*bdev)->bd_inode->i_mapping); ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE); if (ret) { blkdev_put(*bdev, flags); goto error; } invalidate_bdev(*bdev); *bh = btrfs_read_dev_super(*bdev); if (IS_ERR(*bh)) { ret = PTR_ERR(*bh); blkdev_put(*bdev, flags); goto error; } return 0; error: *bdev = NULL; *bh = NULL; return ret; } static void requeue_list(struct btrfs_pending_bios *pending_bios, struct bio *head, struct bio *tail) { struct bio *old_head; old_head = pending_bios->head; pending_bios->head = head; if (pending_bios->tail) tail->bi_next = old_head; else pending_bios->tail = tail; } /* * we try to collect pending bios for a device so we don't get a large * number of procs sending bios down to the same device. This greatly * improves the schedulers ability to collect and merge the bios. * * But, it also turns into a long list of bios to process and that is sure * to eventually make the worker thread block. The solution here is to * make some progress and then put this work struct back at the end of * the list if the block device is congested. This way, multiple devices * can make progress from a single worker thread. */ static noinline void run_scheduled_bios(struct btrfs_device *device) { struct btrfs_fs_info *fs_info = device->fs_info; struct bio *pending; struct backing_dev_info *bdi; struct btrfs_pending_bios *pending_bios; struct bio *tail; struct bio *cur; int again = 0; unsigned long num_run; unsigned long batch_run = 0; unsigned long last_waited = 0; int force_reg = 0; int sync_pending = 0; struct blk_plug plug; /* * this function runs all the bios we've collected for * a particular device. We don't want to wander off to * another device without first sending all of these down. * So, setup a plug here and finish it off before we return */ blk_start_plug(&plug); bdi = device->bdev->bd_bdi; loop: spin_lock(&device->io_lock); loop_lock: num_run = 0; /* take all the bios off the list at once and process them * later on (without the lock held). But, remember the * tail and other pointers so the bios can be properly reinserted * into the list if we hit congestion */ if (!force_reg && device->pending_sync_bios.head) { pending_bios = &device->pending_sync_bios; force_reg = 1; } else { pending_bios = &device->pending_bios; force_reg = 0; } pending = pending_bios->head; tail = pending_bios->tail; WARN_ON(pending && !tail); /* * if pending was null this time around, no bios need processing * at all and we can stop. Otherwise it'll loop back up again * and do an additional check so no bios are missed. * * device->running_pending is used to synchronize with the * schedule_bio code. */ if (device->pending_sync_bios.head == NULL && device->pending_bios.head == NULL) { again = 0; device->running_pending = 0; } else { again = 1; device->running_pending = 1; } pending_bios->head = NULL; pending_bios->tail = NULL; spin_unlock(&device->io_lock); while (pending) { rmb(); /* we want to work on both lists, but do more bios on the * sync list than the regular list */ if ((num_run > 32 && pending_bios != &device->pending_sync_bios && device->pending_sync_bios.head) || (num_run > 64 && pending_bios == &device->pending_sync_bios && device->pending_bios.head)) { spin_lock(&device->io_lock); requeue_list(pending_bios, pending, tail); goto loop_lock; } cur = pending; pending = pending->bi_next; cur->bi_next = NULL; BUG_ON(atomic_read(&cur->__bi_cnt) == 0); /* * if we're doing the sync list, record that our * plug has some sync requests on it * * If we're doing the regular list and there are * sync requests sitting around, unplug before * we add more */ if (pending_bios == &device->pending_sync_bios) { sync_pending = 1; } else if (sync_pending) { blk_finish_plug(&plug); blk_start_plug(&plug); sync_pending = 0; } btrfsic_submit_bio(cur); num_run++; batch_run++; cond_resched(); /* * we made progress, there is more work to do and the bdi * is now congested. Back off and let other work structs * run instead */ if (pending && bdi_write_congested(bdi) && batch_run > 8 && fs_info->fs_devices->open_devices > 1) { struct io_context *ioc; ioc = current->io_context; /* * the main goal here is that we don't want to * block if we're going to be able to submit * more requests without blocking. * * This code does two great things, it pokes into * the elevator code from a filesystem _and_ * it makes assumptions about how batching works. */ if (ioc && ioc->nr_batch_requests > 0 && time_before(jiffies, ioc->last_waited + HZ/50UL) && (last_waited == 0 || ioc->last_waited == last_waited)) { /* * we want to go through our batch of * requests and stop. So, we copy out * the ioc->last_waited time and test * against it before looping */ last_waited = ioc->last_waited; cond_resched(); continue; } spin_lock(&device->io_lock); requeue_list(pending_bios, pending, tail); device->running_pending = 1; spin_unlock(&device->io_lock); btrfs_queue_work(fs_info->submit_workers, &device->work); goto done; } } cond_resched(); if (again) goto loop; spin_lock(&device->io_lock); if (device->pending_bios.head || device->pending_sync_bios.head) goto loop_lock; spin_unlock(&device->io_lock); done: blk_finish_plug(&plug); } static void pending_bios_fn(struct btrfs_work *work) { struct btrfs_device *device; device = container_of(work, struct btrfs_device, work); run_scheduled_bios(device); } static bool device_path_matched(const char *path, struct btrfs_device *device) { int found; rcu_read_lock(); found = strcmp(rcu_str_deref(device->name), path); rcu_read_unlock(); return found == 0; } /* * Search and remove all stale (devices which are not mounted) devices. * When both inputs are NULL, it will search and release all stale devices. * path: Optional. When provided will it release all unmounted devices * matching this path only. * skip_dev: Optional. Will skip this device when searching for the stale * devices. * Return: 0 for success or if @path is NULL. * -EBUSY if @path is a mounted device. * -ENOENT if @path does not match any device in the list. */ static int btrfs_free_stale_devices(const char *path, struct btrfs_device *skip_device) { struct btrfs_fs_devices *fs_devices, *tmp_fs_devices; struct btrfs_device *device, *tmp_device; int ret = 0; if (path) ret = -ENOENT; list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) { mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry_safe(device, tmp_device, &fs_devices->devices, dev_list) { if (skip_device && skip_device == device) continue; if (path && !device->name) continue; if (path && !device_path_matched(path, device)) continue; if (fs_devices->opened) { /* for an already deleted device return 0 */ if (path && ret != 0) ret = -EBUSY; break; } /* delete the stale device */ fs_devices->num_devices--; list_del(&device->dev_list); btrfs_free_device(device); ret = 0; if (fs_devices->num_devices == 0) break; } mutex_unlock(&fs_devices->device_list_mutex); if (fs_devices->num_devices == 0) { btrfs_sysfs_remove_fsid(fs_devices); list_del(&fs_devices->fs_list); free_fs_devices(fs_devices); } } return ret; } static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices, struct btrfs_device *device, fmode_t flags, void *holder) { struct request_queue *q; struct block_device *bdev; struct buffer_head *bh; struct btrfs_super_block *disk_super; u64 devid; int ret; if (device->bdev) return -EINVAL; if (!device->name) return -EINVAL; ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1, &bdev, &bh); if (ret) return ret; disk_super = (struct btrfs_super_block *)bh->b_data; devid = btrfs_stack_device_id(&disk_super->dev_item); if (devid != device->devid) goto error_brelse; if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE)) goto error_brelse; device->generation = btrfs_super_generation(disk_super); if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) { if (btrfs_super_incompat_flags(disk_super) & BTRFS_FEATURE_INCOMPAT_METADATA_UUID) { pr_err( "BTRFS: Invalid seeding and uuid-changed device detected\n"); goto error_brelse; } clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); fs_devices->seeding = 1; } else { if (bdev_read_only(bdev)) clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); else set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); } q = bdev_get_queue(bdev); if (!blk_queue_nonrot(q)) fs_devices->rotating = 1; device->bdev = bdev; clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); device->mode = flags; fs_devices->open_devices++; if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && device->devid != BTRFS_DEV_REPLACE_DEVID) { fs_devices->rw_devices++; list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list); } brelse(bh); return 0; error_brelse: brelse(bh); blkdev_put(bdev, flags); return -EINVAL; } /* * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices * being created with a disk that has already completed its fsid change. */ static struct btrfs_fs_devices *find_fsid_inprogress( struct btrfs_super_block *disk_super) { struct btrfs_fs_devices *fs_devices; list_for_each_entry(fs_devices, &fs_uuids, fs_list) { if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0 && memcmp(fs_devices->metadata_uuid, disk_super->fsid, BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) { return fs_devices; } } return NULL; } static struct btrfs_fs_devices *find_fsid_changed( struct btrfs_super_block *disk_super) { struct btrfs_fs_devices *fs_devices; /* * Handles the case where scanned device is part of an fs that had * multiple successful changes of FSID but curently device didn't * observe it. Meaning our fsid will be different than theirs. */ list_for_each_entry(fs_devices, &fs_uuids, fs_list) { if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0 && memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid, BTRFS_FSID_SIZE) == 0 && memcmp(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE) != 0) { return fs_devices; } } return NULL; } /* * Add new device to list of registered devices * * Returns: * device pointer which was just added or updated when successful * error pointer when failed */ static noinline struct btrfs_device *device_list_add(const char *path, struct btrfs_super_block *disk_super, bool *new_device_added) { struct btrfs_device *device; struct btrfs_fs_devices *fs_devices = NULL; struct rcu_string *name; u64 found_transid = btrfs_super_generation(disk_super); u64 devid = btrfs_stack_device_id(&disk_super->dev_item); bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) & BTRFS_FEATURE_INCOMPAT_METADATA_UUID); bool fsid_change_in_progress = (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2); if (fsid_change_in_progress) { if (!has_metadata_uuid) { /* * When we have an image which has CHANGING_FSID_V2 set * it might belong to either a filesystem which has * disks with completed fsid change or it might belong * to fs with no UUID changes in effect, handle both. */ fs_devices = find_fsid_inprogress(disk_super); if (!fs_devices) fs_devices = find_fsid(disk_super->fsid, NULL); } else { fs_devices = find_fsid_changed(disk_super); } } else if (has_metadata_uuid) { fs_devices = find_fsid(disk_super->fsid, disk_super->metadata_uuid); } else { fs_devices = find_fsid(disk_super->fsid, NULL); } if (!fs_devices) { if (has_metadata_uuid) fs_devices = alloc_fs_devices(disk_super->fsid, disk_super->metadata_uuid); else fs_devices = alloc_fs_devices(disk_super->fsid, NULL); if (IS_ERR(fs_devices)) return ERR_CAST(fs_devices); fs_devices->fsid_change = fsid_change_in_progress; mutex_lock(&fs_devices->device_list_mutex); list_add(&fs_devices->fs_list, &fs_uuids); device = NULL; } else { mutex_lock(&fs_devices->device_list_mutex); device = find_device(fs_devices, devid, disk_super->dev_item.uuid); /* * If this disk has been pulled into an fs devices created by * a device which had the CHANGING_FSID_V2 flag then replace the * metadata_uuid/fsid values of the fs_devices. */ if (has_metadata_uuid && fs_devices->fsid_change && found_transid > fs_devices->latest_generation) { memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE); memcpy(fs_devices->metadata_uuid, disk_super->metadata_uuid, BTRFS_FSID_SIZE); fs_devices->fsid_change = false; } } if (!device) { if (fs_devices->opened) { mutex_unlock(&fs_devices->device_list_mutex); return ERR_PTR(-EBUSY); } device = btrfs_alloc_device(NULL, &devid, disk_super->dev_item.uuid); if (IS_ERR(device)) { mutex_unlock(&fs_devices->device_list_mutex); /* we can safely leave the fs_devices entry around */ return device; } name = rcu_string_strdup(path, GFP_NOFS); if (!name) { btrfs_free_device(device); mutex_unlock(&fs_devices->device_list_mutex); return ERR_PTR(-ENOMEM); } rcu_assign_pointer(device->name, name); list_add_rcu(&device->dev_list, &fs_devices->devices); fs_devices->num_devices++; device->fs_devices = fs_devices; *new_device_added = true; if (disk_super->label[0]) pr_info("BTRFS: device label %s devid %llu transid %llu %s\n", disk_super->label, devid, found_transid, path); else pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n", disk_super->fsid, devid, found_transid, path); } else if (!device->name || strcmp(device->name->str, path)) { /* * When FS is already mounted. * 1. If you are here and if the device->name is NULL that * means this device was missing at time of FS mount. * 2. If you are here and if the device->name is different * from 'path' that means either * a. The same device disappeared and reappeared with * different name. or * b. The missing-disk-which-was-replaced, has * reappeared now. * * We must allow 1 and 2a above. But 2b would be a spurious * and unintentional. * * Further in case of 1 and 2a above, the disk at 'path' * would have missed some transaction when it was away and * in case of 2a the stale bdev has to be updated as well. * 2b must not be allowed at all time. */ /* * For now, we do allow update to btrfs_fs_device through the * btrfs dev scan cli after FS has been mounted. We're still * tracking a problem where systems fail mount by subvolume id * when we reject replacement on a mounted FS. */ if (!fs_devices->opened && found_transid < device->generation) { /* * That is if the FS is _not_ mounted and if you * are here, that means there is more than one * disk with same uuid and devid.We keep the one * with larger generation number or the last-in if * generation are equal. */ mutex_unlock(&fs_devices->device_list_mutex); return ERR_PTR(-EEXIST); } /* * We are going to replace the device path for a given devid, * make sure it's the same device if the device is mounted */ if (device->bdev) { struct block_device *path_bdev; path_bdev = lookup_bdev(path); if (IS_ERR(path_bdev)) { mutex_unlock(&fs_devices->device_list_mutex); return ERR_CAST(path_bdev); } if (device->bdev != path_bdev) { bdput(path_bdev); mutex_unlock(&fs_devices->device_list_mutex); btrfs_warn_in_rcu(device->fs_info, "duplicate device fsid:devid for %pU:%llu old:%s new:%s", disk_super->fsid, devid, rcu_str_deref(device->name), path); return ERR_PTR(-EEXIST); } bdput(path_bdev); btrfs_info_in_rcu(device->fs_info, "device fsid %pU devid %llu moved old:%s new:%s", disk_super->fsid, devid, rcu_str_deref(device->name), path); } name = rcu_string_strdup(path, GFP_NOFS); if (!name) { mutex_unlock(&fs_devices->device_list_mutex); return ERR_PTR(-ENOMEM); } rcu_string_free(device->name); rcu_assign_pointer(device->name, name); if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) { fs_devices->missing_devices--; clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); } } /* * Unmount does not free the btrfs_device struct but would zero * generation along with most of the other members. So just update * it back. We need it to pick the disk with largest generation * (as above). */ if (!fs_devices->opened) { device->generation = found_transid; fs_devices->latest_generation = max_t(u64, found_transid, fs_devices->latest_generation); } fs_devices->total_devices = btrfs_super_num_devices(disk_super); mutex_unlock(&fs_devices->device_list_mutex); return device; } static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig) { struct btrfs_fs_devices *fs_devices; struct btrfs_device *device; struct btrfs_device *orig_dev; fs_devices = alloc_fs_devices(orig->fsid, NULL); if (IS_ERR(fs_devices)) return fs_devices; mutex_lock(&orig->device_list_mutex); fs_devices->total_devices = orig->total_devices; /* We have held the volume lock, it is safe to get the devices. */ list_for_each_entry(orig_dev, &orig->devices, dev_list) { struct rcu_string *name; device = btrfs_alloc_device(NULL, &orig_dev->devid, orig_dev->uuid); if (IS_ERR(device)) goto error; /* * This is ok to do without rcu read locked because we hold the * uuid mutex so nothing we touch in here is going to disappear. */ if (orig_dev->name) { name = rcu_string_strdup(orig_dev->name->str, GFP_KERNEL); if (!name) { btrfs_free_device(device); goto error; } rcu_assign_pointer(device->name, name); } list_add(&device->dev_list, &fs_devices->devices); device->fs_devices = fs_devices; fs_devices->num_devices++; } mutex_unlock(&orig->device_list_mutex); return fs_devices; error: mutex_unlock(&orig->device_list_mutex); free_fs_devices(fs_devices); return ERR_PTR(-ENOMEM); } /* * After we have read the system tree and know devids belonging to * this filesystem, remove the device which does not belong there. */ void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step) { struct btrfs_device *device, *next; struct btrfs_device *latest_dev = NULL; mutex_lock(&uuid_mutex); again: /* This is the initialized path, it is safe to release the devices. */ list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) { if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) { if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state) && (!latest_dev || device->generation > latest_dev->generation)) { latest_dev = device; } continue; } if (device->devid == BTRFS_DEV_REPLACE_DEVID) { /* * In the first step, keep the device which has * the correct fsid and the devid that is used * for the dev_replace procedure. * In the second step, the dev_replace state is * read from the device tree and it is known * whether the procedure is really active or * not, which means whether this device is * used or whether it should be removed. */ if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { continue; } } if (device->bdev) { blkdev_put(device->bdev, device->mode); device->bdev = NULL; fs_devices->open_devices--; } if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { list_del_init(&device->dev_alloc_list); clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) fs_devices->rw_devices--; } list_del_init(&device->dev_list); fs_devices->num_devices--; btrfs_free_device(device); } if (fs_devices->seed) { fs_devices = fs_devices->seed; goto again; } fs_devices->latest_bdev = latest_dev->bdev; mutex_unlock(&uuid_mutex); } static void free_device_rcu(struct rcu_head *head) { struct btrfs_device *device; device = container_of(head, struct btrfs_device, rcu); btrfs_free_device(device); } static void btrfs_close_bdev(struct btrfs_device *device) { if (!device->bdev) return; if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { sync_blockdev(device->bdev); invalidate_bdev(device->bdev); } blkdev_put(device->bdev, device->mode); } static void btrfs_close_one_device(struct btrfs_device *device) { struct btrfs_fs_devices *fs_devices = device->fs_devices; struct btrfs_device *new_device; struct rcu_string *name; if (device->bdev) fs_devices->open_devices--; if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && device->devid != BTRFS_DEV_REPLACE_DEVID) { list_del_init(&device->dev_alloc_list); fs_devices->rw_devices--; } if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) fs_devices->missing_devices--; btrfs_close_bdev(device); new_device = btrfs_alloc_device(NULL, &device->devid, device->uuid); BUG_ON(IS_ERR(new_device)); /* -ENOMEM */ /* Safe because we are under uuid_mutex */ if (device->name) { name = rcu_string_strdup(device->name->str, GFP_NOFS); BUG_ON(!name); /* -ENOMEM */ rcu_assign_pointer(new_device->name, name); } list_replace_rcu(&device->dev_list, &new_device->dev_list); new_device->fs_devices = device->fs_devices; call_rcu(&device->rcu, free_device_rcu); } static int close_fs_devices(struct btrfs_fs_devices *fs_devices) { struct btrfs_device *device, *tmp; if (--fs_devices->opened > 0) return 0; mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) { btrfs_close_one_device(device); } mutex_unlock(&fs_devices->device_list_mutex); WARN_ON(fs_devices->open_devices); WARN_ON(fs_devices->rw_devices); fs_devices->opened = 0; fs_devices->seeding = 0; return 0; } int btrfs_close_devices(struct btrfs_fs_devices *fs_devices) { struct btrfs_fs_devices *seed_devices = NULL; int ret; mutex_lock(&uuid_mutex); ret = close_fs_devices(fs_devices); if (!fs_devices->opened) { seed_devices = fs_devices->seed; fs_devices->seed = NULL; } mutex_unlock(&uuid_mutex); while (seed_devices) { fs_devices = seed_devices; seed_devices = fs_devices->seed; close_fs_devices(fs_devices); free_fs_devices(fs_devices); } return ret; } static int open_fs_devices(struct btrfs_fs_devices *fs_devices, fmode_t flags, void *holder) { struct btrfs_device *device; struct btrfs_device *latest_dev = NULL; int ret = 0; flags |= FMODE_EXCL; list_for_each_entry(device, &fs_devices->devices, dev_list) { /* Just open everything we can; ignore failures here */ if (btrfs_open_one_device(fs_devices, device, flags, holder)) continue; if (!latest_dev || device->generation > latest_dev->generation) latest_dev = device; } if (fs_devices->open_devices == 0) { ret = -EINVAL; goto out; } fs_devices->opened = 1; fs_devices->latest_bdev = latest_dev->bdev; fs_devices->total_rw_bytes = 0; out: return ret; } static int devid_cmp(void *priv, struct list_head *a, struct list_head *b) { struct btrfs_device *dev1, *dev2; dev1 = list_entry(a, struct btrfs_device, dev_list); dev2 = list_entry(b, struct btrfs_device, dev_list); if (dev1->devid < dev2->devid) return -1; else if (dev1->devid > dev2->devid) return 1; return 0; } int btrfs_open_devices(struct btrfs_fs_devices *fs_devices, fmode_t flags, void *holder) { int ret; lockdep_assert_held(&uuid_mutex); mutex_lock(&fs_devices->device_list_mutex); if (fs_devices->opened) { fs_devices->opened++; ret = 0; } else { list_sort(NULL, &fs_devices->devices, devid_cmp); ret = open_fs_devices(fs_devices, flags, holder); } mutex_unlock(&fs_devices->device_list_mutex); return ret; } static void btrfs_release_disk_super(struct page *page) { kunmap(page); put_page(page); } static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr, struct page **page, struct btrfs_super_block **disk_super) { void *p; pgoff_t index; /* make sure our super fits in the device */ if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode)) return 1; /* make sure our super fits in the page */ if (sizeof(**disk_super) > PAGE_SIZE) return 1; /* make sure our super doesn't straddle pages on disk */ index = bytenr >> PAGE_SHIFT; if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index) return 1; /* pull in the page with our super */ *page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL); if (IS_ERR_OR_NULL(*page)) return 1; p = kmap(*page); /* align our pointer to the offset of the super block */ *disk_super = p + offset_in_page(bytenr); if (btrfs_super_bytenr(*disk_super) != bytenr || btrfs_super_magic(*disk_super) != BTRFS_MAGIC) { btrfs_release_disk_super(*page); return 1; } if ((*disk_super)->label[0] && (*disk_super)->label[BTRFS_LABEL_SIZE - 1]) (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0'; return 0; } /* * Look for a btrfs signature on a device. This may be called out of the mount path * and we are not allowed to call set_blocksize during the scan. The superblock * is read via pagecache */ struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags, void *holder) { struct btrfs_super_block *disk_super; bool new_device_added = false; struct btrfs_device *device = NULL; struct block_device *bdev; struct page *page; u64 bytenr; lockdep_assert_held(&uuid_mutex); /* * we would like to check all the supers, but that would make * a btrfs mount succeed after a mkfs from a different FS. * So, we need to add a special mount option to scan for * later supers, using BTRFS_SUPER_MIRROR_MAX instead */ bytenr = btrfs_sb_offset(0); flags |= FMODE_EXCL; bdev = blkdev_get_by_path(path, flags, holder); if (IS_ERR(bdev)) return ERR_CAST(bdev); if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) { device = ERR_PTR(-EINVAL); goto error_bdev_put; } device = device_list_add(path, disk_super, &new_device_added); if (!IS_ERR(device)) { if (new_device_added) btrfs_free_stale_devices(path, device); } btrfs_release_disk_super(page); error_bdev_put: blkdev_put(bdev, flags); return device; } static int contains_pending_extent(struct btrfs_transaction *transaction, struct btrfs_device *device, u64 *start, u64 len) { struct btrfs_fs_info *fs_info = device->fs_info; struct extent_map *em; struct list_head *search_list = &fs_info->pinned_chunks; int ret = 0; u64 physical_start = *start; if (transaction) search_list = &transaction->pending_chunks; again: list_for_each_entry(em, search_list, list) { struct map_lookup *map; int i; map = em->map_lookup; for (i = 0; i < map->num_stripes; i++) { u64 end; if (map->stripes[i].dev != device) continue; if (map->stripes[i].physical >= physical_start + len || map->stripes[i].physical + em->orig_block_len <= physical_start) continue; /* * Make sure that while processing the pinned list we do * not override our *start with a lower value, because * we can have pinned chunks that fall within this * device hole and that have lower physical addresses * than the pending chunks we processed before. If we * do not take this special care we can end up getting * 2 pending chunks that start at the same physical * device offsets because the end offset of a pinned * chunk can be equal to the start offset of some * pending chunk. */ end = map->stripes[i].physical + em->orig_block_len; if (end > *start) { *start = end; ret = 1; } } } if (search_list != &fs_info->pinned_chunks) { search_list = &fs_info->pinned_chunks; goto again; } return ret; } /* * find_free_dev_extent_start - find free space in the specified device * @device: the device which we search the free space in * @num_bytes: the size of the free space that we need * @search_start: the position from which to begin the search * @start: store the start of the free space. * @len: the size of the free space. that we find, or the size * of the max free space if we don't find suitable free space * * this uses a pretty simple search, the expectation is that it is * called very infrequently and that a given device has a small number * of extents * * @start is used to store the start of the free space if we find. But if we * don't find suitable free space, it will be used to store the start position * of the max free space. * * @len is used to store the size of the free space that we find. * But if we don't find suitable free space, it is used to store the size of * the max free space. */ int find_free_dev_extent_start(struct btrfs_transaction *transaction, struct btrfs_device *device, u64 num_bytes, u64 search_start, u64 *start, u64 *len) { struct btrfs_fs_info *fs_info = device->fs_info; struct btrfs_root *root = fs_info->dev_root; struct btrfs_key key; struct btrfs_dev_extent *dev_extent; struct btrfs_path *path; u64 hole_size; u64 max_hole_start; u64 max_hole_size; u64 extent_end; u64 search_end = device->total_bytes; int ret; int slot; struct extent_buffer *l; /* * We don't want to overwrite the superblock on the drive nor any area * used by the boot loader (grub for example), so we make sure to start * at an offset of at least 1MB. */ search_start = max_t(u64, search_start, SZ_1M); path = btrfs_alloc_path(); if (!path) return -ENOMEM; max_hole_start = search_start; max_hole_size = 0; again: if (search_start >= search_end || test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { ret = -ENOSPC; goto out; } path->reada = READA_FORWARD; path->search_commit_root = 1; path->skip_locking = 1; key.objectid = device->devid; key.offset = search_start; key.type = BTRFS_DEV_EXTENT_KEY; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; if (ret > 0) { ret = btrfs_previous_item(root, path, key.objectid, key.type); if (ret < 0) goto out; } while (1) { l = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(l)) { ret = btrfs_next_leaf(root, path); if (ret == 0) continue; if (ret < 0) goto out; break; } btrfs_item_key_to_cpu(l, &key, slot); if (key.objectid < device->devid) goto next; if (key.objectid > device->devid) break; if (key.type != BTRFS_DEV_EXTENT_KEY) goto next; if (key.offset > search_start) { hole_size = key.offset - search_start; /* * Have to check before we set max_hole_start, otherwise * we could end up sending back this offset anyway. */ if (contains_pending_extent(transaction, device, &search_start, hole_size)) { if (key.offset >= search_start) { hole_size = key.offset - search_start; } else { WARN_ON_ONCE(1); hole_size = 0; } } if (hole_size > max_hole_size) { max_hole_start = search_start; max_hole_size = hole_size; } /* * If this free space is greater than which we need, * it must be the max free space that we have found * until now, so max_hole_start must point to the start * of this free space and the length of this free space * is stored in max_hole_size. Thus, we return * max_hole_start and max_hole_size and go back to the * caller. */ if (hole_size >= num_bytes) { ret = 0; goto out; } } dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent); extent_end = key.offset + btrfs_dev_extent_length(l, dev_extent); if (extent_end > search_start) search_start = extent_end; next: path->slots[0]++; cond_resched(); } /* * At this point, search_start should be the end of * allocated dev extents, and when shrinking the device, * search_end may be smaller than search_start. */ if (search_end > search_start) { hole_size = search_end - search_start; if (contains_pending_extent(transaction, device, &search_start, hole_size)) { btrfs_release_path(path); goto again; } if (hole_size > max_hole_size) { max_hole_start = search_start; max_hole_size = hole_size; } } /* See above. */ if (max_hole_size < num_bytes) ret = -ENOSPC; else ret = 0; out: btrfs_free_path(path); *start = max_hole_start; if (len) *len = max_hole_size; return ret; } int find_free_dev_extent(struct btrfs_trans_handle *trans, struct btrfs_device *device, u64 num_bytes, u64 *start, u64 *len) { /* FIXME use last free of some kind */ return find_free_dev_extent_start(trans->transaction, device, num_bytes, 0, start, len); } static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans, struct btrfs_device *device, u64 start, u64 *dev_extent_len) { struct btrfs_fs_info *fs_info = device->fs_info; struct btrfs_root *root = fs_info->dev_root; int ret; struct btrfs_path *path; struct btrfs_key key; struct btrfs_key found_key; struct extent_buffer *leaf = NULL; struct btrfs_dev_extent *extent = NULL; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = device->devid; key.offset = start; key.type = BTRFS_DEV_EXTENT_KEY; again: ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret > 0) { ret = btrfs_previous_item(root, path, key.objectid, BTRFS_DEV_EXTENT_KEY); if (ret) goto out; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent); BUG_ON(found_key.offset > start || found_key.offset + btrfs_dev_extent_length(leaf, extent) < start); key = found_key; btrfs_release_path(path); goto again; } else if (ret == 0) { leaf = path->nodes[0]; extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent); } else { btrfs_handle_fs_error(fs_info, ret, "Slot search failed"); goto out; } *dev_extent_len = btrfs_dev_extent_length(leaf, extent); ret = btrfs_del_item(trans, root, path); if (ret) { btrfs_handle_fs_error(fs_info, ret, "Failed to remove dev extent item"); } else { set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags); } out: btrfs_free_path(path); return ret; } static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans, struct btrfs_device *device, u64 chunk_offset, u64 start, u64 num_bytes) { int ret; struct btrfs_path *path; struct btrfs_fs_info *fs_info = device->fs_info; struct btrfs_root *root = fs_info->dev_root; struct btrfs_dev_extent *extent; struct extent_buffer *leaf; struct btrfs_key key; WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)); WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)); path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = device->devid; key.offset = start; key.type = BTRFS_DEV_EXTENT_KEY; ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent)); if (ret) goto out; leaf = path->nodes[0]; extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent); btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID); btrfs_set_dev_extent_chunk_objectid(leaf, extent, BTRFS_FIRST_CHUNK_TREE_OBJECTID); btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset); btrfs_set_dev_extent_length(leaf, extent, num_bytes); btrfs_mark_buffer_dirty(leaf); out: btrfs_free_path(path); return ret; } static u64 find_next_chunk(struct btrfs_fs_info *fs_info) { struct extent_map_tree *em_tree; struct extent_map *em; struct rb_node *n; u64 ret = 0; em_tree = &fs_info->mapping_tree.map_tree; read_lock(&em_tree->lock); n = rb_last(&em_tree->map.rb_root); if (n) { em = rb_entry(n, struct extent_map, rb_node); ret = em->start + em->len; } read_unlock(&em_tree->lock); return ret; } static noinline int find_next_devid(struct btrfs_fs_info *fs_info, u64 *devid_ret) { int ret; struct btrfs_key key; struct btrfs_key found_key; struct btrfs_path *path; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = BTRFS_DEV_ITEMS_OBJECTID; key.type = BTRFS_DEV_ITEM_KEY; key.offset = (u64)-1; ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0); if (ret < 0) goto error; BUG_ON(ret == 0); /* Corruption */ ret = btrfs_previous_item(fs_info->chunk_root, path, BTRFS_DEV_ITEMS_OBJECTID, BTRFS_DEV_ITEM_KEY); if (ret) { *devid_ret = 1; } else { btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]); *devid_ret = found_key.offset + 1; } ret = 0; error: btrfs_free_path(path); return ret; } /* * the device information is stored in the chunk root * the btrfs_device struct should be fully filled in */ static int btrfs_add_dev_item(struct btrfs_trans_handle *trans, struct btrfs_device *device) { int ret; struct btrfs_path *path; struct btrfs_dev_item *dev_item; struct extent_buffer *leaf; struct btrfs_key key; unsigned long ptr; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = BTRFS_DEV_ITEMS_OBJECTID; key.type = BTRFS_DEV_ITEM_KEY; key.offset = device->devid; ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path, &key, sizeof(*dev_item)); if (ret) goto out; leaf = path->nodes[0]; dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item); btrfs_set_device_id(leaf, dev_item, device->devid); btrfs_set_device_generation(leaf, dev_item, 0); btrfs_set_device_type(leaf, dev_item, device->type); btrfs_set_device_io_align(leaf, dev_item, device->io_align); btrfs_set_device_io_width(leaf, dev_item, device->io_width); btrfs_set_device_sector_size(leaf, dev_item, device->sector_size); btrfs_set_device_total_bytes(leaf, dev_item, btrfs_device_get_disk_total_bytes(device)); btrfs_set_device_bytes_used(leaf, dev_item, btrfs_device_get_bytes_used(device)); btrfs_set_device_group(leaf, dev_item, 0); btrfs_set_device_seek_speed(leaf, dev_item, 0); btrfs_set_device_bandwidth(leaf, dev_item, 0); btrfs_set_device_start_offset(leaf, dev_item, 0); ptr = btrfs_device_uuid(dev_item); write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE); ptr = btrfs_device_fsid(dev_item); write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid, ptr, BTRFS_FSID_SIZE); btrfs_mark_buffer_dirty(leaf); ret = 0; out: btrfs_free_path(path); return ret; } /* * Function to update ctime/mtime for a given device path. * Mainly used for ctime/mtime based probe like libblkid. */ static void update_dev_time(const char *path_name) { struct file *filp; filp = filp_open(path_name, O_RDWR, 0); if (IS_ERR(filp)) return; file_update_time(filp); filp_close(filp, NULL); } static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info, struct btrfs_device *device) { struct btrfs_root *root = fs_info->chunk_root; int ret; struct btrfs_path *path; struct btrfs_key key; struct btrfs_trans_handle *trans; path = btrfs_alloc_path(); if (!path) return -ENOMEM; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { btrfs_free_path(path); return PTR_ERR(trans); } key.objectid = BTRFS_DEV_ITEMS_OBJECTID; key.type = BTRFS_DEV_ITEM_KEY; key.offset = device->devid; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret) { if (ret > 0) ret = -ENOENT; btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); goto out; } ret = btrfs_del_item(trans, root, path); if (ret) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); } out: btrfs_free_path(path); if (!ret) ret = btrfs_commit_transaction(trans); return ret; } /* * Verify that @num_devices satisfies the RAID profile constraints in the whole * filesystem. It's up to the caller to adjust that number regarding eg. device * replace. */ static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info, u64 num_devices) { u64 all_avail; unsigned seq; int i; do { seq = read_seqbegin(&fs_info->profiles_lock); all_avail = fs_info->avail_data_alloc_bits | fs_info->avail_system_alloc_bits | fs_info->avail_metadata_alloc_bits; } while (read_seqretry(&fs_info->profiles_lock, seq)); for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) { if (!(all_avail & btrfs_raid_array[i].bg_flag)) continue; if (num_devices < btrfs_raid_array[i].devs_min) { int ret = btrfs_raid_array[i].mindev_error; if (ret) return ret; } } return 0; } static struct btrfs_device * btrfs_find_next_active_device( struct btrfs_fs_devices *fs_devs, struct btrfs_device *device) { struct btrfs_device *next_device; list_for_each_entry(next_device, &fs_devs->devices, dev_list) { if (next_device != device && !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state) && next_device->bdev) return next_device; } return NULL; } /* * Helper function to check if the given device is part of s_bdev / latest_bdev * and replace it with the provided or the next active device, in the context * where this function called, there should be always be another device (or * this_dev) which is active. */ void btrfs_assign_next_active_device(struct btrfs_device *device, struct btrfs_device *this_dev) { struct btrfs_fs_info *fs_info = device->fs_info; struct btrfs_device *next_device; if (this_dev) next_device = this_dev; else next_device = btrfs_find_next_active_device(fs_info->fs_devices, device); ASSERT(next_device); if (fs_info->sb->s_bdev && (fs_info->sb->s_bdev == device->bdev)) fs_info->sb->s_bdev = next_device->bdev; if (fs_info->fs_devices->latest_bdev == device->bdev) fs_info->fs_devices->latest_bdev = next_device->bdev; } /* * Return btrfs_fs_devices::num_devices excluding the device that's being * currently replaced. */ static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info) { u64 num_devices = fs_info->fs_devices->num_devices; down_read(&fs_info->dev_replace.rwsem); if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) { ASSERT(num_devices > 1); num_devices--; } up_read(&fs_info->dev_replace.rwsem); return num_devices; } int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path, u64 devid) { struct btrfs_device *device; struct btrfs_fs_devices *cur_devices; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; u64 num_devices; int ret = 0; mutex_lock(&uuid_mutex); num_devices = btrfs_num_devices(fs_info); ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1); if (ret) goto out; device = btrfs_find_device_by_devspec(fs_info, devid, device_path); if (IS_ERR(device)) { if (PTR_ERR(device) == -ENOENT && strcmp(device_path, "missing") == 0) ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND; else ret = PTR_ERR(device); goto out; } if (btrfs_pinned_by_swapfile(fs_info, device)) { btrfs_warn_in_rcu(fs_info, "cannot remove device %s (devid %llu) due to active swapfile", rcu_str_deref(device->name), device->devid); ret = -ETXTBSY; goto out; } if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { ret = BTRFS_ERROR_DEV_TGT_REPLACE; goto out; } if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && fs_info->fs_devices->rw_devices == 1) { ret = BTRFS_ERROR_DEV_ONLY_WRITABLE; goto out; } if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { mutex_lock(&fs_info->chunk_mutex); list_del_init(&device->dev_alloc_list); device->fs_devices->rw_devices--; mutex_unlock(&fs_info->chunk_mutex); } mutex_unlock(&uuid_mutex); ret = btrfs_shrink_device(device, 0); mutex_lock(&uuid_mutex); if (ret) goto error_undo; /* * TODO: the superblock still includes this device in its num_devices * counter although write_all_supers() is not locked out. This * could give a filesystem state which requires a degraded mount. */ ret = btrfs_rm_dev_item(fs_info, device); if (ret) goto error_undo; clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); btrfs_scrub_cancel_dev(fs_info, device); /* * the device list mutex makes sure that we don't change * the device list while someone else is writing out all * the device supers. Whoever is writing all supers, should * lock the device list mutex before getting the number of * devices in the super block (super_copy). Conversely, * whoever updates the number of devices in the super block * (super_copy) should hold the device list mutex. */ /* * In normal cases the cur_devices == fs_devices. But in case * of deleting a seed device, the cur_devices should point to * its own fs_devices listed under the fs_devices->seed. */ cur_devices = device->fs_devices; mutex_lock(&fs_devices->device_list_mutex); list_del_rcu(&device->dev_list); cur_devices->num_devices--; cur_devices->total_devices--; /* Update total_devices of the parent fs_devices if it's seed */ if (cur_devices != fs_devices) fs_devices->total_devices--; if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) cur_devices->missing_devices--; btrfs_assign_next_active_device(device, NULL); if (device->bdev) { cur_devices->open_devices--; /* remove sysfs entry */ btrfs_sysfs_rm_device_link(fs_devices, device); } num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1; btrfs_set_super_num_devices(fs_info->super_copy, num_devices); mutex_unlock(&fs_devices->device_list_mutex); /* * at this point, the device is zero sized and detached from * the devices list. All that's left is to zero out the old * supers and free the device. */ if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) btrfs_scratch_superblocks(device->bdev, device->name->str); btrfs_close_bdev(device); call_rcu(&device->rcu, free_device_rcu); if (cur_devices->open_devices == 0) { while (fs_devices) { if (fs_devices->seed == cur_devices) { fs_devices->seed = cur_devices->seed; break; } fs_devices = fs_devices->seed; } cur_devices->seed = NULL; close_fs_devices(cur_devices); free_fs_devices(cur_devices); } out: mutex_unlock(&uuid_mutex); return ret; error_undo: if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { mutex_lock(&fs_info->chunk_mutex); list_add(&device->dev_alloc_list, &fs_devices->alloc_list); device->fs_devices->rw_devices++; mutex_unlock(&fs_info->chunk_mutex); } goto out; } void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev) { struct btrfs_fs_devices *fs_devices; lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex); /* * in case of fs with no seed, srcdev->fs_devices will point * to fs_devices of fs_info. However when the dev being replaced is * a seed dev it will point to the seed's local fs_devices. In short * srcdev will have its correct fs_devices in both the cases. */ fs_devices = srcdev->fs_devices; list_del_rcu(&srcdev->dev_list); list_del(&srcdev->dev_alloc_list); fs_devices->num_devices--; if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state)) fs_devices->missing_devices--; if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) fs_devices->rw_devices--; if (srcdev->bdev) fs_devices->open_devices--; } void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info, struct btrfs_device *srcdev) { struct btrfs_fs_devices *fs_devices = srcdev->fs_devices; if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) { /* zero out the old super if it is writable */ btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str); } btrfs_close_bdev(srcdev); call_rcu(&srcdev->rcu, free_device_rcu); /* if this is no devs we rather delete the fs_devices */ if (!fs_devices->num_devices) { struct btrfs_fs_devices *tmp_fs_devices; /* * On a mounted FS, num_devices can't be zero unless it's a * seed. In case of a seed device being replaced, the replace * target added to the sprout FS, so there will be no more * device left under the seed FS. */ ASSERT(fs_devices->seeding); tmp_fs_devices = fs_info->fs_devices; while (tmp_fs_devices) { if (tmp_fs_devices->seed == fs_devices) { tmp_fs_devices->seed = fs_devices->seed; break; } tmp_fs_devices = tmp_fs_devices->seed; } fs_devices->seed = NULL; close_fs_devices(fs_devices); free_fs_devices(fs_devices); } } void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev) { struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices; WARN_ON(!tgtdev); mutex_lock(&fs_devices->device_list_mutex); btrfs_sysfs_rm_device_link(fs_devices, tgtdev); if (tgtdev->bdev) fs_devices->open_devices--; fs_devices->num_devices--; btrfs_assign_next_active_device(tgtdev, NULL); list_del_rcu(&tgtdev->dev_list); mutex_unlock(&fs_devices->device_list_mutex); /* * The update_dev_time() with in btrfs_scratch_superblocks() * may lead to a call to btrfs_show_devname() which will try * to hold device_list_mutex. And here this device * is already out of device list, so we don't have to hold * the device_list_mutex lock. */ btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str); btrfs_close_bdev(tgtdev); call_rcu(&tgtdev->rcu, free_device_rcu); } static struct btrfs_device *btrfs_find_device_by_path( struct btrfs_fs_info *fs_info, const char *device_path) { int ret = 0; struct btrfs_super_block *disk_super; u64 devid; u8 *dev_uuid; struct block_device *bdev; struct buffer_head *bh; struct btrfs_device *device; ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ, fs_info->bdev_holder, 0, &bdev, &bh); if (ret) return ERR_PTR(ret); disk_super = (struct btrfs_super_block *)bh->b_data; devid = btrfs_stack_device_id(&disk_super->dev_item); dev_uuid = disk_super->dev_item.uuid; if (btrfs_fs_incompat(fs_info, METADATA_UUID)) device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid, disk_super->metadata_uuid); else device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid, disk_super->fsid); brelse(bh); if (!device) device = ERR_PTR(-ENOENT); blkdev_put(bdev, FMODE_READ); return device; } /* * Lookup a device given by device id, or the path if the id is 0. */ struct btrfs_device *btrfs_find_device_by_devspec( struct btrfs_fs_info *fs_info, u64 devid, const char *device_path) { struct btrfs_device *device; if (devid) { device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (!device) return ERR_PTR(-ENOENT); return device; } if (!device_path || !device_path[0]) return ERR_PTR(-EINVAL); if (strcmp(device_path, "missing") == 0) { /* Find first missing device */ list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) { if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) && !device->bdev) return device; } return ERR_PTR(-ENOENT); } return btrfs_find_device_by_path(fs_info, device_path); } /* * does all the dirty work required for changing file system's UUID. */ static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct btrfs_fs_devices *old_devices; struct btrfs_fs_devices *seed_devices; struct btrfs_super_block *disk_super = fs_info->super_copy; struct btrfs_device *device; u64 super_flags; lockdep_assert_held(&uuid_mutex); if (!fs_devices->seeding) return -EINVAL; seed_devices = alloc_fs_devices(NULL, NULL); if (IS_ERR(seed_devices)) return PTR_ERR(seed_devices); old_devices = clone_fs_devices(fs_devices); if (IS_ERR(old_devices)) { kfree(seed_devices); return PTR_ERR(old_devices); } list_add(&old_devices->fs_list, &fs_uuids); memcpy(seed_devices, fs_devices, sizeof(*seed_devices)); seed_devices->opened = 1; INIT_LIST_HEAD(&seed_devices->devices); INIT_LIST_HEAD(&seed_devices->alloc_list); mutex_init(&seed_devices->device_list_mutex); mutex_lock(&fs_devices->device_list_mutex); list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices, synchronize_rcu); list_for_each_entry(device, &seed_devices->devices, dev_list) device->fs_devices = seed_devices; mutex_lock(&fs_info->chunk_mutex); list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list); mutex_unlock(&fs_info->chunk_mutex); fs_devices->seeding = 0; fs_devices->num_devices = 0; fs_devices->open_devices = 0; fs_devices->missing_devices = 0; fs_devices->rotating = 0; fs_devices->seed = seed_devices; generate_random_uuid(fs_devices->fsid); memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE); memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE); mutex_unlock(&fs_devices->device_list_mutex); super_flags = btrfs_super_flags(disk_super) & ~BTRFS_SUPER_FLAG_SEEDING; btrfs_set_super_flags(disk_super, super_flags); return 0; } /* * Store the expected generation for seed devices in device items. */ static int btrfs_finish_sprout(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info) { struct btrfs_root *root = fs_info->chunk_root; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_dev_item *dev_item; struct btrfs_device *device; struct btrfs_key key; u8 fs_uuid[BTRFS_FSID_SIZE]; u8 dev_uuid[BTRFS_UUID_SIZE]; u64 devid; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = BTRFS_DEV_ITEMS_OBJECTID; key.offset = 0; key.type = BTRFS_DEV_ITEM_KEY; while (1) { ret = btrfs_search_slot(trans, root, &key, path, 0, 1); if (ret < 0) goto error; leaf = path->nodes[0]; next_slot: if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret > 0) break; if (ret < 0) goto error; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); btrfs_release_path(path); continue; } btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID || key.type != BTRFS_DEV_ITEM_KEY) break; dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item); devid = btrfs_device_id(leaf, dev_item); read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item), BTRFS_UUID_SIZE); read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item), BTRFS_FSID_SIZE); device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid, fs_uuid); BUG_ON(!device); /* Logic error */ if (device->fs_devices->seeding) { btrfs_set_device_generation(leaf, dev_item, device->generation); btrfs_mark_buffer_dirty(leaf); } path->slots[0]++; goto next_slot; } ret = 0; error: btrfs_free_path(path); return ret; } int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path) { struct btrfs_root *root = fs_info->dev_root; struct request_queue *q; struct btrfs_trans_handle *trans; struct btrfs_device *device; struct block_device *bdev; struct super_block *sb = fs_info->sb; struct rcu_string *name; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; u64 orig_super_total_bytes; u64 orig_super_num_devices; int seeding_dev = 0; int ret = 0; bool unlocked = false; if (sb_rdonly(sb) && !fs_devices->seeding) return -EROFS; bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL, fs_info->bdev_holder); if (IS_ERR(bdev)) return PTR_ERR(bdev); if (fs_devices->seeding) { seeding_dev = 1; down_write(&sb->s_umount); mutex_lock(&uuid_mutex); } filemap_write_and_wait(bdev->bd_inode->i_mapping); mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry(device, &fs_devices->devices, dev_list) { if (device->bdev == bdev) { ret = -EEXIST; mutex_unlock( &fs_devices->device_list_mutex); goto error; } } mutex_unlock(&fs_devices->device_list_mutex); device = btrfs_alloc_device(fs_info, NULL, NULL); if (IS_ERR(device)) { /* we can safely leave the fs_devices entry around */ ret = PTR_ERR(device); goto error; } name = rcu_string_strdup(device_path, GFP_KERNEL); if (!name) { ret = -ENOMEM; goto error_free_device; } rcu_assign_pointer(device->name, name); trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto error_free_device; } q = bdev_get_queue(bdev); set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); device->generation = trans->transid; device->io_width = fs_info->sectorsize; device->io_align = fs_info->sectorsize; device->sector_size = fs_info->sectorsize; device->total_bytes = round_down(i_size_read(bdev->bd_inode), fs_info->sectorsize); device->disk_total_bytes = device->total_bytes; device->commit_total_bytes = device->total_bytes; device->fs_info = fs_info; device->bdev = bdev; set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state); device->mode = FMODE_EXCL; device->dev_stats_valid = 1; set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE); if (seeding_dev) { sb->s_flags &= ~SB_RDONLY; ret = btrfs_prepare_sprout(fs_info); if (ret) { btrfs_abort_transaction(trans, ret); goto error_trans; } } device->fs_devices = fs_devices; mutex_lock(&fs_devices->device_list_mutex); mutex_lock(&fs_info->chunk_mutex); list_add_rcu(&device->dev_list, &fs_devices->devices); list_add(&device->dev_alloc_list, &fs_devices->alloc_list); fs_devices->num_devices++; fs_devices->open_devices++; fs_devices->rw_devices++; fs_devices->total_devices++; fs_devices->total_rw_bytes += device->total_bytes; atomic64_add(device->total_bytes, &fs_info->free_chunk_space); if (!blk_queue_nonrot(q)) fs_devices->rotating = 1; orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy); btrfs_set_super_total_bytes(fs_info->super_copy, round_down(orig_super_total_bytes + device->total_bytes, fs_info->sectorsize)); orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy); btrfs_set_super_num_devices(fs_info->super_copy, orig_super_num_devices + 1); /* add sysfs device entry */ btrfs_sysfs_add_device_link(fs_devices, device); /* * we've got more storage, clear any full flags on the space * infos */ btrfs_clear_space_info_full(fs_info); mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&fs_devices->device_list_mutex); if (seeding_dev) { mutex_lock(&fs_info->chunk_mutex); ret = init_first_rw_device(trans, fs_info); mutex_unlock(&fs_info->chunk_mutex); if (ret) { btrfs_abort_transaction(trans, ret); goto error_sysfs; } } ret = btrfs_add_dev_item(trans, device); if (ret) { btrfs_abort_transaction(trans, ret); goto error_sysfs; } if (seeding_dev) { char fsid_buf[BTRFS_UUID_UNPARSED_SIZE]; ret = btrfs_finish_sprout(trans, fs_info); if (ret) { btrfs_abort_transaction(trans, ret); goto error_sysfs; } /* Sprouting would change fsid of the mounted root, * so rename the fsid on the sysfs */ snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU", fs_info->fs_devices->fsid); if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf)) btrfs_warn(fs_info, "sysfs: failed to create fsid for sprout"); } ret = btrfs_commit_transaction(trans); if (seeding_dev) { mutex_unlock(&uuid_mutex); up_write(&sb->s_umount); unlocked = true; if (ret) /* transaction commit */ return ret; ret = btrfs_relocate_sys_chunks(fs_info); if (ret < 0) btrfs_handle_fs_error(fs_info, ret, "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command."); trans = btrfs_attach_transaction(root); if (IS_ERR(trans)) { if (PTR_ERR(trans) == -ENOENT) return 0; ret = PTR_ERR(trans); trans = NULL; goto error_sysfs; } ret = btrfs_commit_transaction(trans); } /* Update ctime/mtime for libblkid */ update_dev_time(device_path); return ret; error_sysfs: btrfs_sysfs_rm_device_link(fs_devices, device); mutex_lock(&fs_info->fs_devices->device_list_mutex); mutex_lock(&fs_info->chunk_mutex); list_del_rcu(&device->dev_list); list_del(&device->dev_alloc_list); fs_info->fs_devices->num_devices--; fs_info->fs_devices->open_devices--; fs_info->fs_devices->rw_devices--; fs_info->fs_devices->total_devices--; fs_info->fs_devices->total_rw_bytes -= device->total_bytes; atomic64_sub(device->total_bytes, &fs_info->free_chunk_space); btrfs_set_super_total_bytes(fs_info->super_copy, orig_super_total_bytes); btrfs_set_super_num_devices(fs_info->super_copy, orig_super_num_devices); mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&fs_info->fs_devices->device_list_mutex); error_trans: if (seeding_dev) sb->s_flags |= SB_RDONLY; if (trans) btrfs_end_transaction(trans); error_free_device: btrfs_free_device(device); error: blkdev_put(bdev, FMODE_EXCL); if (seeding_dev && !unlocked) { mutex_unlock(&uuid_mutex); up_write(&sb->s_umount); } return ret; } static noinline int btrfs_update_device(struct btrfs_trans_handle *trans, struct btrfs_device *device) { int ret; struct btrfs_path *path; struct btrfs_root *root = device->fs_info->chunk_root; struct btrfs_dev_item *dev_item; struct extent_buffer *leaf; struct btrfs_key key; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = BTRFS_DEV_ITEMS_OBJECTID; key.type = BTRFS_DEV_ITEM_KEY; key.offset = device->devid; ret = btrfs_search_slot(trans, root, &key, path, 0, 1); if (ret < 0) goto out; if (ret > 0) { ret = -ENOENT; goto out; } leaf = path->nodes[0]; dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item); btrfs_set_device_id(leaf, dev_item, device->devid); btrfs_set_device_type(leaf, dev_item, device->type); btrfs_set_device_io_align(leaf, dev_item, device->io_align); btrfs_set_device_io_width(leaf, dev_item, device->io_width); btrfs_set_device_sector_size(leaf, dev_item, device->sector_size); btrfs_set_device_total_bytes(leaf, dev_item, btrfs_device_get_disk_total_bytes(device)); btrfs_set_device_bytes_used(leaf, dev_item, btrfs_device_get_bytes_used(device)); btrfs_mark_buffer_dirty(leaf); out: btrfs_free_path(path); return ret; } int btrfs_grow_device(struct btrfs_trans_handle *trans, struct btrfs_device *device, u64 new_size) { struct btrfs_fs_info *fs_info = device->fs_info; struct btrfs_super_block *super_copy = fs_info->super_copy; struct btrfs_fs_devices *fs_devices; u64 old_total; u64 diff; if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) return -EACCES; new_size = round_down(new_size, fs_info->sectorsize); mutex_lock(&fs_info->chunk_mutex); old_total = btrfs_super_total_bytes(super_copy); diff = round_down(new_size - device->total_bytes, fs_info->sectorsize); if (new_size <= device->total_bytes || test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { mutex_unlock(&fs_info->chunk_mutex); return -EINVAL; } fs_devices = fs_info->fs_devices; btrfs_set_super_total_bytes(super_copy, round_down(old_total + diff, fs_info->sectorsize)); device->fs_devices->total_rw_bytes += diff; btrfs_device_set_total_bytes(device, new_size); btrfs_device_set_disk_total_bytes(device, new_size); btrfs_clear_space_info_full(device->fs_info); if (list_empty(&device->resized_list)) list_add_tail(&device->resized_list, &fs_devices->resized_devices); mutex_unlock(&fs_info->chunk_mutex); return btrfs_update_device(trans, device); } static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset) { struct btrfs_fs_info *fs_info = trans->fs_info; struct btrfs_root *root = fs_info->chunk_root; int ret; struct btrfs_path *path; struct btrfs_key key; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; key.offset = chunk_offset; key.type = BTRFS_CHUNK_ITEM_KEY; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) goto out; else if (ret > 0) { /* Logic error or corruption */ btrfs_handle_fs_error(fs_info, -ENOENT, "Failed lookup while freeing chunk."); ret = -ENOENT; goto out; } ret = btrfs_del_item(trans, root, path); if (ret < 0) btrfs_handle_fs_error(fs_info, ret, "Failed to delete chunk item."); out: btrfs_free_path(path); return ret; } static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset) { struct btrfs_super_block *super_copy = fs_info->super_copy; struct btrfs_disk_key *disk_key; struct btrfs_chunk *chunk; u8 *ptr; int ret = 0; u32 num_stripes; u32 array_size; u32 len = 0; u32 cur; struct btrfs_key key; mutex_lock(&fs_info->chunk_mutex); array_size = btrfs_super_sys_array_size(super_copy); ptr = super_copy->sys_chunk_array; cur = 0; while (cur < array_size) { disk_key = (struct btrfs_disk_key *)ptr; btrfs_disk_key_to_cpu(&key, disk_key); len = sizeof(*disk_key); if (key.type == BTRFS_CHUNK_ITEM_KEY) { chunk = (struct btrfs_chunk *)(ptr + len); num_stripes = btrfs_stack_chunk_num_stripes(chunk); len += btrfs_chunk_item_size(num_stripes); } else { ret = -EIO; break; } if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID && key.offset == chunk_offset) { memmove(ptr, ptr + len, array_size - (cur + len)); array_size -= len; btrfs_set_super_sys_array_size(super_copy, array_size); } else { ptr += len; cur += len; } } mutex_unlock(&fs_info->chunk_mutex); return ret; } /* * btrfs_get_chunk_map() - Find the mapping containing the given logical extent. * @logical: Logical block offset in bytes. * @length: Length of extent in bytes. * * Return: Chunk mapping or ERR_PTR. */ struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info, u64 logical, u64 length) { struct extent_map_tree *em_tree; struct extent_map *em; em_tree = &fs_info->mapping_tree.map_tree; read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, logical, length); read_unlock(&em_tree->lock); if (!em) { btrfs_crit(fs_info, "unable to find logical %llu length %llu", logical, length); return ERR_PTR(-EINVAL); } if (em->start > logical || em->start + em->len < logical) { btrfs_crit(fs_info, "found a bad mapping, wanted %llu-%llu, found %llu-%llu", logical, length, em->start, em->start + em->len); free_extent_map(em); return ERR_PTR(-EINVAL); } /* callers are responsible for dropping em's ref. */ return em; } int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset) { struct btrfs_fs_info *fs_info = trans->fs_info; struct extent_map *em; struct map_lookup *map; u64 dev_extent_len = 0; int i, ret = 0; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; em = btrfs_get_chunk_map(fs_info, chunk_offset, 1); if (IS_ERR(em)) { /* * This is a logic error, but we don't want to just rely on the * user having built with ASSERT enabled, so if ASSERT doesn't * do anything we still error out. */ ASSERT(0); return PTR_ERR(em); } map = em->map_lookup; mutex_lock(&fs_info->chunk_mutex); check_system_chunk(trans, map->type); mutex_unlock(&fs_info->chunk_mutex); /* * Take the device list mutex to prevent races with the final phase of * a device replace operation that replaces the device object associated * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()). */ mutex_lock(&fs_devices->device_list_mutex); for (i = 0; i < map->num_stripes; i++) { struct btrfs_device *device = map->stripes[i].dev; ret = btrfs_free_dev_extent(trans, device, map->stripes[i].physical, &dev_extent_len); if (ret) { mutex_unlock(&fs_devices->device_list_mutex); btrfs_abort_transaction(trans, ret); goto out; } if (device->bytes_used > 0) { mutex_lock(&fs_info->chunk_mutex); btrfs_device_set_bytes_used(device, device->bytes_used - dev_extent_len); atomic64_add(dev_extent_len, &fs_info->free_chunk_space); btrfs_clear_space_info_full(fs_info); mutex_unlock(&fs_info->chunk_mutex); } ret = btrfs_update_device(trans, device); if (ret) { mutex_unlock(&fs_devices->device_list_mutex); btrfs_abort_transaction(trans, ret); goto out; } } mutex_unlock(&fs_devices->device_list_mutex); ret = btrfs_free_chunk(trans, chunk_offset); if (ret) { btrfs_abort_transaction(trans, ret); goto out; } trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len); if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) { ret = btrfs_del_sys_chunk(fs_info, chunk_offset); if (ret) { btrfs_abort_transaction(trans, ret); goto out; } } ret = btrfs_remove_block_group(trans, chunk_offset, em); if (ret) { btrfs_abort_transaction(trans, ret); goto out; } out: /* once for us */ free_extent_map(em); return ret; } static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset) { struct btrfs_root *root = fs_info->chunk_root; struct btrfs_trans_handle *trans; int ret; /* * Prevent races with automatic removal of unused block groups. * After we relocate and before we remove the chunk with offset * chunk_offset, automatic removal of the block group can kick in, * resulting in a failure when calling btrfs_remove_chunk() below. * * Make sure to acquire this mutex before doing a tree search (dev * or chunk trees) to find chunks. Otherwise the cleaner kthread might * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after * we release the path used to search the chunk/dev tree and before * the current task acquires this mutex and calls us. */ lockdep_assert_held(&fs_info->delete_unused_bgs_mutex); ret = btrfs_can_relocate(fs_info, chunk_offset); if (ret) return -ENOSPC; /* step one, relocate all the extents inside this chunk */ btrfs_scrub_pause(fs_info); ret = btrfs_relocate_block_group(fs_info, chunk_offset); btrfs_scrub_continue(fs_info); if (ret) return ret; /* * We add the kobjects here (and after forcing data chunk creation) * since relocation is the only place we'll create chunks of a new * type at runtime. The only place where we'll remove the last * chunk of a type is the call immediately below this one. Even * so, we're protected against races with the cleaner thread since * we're covered by the delete_unused_bgs_mutex. */ btrfs_add_raid_kobjects(fs_info); trans = btrfs_start_trans_remove_block_group(root->fs_info, chunk_offset); if (IS_ERR(trans)) { ret = PTR_ERR(trans); btrfs_handle_fs_error(root->fs_info, ret, NULL); return ret; } /* * step two, delete the device extents and the * chunk tree entries */ ret = btrfs_remove_chunk(trans, chunk_offset); btrfs_end_transaction(trans); return ret; } static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info) { struct btrfs_root *chunk_root = fs_info->chunk_root; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_chunk *chunk; struct btrfs_key key; struct btrfs_key found_key; u64 chunk_type; bool retried = false; int failed = 0; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; again: key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; key.offset = (u64)-1; key.type = BTRFS_CHUNK_ITEM_KEY; while (1) { mutex_lock(&fs_info->delete_unused_bgs_mutex); ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0); if (ret < 0) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto error; } BUG_ON(ret == 0); /* Corruption */ ret = btrfs_previous_item(chunk_root, path, key.objectid, key.type); if (ret) mutex_unlock(&fs_info->delete_unused_bgs_mutex); if (ret < 0) goto error; if (ret > 0) break; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk); chunk_type = btrfs_chunk_type(leaf, chunk); btrfs_release_path(path); if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) { ret = btrfs_relocate_chunk(fs_info, found_key.offset); if (ret == -ENOSPC) failed++; else BUG_ON(ret); } mutex_unlock(&fs_info->delete_unused_bgs_mutex); if (found_key.offset == 0) break; key.offset = found_key.offset - 1; } ret = 0; if (failed && !retried) { failed = 0; retried = true; goto again; } else if (WARN_ON(failed && retried)) { ret = -ENOSPC; } error: btrfs_free_path(path); return ret; } /* * return 1 : allocate a data chunk successfully, * return <0: errors during allocating a data chunk, * return 0 : no need to allocate a data chunk. */ static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset) { struct btrfs_block_group_cache *cache; u64 bytes_used; u64 chunk_type; cache = btrfs_lookup_block_group(fs_info, chunk_offset); ASSERT(cache); chunk_type = cache->flags; btrfs_put_block_group(cache); if (chunk_type & BTRFS_BLOCK_GROUP_DATA) { spin_lock(&fs_info->data_sinfo->lock); bytes_used = fs_info->data_sinfo->bytes_used; spin_unlock(&fs_info->data_sinfo->lock); if (!bytes_used) { struct btrfs_trans_handle *trans; int ret; trans = btrfs_join_transaction(fs_info->tree_root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA); btrfs_end_transaction(trans); if (ret < 0) return ret; btrfs_add_raid_kobjects(fs_info); return 1; } } return 0; } static int insert_balance_item(struct btrfs_fs_info *fs_info, struct btrfs_balance_control *bctl) { struct btrfs_root *root = fs_info->tree_root; struct btrfs_trans_handle *trans; struct btrfs_balance_item *item; struct btrfs_disk_balance_args disk_bargs; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key key; int ret, err; path = btrfs_alloc_path(); if (!path) return -ENOMEM; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { btrfs_free_path(path); return PTR_ERR(trans); } key.objectid = BTRFS_BALANCE_OBJECTID; key.type = BTRFS_TEMPORARY_ITEM_KEY; key.offset = 0; ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*item)); if (ret) goto out; leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item); memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item)); btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data); btrfs_set_balance_data(leaf, item, &disk_bargs); btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta); btrfs_set_balance_meta(leaf, item, &disk_bargs); btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys); btrfs_set_balance_sys(leaf, item, &disk_bargs); btrfs_set_balance_flags(leaf, item, bctl->flags); btrfs_mark_buffer_dirty(leaf); out: btrfs_free_path(path); err = btrfs_commit_transaction(trans); if (err && !ret) ret = err; return ret; } static int del_balance_item(struct btrfs_fs_info *fs_info) { struct btrfs_root *root = fs_info->tree_root; struct btrfs_trans_handle *trans; struct btrfs_path *path; struct btrfs_key key; int ret, err; path = btrfs_alloc_path(); if (!path) return -ENOMEM; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { btrfs_free_path(path); return PTR_ERR(trans); } key.objectid = BTRFS_BALANCE_OBJECTID; key.type = BTRFS_TEMPORARY_ITEM_KEY; key.offset = 0; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) goto out; if (ret > 0) { ret = -ENOENT; goto out; } ret = btrfs_del_item(trans, root, path); out: btrfs_free_path(path); err = btrfs_commit_transaction(trans); if (err && !ret) ret = err; return ret; } /* * This is a heuristic used to reduce the number of chunks balanced on * resume after balance was interrupted. */ static void update_balance_args(struct btrfs_balance_control *bctl) { /* * Turn on soft mode for chunk types that were being converted. */ if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT; if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT; if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT; /* * Turn on usage filter if is not already used. The idea is * that chunks that we have already balanced should be * reasonably full. Don't do it for chunks that are being * converted - that will keep us from relocating unconverted * (albeit full) chunks. */ if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) && !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) { bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE; bctl->data.usage = 90; } if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) && !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) { bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE; bctl->sys.usage = 90; } if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) && !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) { bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE; bctl->meta.usage = 90; } } /* * Clear the balance status in fs_info and delete the balance item from disk. */ static void reset_balance_state(struct btrfs_fs_info *fs_info) { struct btrfs_balance_control *bctl = fs_info->balance_ctl; int ret; BUG_ON(!fs_info->balance_ctl); spin_lock(&fs_info->balance_lock); fs_info->balance_ctl = NULL; spin_unlock(&fs_info->balance_lock); kfree(bctl); ret = del_balance_item(fs_info); if (ret) btrfs_handle_fs_error(fs_info, ret, NULL); } /* * Balance filters. Return 1 if chunk should be filtered out * (should not be balanced). */ static int chunk_profiles_filter(u64 chunk_type, struct btrfs_balance_args *bargs) { chunk_type = chunk_to_extended(chunk_type) & BTRFS_EXTENDED_PROFILE_MASK; if (bargs->profiles & chunk_type) return 0; return 1; } static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset, struct btrfs_balance_args *bargs) { struct btrfs_block_group_cache *cache; u64 chunk_used; u64 user_thresh_min; u64 user_thresh_max; int ret = 1; cache = btrfs_lookup_block_group(fs_info, chunk_offset); chunk_used = btrfs_block_group_used(&cache->item); if (bargs->usage_min == 0) user_thresh_min = 0; else user_thresh_min = div_factor_fine(cache->key.offset, bargs->usage_min); if (bargs->usage_max == 0) user_thresh_max = 1; else if (bargs->usage_max > 100) user_thresh_max = cache->key.offset; else user_thresh_max = div_factor_fine(cache->key.offset, bargs->usage_max); if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max) ret = 0; btrfs_put_block_group(cache); return ret; } static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset, struct btrfs_balance_args *bargs) { struct btrfs_block_group_cache *cache; u64 chunk_used, user_thresh; int ret = 1; cache = btrfs_lookup_block_group(fs_info, chunk_offset); chunk_used = btrfs_block_group_used(&cache->item); if (bargs->usage_min == 0) user_thresh = 1; else if (bargs->usage > 100) user_thresh = cache->key.offset; else user_thresh = div_factor_fine(cache->key.offset, bargs->usage); if (chunk_used < user_thresh) ret = 0; btrfs_put_block_group(cache); return ret; } static int chunk_devid_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk, struct btrfs_balance_args *bargs) { struct btrfs_stripe *stripe; int num_stripes = btrfs_chunk_num_stripes(leaf, chunk); int i; for (i = 0; i < num_stripes; i++) { stripe = btrfs_stripe_nr(chunk, i); if (btrfs_stripe_devid(leaf, stripe) == bargs->devid) return 0; } return 1; } /* [pstart, pend) */ static int chunk_drange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk, struct btrfs_balance_args *bargs) { struct btrfs_stripe *stripe; int num_stripes = btrfs_chunk_num_stripes(leaf, chunk); u64 stripe_offset; u64 stripe_length; int factor; int i; if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID)) return 0; if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) { factor = num_stripes / 2; } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) { factor = num_stripes - 1; } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) { factor = num_stripes - 2; } else { factor = num_stripes; } for (i = 0; i < num_stripes; i++) { stripe = btrfs_stripe_nr(chunk, i); if (btrfs_stripe_devid(leaf, stripe) != bargs->devid) continue; stripe_offset = btrfs_stripe_offset(leaf, stripe); stripe_length = btrfs_chunk_length(leaf, chunk); stripe_length = div_u64(stripe_length, factor); if (stripe_offset < bargs->pend && stripe_offset + stripe_length > bargs->pstart) return 0; } return 1; } /* [vstart, vend) */ static int chunk_vrange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk, u64 chunk_offset, struct btrfs_balance_args *bargs) { if (chunk_offset < bargs->vend && chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart) /* at least part of the chunk is inside this vrange */ return 0; return 1; } static int chunk_stripes_range_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk, struct btrfs_balance_args *bargs) { int num_stripes = btrfs_chunk_num_stripes(leaf, chunk); if (bargs->stripes_min <= num_stripes && num_stripes <= bargs->stripes_max) return 0; return 1; } static int chunk_soft_convert_filter(u64 chunk_type, struct btrfs_balance_args *bargs) { if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT)) return 0; chunk_type = chunk_to_extended(chunk_type) & BTRFS_EXTENDED_PROFILE_MASK; if (bargs->target == chunk_type) return 1; return 0; } static int should_balance_chunk(struct btrfs_fs_info *fs_info, struct extent_buffer *leaf, struct btrfs_chunk *chunk, u64 chunk_offset) { struct btrfs_balance_control *bctl = fs_info->balance_ctl; struct btrfs_balance_args *bargs = NULL; u64 chunk_type = btrfs_chunk_type(leaf, chunk); /* type filter */ if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) & (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) { return 0; } if (chunk_type & BTRFS_BLOCK_GROUP_DATA) bargs = &bctl->data; else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) bargs = &bctl->sys; else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA) bargs = &bctl->meta; /* profiles filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) && chunk_profiles_filter(chunk_type, bargs)) { return 0; } /* usage filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) && chunk_usage_filter(fs_info, chunk_offset, bargs)) { return 0; } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && chunk_usage_range_filter(fs_info, chunk_offset, bargs)) { return 0; } /* devid filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) && chunk_devid_filter(leaf, chunk, bargs)) { return 0; } /* drange filter, makes sense only with devid filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) && chunk_drange_filter(leaf, chunk, bargs)) { return 0; } /* vrange filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) && chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) { return 0; } /* stripes filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) && chunk_stripes_range_filter(leaf, chunk, bargs)) { return 0; } /* soft profile changing mode */ if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) && chunk_soft_convert_filter(chunk_type, bargs)) { return 0; } /* * limited by count, must be the last filter */ if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) { if (bargs->limit == 0) return 0; else bargs->limit--; } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) { /* * Same logic as the 'limit' filter; the minimum cannot be * determined here because we do not have the global information * about the count of all chunks that satisfy the filters. */ if (bargs->limit_max == 0) return 0; else bargs->limit_max--; } return 1; } static int __btrfs_balance(struct btrfs_fs_info *fs_info) { struct btrfs_balance_control *bctl = fs_info->balance_ctl; struct btrfs_root *chunk_root = fs_info->chunk_root; u64 chunk_type; struct btrfs_chunk *chunk; struct btrfs_path *path = NULL; struct btrfs_key key; struct btrfs_key found_key; struct extent_buffer *leaf; int slot; int ret; int enospc_errors = 0; bool counting = true; /* The single value limit and min/max limits use the same bytes in the */ u64 limit_data = bctl->data.limit; u64 limit_meta = bctl->meta.limit; u64 limit_sys = bctl->sys.limit; u32 count_data = 0; u32 count_meta = 0; u32 count_sys = 0; int chunk_reserved = 0; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto error; } /* zero out stat counters */ spin_lock(&fs_info->balance_lock); memset(&bctl->stat, 0, sizeof(bctl->stat)); spin_unlock(&fs_info->balance_lock); again: if (!counting) { /* * The single value limit and min/max limits use the same bytes * in the */ bctl->data.limit = limit_data; bctl->meta.limit = limit_meta; bctl->sys.limit = limit_sys; } key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; key.offset = (u64)-1; key.type = BTRFS_CHUNK_ITEM_KEY; while (1) { if ((!counting && atomic_read(&fs_info->balance_pause_req)) || atomic_read(&fs_info->balance_cancel_req)) { ret = -ECANCELED; goto error; } mutex_lock(&fs_info->delete_unused_bgs_mutex); ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0); if (ret < 0) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto error; } /* * this shouldn't happen, it means the last relocate * failed */ if (ret == 0) BUG(); /* FIXME break ? */ ret = btrfs_previous_item(chunk_root, path, 0, BTRFS_CHUNK_ITEM_KEY); if (ret) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); ret = 0; break; } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &found_key, slot); if (found_key.objectid != key.objectid) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); break; } chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk); chunk_type = btrfs_chunk_type(leaf, chunk); if (!counting) { spin_lock(&fs_info->balance_lock); bctl->stat.considered++; spin_unlock(&fs_info->balance_lock); } ret = should_balance_chunk(fs_info, leaf, chunk, found_key.offset); btrfs_release_path(path); if (!ret) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto loop; } if (counting) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); spin_lock(&fs_info->balance_lock); bctl->stat.expected++; spin_unlock(&fs_info->balance_lock); if (chunk_type & BTRFS_BLOCK_GROUP_DATA) count_data++; else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) count_sys++; else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA) count_meta++; goto loop; } /* * Apply limit_min filter, no need to check if the LIMITS * filter is used, limit_min is 0 by default */ if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) && count_data < bctl->data.limit_min) || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) && count_meta < bctl->meta.limit_min) || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) && count_sys < bctl->sys.limit_min)) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto loop; } if (!chunk_reserved) { /* * We may be relocating the only data chunk we have, * which could potentially end up with losing data's * raid profile, so lets allocate an empty one in * advance. */ ret = btrfs_may_alloc_data_chunk(fs_info, found_key.offset); if (ret < 0) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto error; } else if (ret == 1) { chunk_reserved = 1; } } ret = btrfs_relocate_chunk(fs_info, found_key.offset); mutex_unlock(&fs_info->delete_unused_bgs_mutex); if (ret == -ENOSPC) { enospc_errors++; } else if (ret == -ETXTBSY) { btrfs_info(fs_info, "skipping relocation of block group %llu due to active swapfile", found_key.offset); ret = 0; } else if (ret) { goto error; } else { spin_lock(&fs_info->balance_lock); bctl->stat.completed++; spin_unlock(&fs_info->balance_lock); } loop: if (found_key.offset == 0) break; key.offset = found_key.offset - 1; } if (counting) { btrfs_release_path(path); counting = false; goto again; } error: btrfs_free_path(path); if (enospc_errors) { btrfs_info(fs_info, "%d enospc errors during balance", enospc_errors); if (!ret) ret = -ENOSPC; } return ret; } /** * alloc_profile_is_valid - see if a given profile is valid and reduced * @flags: profile to validate * @extended: if true @flags is treated as an extended profile */ static int alloc_profile_is_valid(u64 flags, int extended) { u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK : BTRFS_BLOCK_GROUP_PROFILE_MASK); flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK; /* 1) check that all other bits are zeroed */ if (flags & ~mask) return 0; /* 2) see if profile is reduced */ if (flags == 0) return !extended; /* "0" is valid for usual profiles */ /* true if exactly one bit set */ return is_power_of_2(flags); } static inline int balance_need_close(struct btrfs_fs_info *fs_info) { /* cancel requested || normal exit path */ return atomic_read(&fs_info->balance_cancel_req) || (atomic_read(&fs_info->balance_pause_req) == 0 && atomic_read(&fs_info->balance_cancel_req) == 0); } /* Non-zero return value signifies invalidity */ static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg, u64 allowed) { return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) && (!alloc_profile_is_valid(bctl_arg->target, 1) || (bctl_arg->target & ~allowed))); } /* * Fill @buf with textual description of balance filter flags @bargs, up to * @size_buf including the terminating null. The output may be trimmed if it * does not fit into the provided buffer. */ static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf, u32 size_buf) { int ret; u32 size_bp = size_buf; char *bp = buf; u64 flags = bargs->flags; char tmp_buf[128] = {'\0'}; if (!flags) return; #define CHECK_APPEND_NOARG(a) \ do { \ ret = snprintf(bp, size_bp, (a)); \ if (ret < 0 || ret >= size_bp) \ goto out_overflow; \ size_bp -= ret; \ bp += ret; \ } while (0) #define CHECK_APPEND_1ARG(a, v1) \ do { \ ret = snprintf(bp, size_bp, (a), (v1)); \ if (ret < 0 || ret >= size_bp) \ goto out_overflow; \ size_bp -= ret; \ bp += ret; \ } while (0) #define CHECK_APPEND_2ARG(a, v1, v2) \ do { \ ret = snprintf(bp, size_bp, (a), (v1), (v2)); \ if (ret < 0 || ret >= size_bp) \ goto out_overflow; \ size_bp -= ret; \ bp += ret; \ } while (0) if (flags & BTRFS_BALANCE_ARGS_CONVERT) { int index = btrfs_bg_flags_to_raid_index(bargs->target); CHECK_APPEND_1ARG("convert=%s,", get_raid_name(index)); } if (flags & BTRFS_BALANCE_ARGS_SOFT) CHECK_APPEND_NOARG("soft,"); if (flags & BTRFS_BALANCE_ARGS_PROFILES) { btrfs_describe_block_groups(bargs->profiles, tmp_buf, sizeof(tmp_buf)); CHECK_APPEND_1ARG("profiles=%s,", tmp_buf); } if (flags & BTRFS_BALANCE_ARGS_USAGE) CHECK_APPEND_1ARG("usage=%llu,", bargs->usage); if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) CHECK_APPEND_2ARG("usage=%u..%u,", bargs->usage_min, bargs->usage_max); if (flags & BTRFS_BALANCE_ARGS_DEVID) CHECK_APPEND_1ARG("devid=%llu,", bargs->devid); if (flags & BTRFS_BALANCE_ARGS_DRANGE) CHECK_APPEND_2ARG("drange=%llu..%llu,", bargs->pstart, bargs->pend); if (flags & BTRFS_BALANCE_ARGS_VRANGE) CHECK_APPEND_2ARG("vrange=%llu..%llu,", bargs->vstart, bargs->vend); if (flags & BTRFS_BALANCE_ARGS_LIMIT) CHECK_APPEND_1ARG("limit=%llu,", bargs->limit); if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE) CHECK_APPEND_2ARG("limit=%u..%u,", bargs->limit_min, bargs->limit_max); if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) CHECK_APPEND_2ARG("stripes=%u..%u,", bargs->stripes_min, bargs->stripes_max); #undef CHECK_APPEND_2ARG #undef CHECK_APPEND_1ARG #undef CHECK_APPEND_NOARG out_overflow: if (size_bp < size_buf) buf[size_buf - size_bp - 1] = '\0'; /* remove last , */ else buf[0] = '\0'; } static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info) { u32 size_buf = 1024; char tmp_buf[192] = {'\0'}; char *buf; char *bp; u32 size_bp = size_buf; int ret; struct btrfs_balance_control *bctl = fs_info->balance_ctl; buf = kzalloc(size_buf, GFP_KERNEL); if (!buf) return; bp = buf; #define CHECK_APPEND_1ARG(a, v1) \ do { \ ret = snprintf(bp, size_bp, (a), (v1)); \ if (ret < 0 || ret >= size_bp) \ goto out_overflow; \ size_bp -= ret; \ bp += ret; \ } while (0) if (bctl->flags & BTRFS_BALANCE_FORCE) CHECK_APPEND_1ARG("%s", "-f "); if (bctl->flags & BTRFS_BALANCE_DATA) { describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf)); CHECK_APPEND_1ARG("-d%s ", tmp_buf); } if (bctl->flags & BTRFS_BALANCE_METADATA) { describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf)); CHECK_APPEND_1ARG("-m%s ", tmp_buf); } if (bctl->flags & BTRFS_BALANCE_SYSTEM) { describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf)); CHECK_APPEND_1ARG("-s%s ", tmp_buf); } #undef CHECK_APPEND_1ARG out_overflow: if (size_bp < size_buf) buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */ btrfs_info(fs_info, "balance: %s %s", (bctl->flags & BTRFS_BALANCE_RESUME) ? "resume" : "start", buf); kfree(buf); } /* * Should be called with balance mutexe held */ int btrfs_balance(struct btrfs_fs_info *fs_info, struct btrfs_balance_control *bctl, struct btrfs_ioctl_balance_args *bargs) { u64 meta_target, data_target; u64 allowed; int mixed = 0; int ret; u64 num_devices; unsigned seq; bool reducing_integrity; if (btrfs_fs_closing(fs_info) || atomic_read(&fs_info->balance_pause_req) || atomic_read(&fs_info->balance_cancel_req)) { ret = -EINVAL; goto out; } allowed = btrfs_super_incompat_flags(fs_info->super_copy); if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) mixed = 1; /* * In case of mixed groups both data and meta should be picked, * and identical options should be given for both of them. */ allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA; if (mixed && (bctl->flags & allowed)) { if (!(bctl->flags & BTRFS_BALANCE_DATA) || !(bctl->flags & BTRFS_BALANCE_METADATA) || memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) { btrfs_err(fs_info, "balance: mixed groups data and metadata options must be the same"); ret = -EINVAL; goto out; } } num_devices = btrfs_num_devices(fs_info); allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP; if (num_devices > 1) allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1); if (num_devices > 2) allowed |= BTRFS_BLOCK_GROUP_RAID5; if (num_devices > 3) allowed |= (BTRFS_BLOCK_GROUP_RAID10 | BTRFS_BLOCK_GROUP_RAID6); if (validate_convert_profile(&bctl->data, allowed)) { int index = btrfs_bg_flags_to_raid_index(bctl->data.target); btrfs_err(fs_info, "balance: invalid convert data profile %s", get_raid_name(index)); ret = -EINVAL; goto out; } if (validate_convert_profile(&bctl->meta, allowed)) { int index = btrfs_bg_flags_to_raid_index(bctl->meta.target); btrfs_err(fs_info, "balance: invalid convert metadata profile %s", get_raid_name(index)); ret = -EINVAL; goto out; } if (validate_convert_profile(&bctl->sys, allowed)) { int index = btrfs_bg_flags_to_raid_index(bctl->sys.target); btrfs_err(fs_info, "balance: invalid convert system profile %s", get_raid_name(index)); ret = -EINVAL; goto out; } /* allow to reduce meta or sys integrity only if force set */ allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10 | BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6; do { seq = read_seqbegin(&fs_info->profiles_lock); if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) && (fs_info->avail_system_alloc_bits & allowed) && !(bctl->sys.target & allowed)) || ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) && (fs_info->avail_metadata_alloc_bits & allowed) && !(bctl->meta.target & allowed))) reducing_integrity = true; else reducing_integrity = false; /* if we're not converting, the target field is uninitialized */ meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ? bctl->meta.target : fs_info->avail_metadata_alloc_bits; data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ? bctl->data.target : fs_info->avail_data_alloc_bits; } while (read_seqretry(&fs_info->profiles_lock, seq)); if (reducing_integrity) { if (bctl->flags & BTRFS_BALANCE_FORCE) { btrfs_info(fs_info, "balance: force reducing metadata integrity"); } else { btrfs_err(fs_info, "balance: reduces metadata integrity, use --force if you want this"); ret = -EINVAL; goto out; } } if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) < btrfs_get_num_tolerated_disk_barrier_failures(data_target)) { int meta_index = btrfs_bg_flags_to_raid_index(meta_target); int data_index = btrfs_bg_flags_to_raid_index(data_target); btrfs_warn(fs_info, "balance: metadata profile %s has lower redundancy than data profile %s", get_raid_name(meta_index), get_raid_name(data_index)); } ret = insert_balance_item(fs_info, bctl); if (ret && ret != -EEXIST) goto out; if (!(bctl->flags & BTRFS_BALANCE_RESUME)) { BUG_ON(ret == -EEXIST); BUG_ON(fs_info->balance_ctl); spin_lock(&fs_info->balance_lock); fs_info->balance_ctl = bctl; spin_unlock(&fs_info->balance_lock); } else { BUG_ON(ret != -EEXIST); spin_lock(&fs_info->balance_lock); update_balance_args(bctl); spin_unlock(&fs_info->balance_lock); } ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags); describe_balance_start_or_resume(fs_info); mutex_unlock(&fs_info->balance_mutex); ret = __btrfs_balance(fs_info); mutex_lock(&fs_info->balance_mutex); if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) btrfs_info(fs_info, "balance: paused"); else if (ret == -ECANCELED && atomic_read(&fs_info->balance_cancel_req)) btrfs_info(fs_info, "balance: canceled"); else btrfs_info(fs_info, "balance: ended with status: %d", ret); clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags); if (bargs) { memset(bargs, 0, sizeof(*bargs)); btrfs_update_ioctl_balance_args(fs_info, bargs); } if ((ret && ret != -ECANCELED && ret != -ENOSPC) || balance_need_close(fs_info)) { reset_balance_state(fs_info); clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); } wake_up(&fs_info->balance_wait_q); return ret; out: if (bctl->flags & BTRFS_BALANCE_RESUME) reset_balance_state(fs_info); else kfree(bctl); clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); return ret; } static int balance_kthread(void *data) { struct btrfs_fs_info *fs_info = data; int ret = 0; mutex_lock(&fs_info->balance_mutex); if (fs_info->balance_ctl) ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL); mutex_unlock(&fs_info->balance_mutex); return ret; } int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info) { struct task_struct *tsk; mutex_lock(&fs_info->balance_mutex); if (!fs_info->balance_ctl) { mutex_unlock(&fs_info->balance_mutex); return 0; } mutex_unlock(&fs_info->balance_mutex); if (btrfs_test_opt(fs_info, SKIP_BALANCE)) { btrfs_info(fs_info, "balance: resume skipped"); return 0; } /* * A ro->rw remount sequence should continue with the paused balance * regardless of who pauses it, system or the user as of now, so set * the resume flag. */ spin_lock(&fs_info->balance_lock); fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME; spin_unlock(&fs_info->balance_lock); tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance"); return PTR_ERR_OR_ZERO(tsk); } int btrfs_recover_balance(struct btrfs_fs_info *fs_info) { struct btrfs_balance_control *bctl; struct btrfs_balance_item *item; struct btrfs_disk_balance_args disk_bargs; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key key; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = BTRFS_BALANCE_OBJECTID; key.type = BTRFS_TEMPORARY_ITEM_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0); if (ret < 0) goto out; if (ret > 0) { /* ret = -ENOENT; */ ret = 0; goto out; } bctl = kzalloc(sizeof(*bctl), GFP_NOFS); if (!bctl) { ret = -ENOMEM; goto out; } leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item); bctl->flags = btrfs_balance_flags(leaf, item); bctl->flags |= BTRFS_BALANCE_RESUME; btrfs_balance_data(leaf, item, &disk_bargs); btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs); btrfs_balance_meta(leaf, item, &disk_bargs); btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs); btrfs_balance_sys(leaf, item, &disk_bargs); btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs); /* * This should never happen, as the paused balance state is recovered * during mount without any chance of other exclusive ops to collide. * * This gives the exclusive op status to balance and keeps in paused * state until user intervention (cancel or umount). If the ownership * cannot be assigned, show a message but do not fail. The balance * is in a paused state and must have fs_info::balance_ctl properly * set up. */ if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) btrfs_warn(fs_info, "balance: cannot set exclusive op status, resume manually"); mutex_lock(&fs_info->balance_mutex); BUG_ON(fs_info->balance_ctl); spin_lock(&fs_info->balance_lock); fs_info->balance_ctl = bctl; spin_unlock(&fs_info->balance_lock); mutex_unlock(&fs_info->balance_mutex); out: btrfs_free_path(path); return ret; } int btrfs_pause_balance(struct btrfs_fs_info *fs_info) { int ret = 0; mutex_lock(&fs_info->balance_mutex); if (!fs_info->balance_ctl) { mutex_unlock(&fs_info->balance_mutex); return -ENOTCONN; } if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) { atomic_inc(&fs_info->balance_pause_req); mutex_unlock(&fs_info->balance_mutex); wait_event(fs_info->balance_wait_q, !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); mutex_lock(&fs_info->balance_mutex); /* we are good with balance_ctl ripped off from under us */ BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); atomic_dec(&fs_info->balance_pause_req); } else { ret = -ENOTCONN; } mutex_unlock(&fs_info->balance_mutex); return ret; } int btrfs_cancel_balance(struct btrfs_fs_info *fs_info) { mutex_lock(&fs_info->balance_mutex); if (!fs_info->balance_ctl) { mutex_unlock(&fs_info->balance_mutex); return -ENOTCONN; } /* * A paused balance with the item stored on disk can be resumed at * mount time if the mount is read-write. Otherwise it's still paused * and we must not allow cancelling as it deletes the item. */ if (sb_rdonly(fs_info->sb)) { mutex_unlock(&fs_info->balance_mutex); return -EROFS; } atomic_inc(&fs_info->balance_cancel_req); /* * if we are running just wait and return, balance item is * deleted in btrfs_balance in this case */ if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) { mutex_unlock(&fs_info->balance_mutex); wait_event(fs_info->balance_wait_q, !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); mutex_lock(&fs_info->balance_mutex); } else { mutex_unlock(&fs_info->balance_mutex); /* * Lock released to allow other waiters to continue, we'll * reexamine the status again. */ mutex_lock(&fs_info->balance_mutex); if (fs_info->balance_ctl) { reset_balance_state(fs_info); clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); btrfs_info(fs_info, "balance: canceled"); } } BUG_ON(fs_info->balance_ctl || test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); atomic_dec(&fs_info->balance_cancel_req); mutex_unlock(&fs_info->balance_mutex); return 0; } static int btrfs_uuid_scan_kthread(void *data) { struct btrfs_fs_info *fs_info = data; struct btrfs_root *root = fs_info->tree_root; struct btrfs_key key; struct btrfs_path *path = NULL; int ret = 0; struct extent_buffer *eb; int slot; struct btrfs_root_item root_item; u32 item_size; struct btrfs_trans_handle *trans = NULL; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } key.objectid = 0; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = 0; while (1) { ret = btrfs_search_forward(root, &key, path, BTRFS_OLDEST_GENERATION); if (ret) { if (ret > 0) ret = 0; break; } if (key.type != BTRFS_ROOT_ITEM_KEY || (key.objectid < BTRFS_FIRST_FREE_OBJECTID && key.objectid != BTRFS_FS_TREE_OBJECTID) || key.objectid > BTRFS_LAST_FREE_OBJECTID) goto skip; eb = path->nodes[0]; slot = path->slots[0]; item_size = btrfs_item_size_nr(eb, slot); if (item_size < sizeof(root_item)) goto skip; read_extent_buffer(eb, &root_item, btrfs_item_ptr_offset(eb, slot), (int)sizeof(root_item)); if (btrfs_root_refs(&root_item) == 0) goto skip; if (!btrfs_is_empty_uuid(root_item.uuid) || !btrfs_is_empty_uuid(root_item.received_uuid)) { if (trans) goto update_tree; btrfs_release_path(path); /* * 1 - subvol uuid item * 1 - received_subvol uuid item */ trans = btrfs_start_transaction(fs_info->uuid_root, 2); if (IS_ERR(trans)) { ret = PTR_ERR(trans); break; } continue; } else { goto skip; } update_tree: if (!btrfs_is_empty_uuid(root_item.uuid)) { ret = btrfs_uuid_tree_add(trans, root_item.uuid, BTRFS_UUID_KEY_SUBVOL, key.objectid); if (ret < 0) { btrfs_warn(fs_info, "uuid_tree_add failed %d", ret); break; } } if (!btrfs_is_empty_uuid(root_item.received_uuid)) { ret = btrfs_uuid_tree_add(trans, root_item.received_uuid, BTRFS_UUID_KEY_RECEIVED_SUBVOL, key.objectid); if (ret < 0) { btrfs_warn(fs_info, "uuid_tree_add failed %d", ret); break; } } skip: if (trans) { ret = btrfs_end_transaction(trans); trans = NULL; if (ret) break; } btrfs_release_path(path); if (key.offset < (u64)-1) { key.offset++; } else if (key.type < BTRFS_ROOT_ITEM_KEY) { key.offset = 0; key.type = BTRFS_ROOT_ITEM_KEY; } else if (key.objectid < (u64)-1) { key.offset = 0; key.type = BTRFS_ROOT_ITEM_KEY; key.objectid++; } else { break; } cond_resched(); } out: btrfs_free_path(path); if (trans && !IS_ERR(trans)) btrfs_end_transaction(trans); if (ret) btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret); else set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags); up(&fs_info->uuid_tree_rescan_sem); return 0; } /* * Callback for btrfs_uuid_tree_iterate(). * returns: * 0 check succeeded, the entry is not outdated. * < 0 if an error occurred. * > 0 if the check failed, which means the caller shall remove the entry. */ static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info, u8 *uuid, u8 type, u64 subid) { struct btrfs_key key; int ret = 0; struct btrfs_root *subvol_root; if (type != BTRFS_UUID_KEY_SUBVOL && type != BTRFS_UUID_KEY_RECEIVED_SUBVOL) goto out; key.objectid = subid; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; subvol_root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(subvol_root)) { ret = PTR_ERR(subvol_root); if (ret == -ENOENT) ret = 1; goto out; } switch (type) { case BTRFS_UUID_KEY_SUBVOL: if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE)) ret = 1; break; case BTRFS_UUID_KEY_RECEIVED_SUBVOL: if (memcmp(uuid, subvol_root->root_item.received_uuid, BTRFS_UUID_SIZE)) ret = 1; break; } out: return ret; } static int btrfs_uuid_rescan_kthread(void *data) { struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data; int ret; /* * 1st step is to iterate through the existing UUID tree and * to delete all entries that contain outdated data. * 2nd step is to add all missing entries to the UUID tree. */ ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry); if (ret < 0) { btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret); up(&fs_info->uuid_tree_rescan_sem); return ret; } return btrfs_uuid_scan_kthread(data); } int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info) { struct btrfs_trans_handle *trans; struct btrfs_root *tree_root = fs_info->tree_root; struct btrfs_root *uuid_root; struct task_struct *task; int ret; /* * 1 - root node * 1 - root item */ trans = btrfs_start_transaction(tree_root, 2); if (IS_ERR(trans)) return PTR_ERR(trans); uuid_root = btrfs_create_tree(trans, fs_info, BTRFS_UUID_TREE_OBJECTID); if (IS_ERR(uuid_root)) { ret = PTR_ERR(uuid_root); btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); return ret; } fs_info->uuid_root = uuid_root; ret = btrfs_commit_transaction(trans); if (ret) return ret; down(&fs_info->uuid_tree_rescan_sem); task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid"); if (IS_ERR(task)) { /* fs_info->update_uuid_tree_gen remains 0 in all error case */ btrfs_warn(fs_info, "failed to start uuid_scan task"); up(&fs_info->uuid_tree_rescan_sem); return PTR_ERR(task); } return 0; } int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info) { struct task_struct *task; down(&fs_info->uuid_tree_rescan_sem); task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid"); if (IS_ERR(task)) { /* fs_info->update_uuid_tree_gen remains 0 in all error case */ btrfs_warn(fs_info, "failed to start uuid_rescan task"); up(&fs_info->uuid_tree_rescan_sem); return PTR_ERR(task); } return 0; } /* * shrinking a device means finding all of the device extents past * the new size, and then following the back refs to the chunks. * The chunk relocation code actually frees the device extent */ int btrfs_shrink_device(struct btrfs_device *device, u64 new_size) { struct btrfs_fs_info *fs_info = device->fs_info; struct btrfs_root *root = fs_info->dev_root; struct btrfs_trans_handle *trans; struct btrfs_dev_extent *dev_extent = NULL; struct btrfs_path *path; u64 length; u64 chunk_offset; int ret; int slot; int failed = 0; bool retried = false; bool checked_pending_chunks = false; struct extent_buffer *l; struct btrfs_key key; struct btrfs_super_block *super_copy = fs_info->super_copy; u64 old_total = btrfs_super_total_bytes(super_copy); u64 old_size = btrfs_device_get_total_bytes(device); u64 diff; new_size = round_down(new_size, fs_info->sectorsize); diff = round_down(old_size - new_size, fs_info->sectorsize); if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) return -EINVAL; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = READA_BACK; mutex_lock(&fs_info->chunk_mutex); btrfs_device_set_total_bytes(device, new_size); if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { device->fs_devices->total_rw_bytes -= diff; atomic64_sub(diff, &fs_info->free_chunk_space); } mutex_unlock(&fs_info->chunk_mutex); again: key.objectid = device->devid; key.offset = (u64)-1; key.type = BTRFS_DEV_EXTENT_KEY; do { mutex_lock(&fs_info->delete_unused_bgs_mutex); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto done; } ret = btrfs_previous_item(root, path, 0, key.type); if (ret) mutex_unlock(&fs_info->delete_unused_bgs_mutex); if (ret < 0) goto done; if (ret) { ret = 0; btrfs_release_path(path); break; } l = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(l, &key, path->slots[0]); if (key.objectid != device->devid) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); btrfs_release_path(path); break; } dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent); length = btrfs_dev_extent_length(l, dev_extent); if (key.offset + length <= new_size) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); btrfs_release_path(path); break; } chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent); btrfs_release_path(path); /* * We may be relocating the only data chunk we have, * which could potentially end up with losing data's * raid profile, so lets allocate an empty one in * advance. */ ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset); if (ret < 0) { mutex_unlock(&fs_info->delete_unused_bgs_mutex); goto done; } ret = btrfs_relocate_chunk(fs_info, chunk_offset); mutex_unlock(&fs_info->delete_unused_bgs_mutex); if (ret == -ENOSPC) { failed++; } else if (ret) { if (ret == -ETXTBSY) { btrfs_warn(fs_info, "could not shrink block group %llu due to active swapfile", chunk_offset); } goto done; } } while (key.offset-- > 0); if (failed && !retried) { failed = 0; retried = true; goto again; } else if (failed && retried) { ret = -ENOSPC; goto done; } /* Shrinking succeeded, else we would be at "done". */ trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto done; } mutex_lock(&fs_info->chunk_mutex); /* * We checked in the above loop all device extents that were already in * the device tree. However before we have updated the device's * total_bytes to the new size, we might have had chunk allocations that * have not complete yet (new block groups attached to transaction * handles), and therefore their device extents were not yet in the * device tree and we missed them in the loop above. So if we have any * pending chunk using a device extent that overlaps the device range * that we can not use anymore, commit the current transaction and * repeat the search on the device tree - this way we guarantee we will * not have chunks using device extents that end beyond 'new_size'. */ if (!checked_pending_chunks) { u64 start = new_size; u64 len = old_size - new_size; if (contains_pending_extent(trans->transaction, device, &start, len)) { mutex_unlock(&fs_info->chunk_mutex); checked_pending_chunks = true; failed = 0; retried = false; ret = btrfs_commit_transaction(trans); if (ret) goto done; goto again; } } btrfs_device_set_disk_total_bytes(device, new_size); if (list_empty(&device->resized_list)) list_add_tail(&device->resized_list, &fs_info->fs_devices->resized_devices); WARN_ON(diff > old_total); btrfs_set_super_total_bytes(super_copy, round_down(old_total - diff, fs_info->sectorsize)); mutex_unlock(&fs_info->chunk_mutex); /* Now btrfs_update_device() will change the on-disk size. */ ret = btrfs_update_device(trans, device); if (ret < 0) { btrfs_abort_transaction(trans, ret); btrfs_end_transaction(trans); } else { ret = btrfs_commit_transaction(trans); } done: btrfs_free_path(path); if (ret) { mutex_lock(&fs_info->chunk_mutex); btrfs_device_set_total_bytes(device, old_size); if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) device->fs_devices->total_rw_bytes += diff; atomic64_add(diff, &fs_info->free_chunk_space); mutex_unlock(&fs_info->chunk_mutex); } return ret; } static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key, struct btrfs_chunk *chunk, int item_size) { struct btrfs_super_block *super_copy = fs_info->super_copy; struct btrfs_disk_key disk_key; u32 array_size; u8 *ptr; mutex_lock(&fs_info->chunk_mutex); array_size = btrfs_super_sys_array_size(super_copy); if (array_size + item_size + sizeof(disk_key) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) { mutex_unlock(&fs_info->chunk_mutex); return -EFBIG; } ptr = super_copy->sys_chunk_array + array_size; btrfs_cpu_key_to_disk(&disk_key, key); memcpy(ptr, &disk_key, sizeof(disk_key)); ptr += sizeof(disk_key); memcpy(ptr, chunk, item_size); item_size += sizeof(disk_key); btrfs_set_super_sys_array_size(super_copy, array_size + item_size); mutex_unlock(&fs_info->chunk_mutex); return 0; } /* * sort the devices in descending order by max_avail, total_avail */ static int btrfs_cmp_device_info(const void *a, const void *b) { const struct btrfs_device_info *di_a = a; const struct btrfs_device_info *di_b = b; if (di_a->max_avail > di_b->max_avail) return -1; if (di_a->max_avail < di_b->max_avail) return 1; if (di_a->total_avail > di_b->total_avail) return -1; if (di_a->total_avail < di_b->total_avail) return 1; return 0; } static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type) { if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK)) return; btrfs_set_fs_incompat(info, RAID56); } #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \ - sizeof(struct btrfs_chunk)) \ / sizeof(struct btrfs_stripe) + 1) #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \ - 2 * sizeof(struct btrfs_disk_key) \ - 2 * sizeof(struct btrfs_chunk)) \ / sizeof(struct btrfs_stripe) + 1) static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 start, u64 type) { struct btrfs_fs_info *info = trans->fs_info; struct btrfs_fs_devices *fs_devices = info->fs_devices; struct btrfs_device *device; struct map_lookup *map = NULL; struct extent_map_tree *em_tree; struct extent_map *em; struct btrfs_device_info *devices_info = NULL; u64 total_avail; int num_stripes; /* total number of stripes to allocate */ int data_stripes; /* number of stripes that count for block group size */ int sub_stripes; /* sub_stripes info for map */ int dev_stripes; /* stripes per dev */ int devs_max; /* max devs to use */ int devs_min; /* min devs needed */ int devs_increment; /* ndevs has to be a multiple of this */ int ncopies; /* how many copies to data has */ int nparity; /* number of stripes worth of bytes to store parity information */ int ret; u64 max_stripe_size; u64 max_chunk_size; u64 stripe_size; u64 chunk_size; int ndevs; int i; int j; int index; BUG_ON(!alloc_profile_is_valid(type, 0)); if (list_empty(&fs_devices->alloc_list)) { if (btrfs_test_opt(info, ENOSPC_DEBUG)) btrfs_debug(info, "%s: no writable device", __func__); return -ENOSPC; } index = btrfs_bg_flags_to_raid_index(type); sub_stripes = btrfs_raid_array[index].sub_stripes; dev_stripes = btrfs_raid_array[index].dev_stripes; devs_max = btrfs_raid_array[index].devs_max; devs_min = btrfs_raid_array[index].devs_min; devs_increment = btrfs_raid_array[index].devs_increment; ncopies = btrfs_raid_array[index].ncopies; nparity = btrfs_raid_array[index].nparity; if (type & BTRFS_BLOCK_GROUP_DATA) { max_stripe_size = SZ_1G; max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE; if (!devs_max) devs_max = BTRFS_MAX_DEVS(info); } else if (type & BTRFS_BLOCK_GROUP_METADATA) { /* for larger filesystems, use larger metadata chunks */ if (fs_devices->total_rw_bytes > 50ULL * SZ_1G) max_stripe_size = SZ_1G; else max_stripe_size = SZ_256M; max_chunk_size = max_stripe_size; if (!devs_max) devs_max = BTRFS_MAX_DEVS(info); } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) { max_stripe_size = SZ_32M; max_chunk_size = 2 * max_stripe_size; if (!devs_max) devs_max = BTRFS_MAX_DEVS_SYS_CHUNK; } else { btrfs_err(info, "invalid chunk type 0x%llx requested", type); BUG_ON(1); } /* We don't want a chunk larger than 10% of writable space */ max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1), max_chunk_size); devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info), GFP_NOFS); if (!devices_info) return -ENOMEM; /* * in the first pass through the devices list, we gather information * about the available holes on each device. */ ndevs = 0; list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) { u64 max_avail; u64 dev_offset; if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { WARN(1, KERN_ERR "BTRFS: read-only device in alloc_list\n"); continue; } if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) || test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) continue; if (device->total_bytes > device->bytes_used) total_avail = device->total_bytes - device->bytes_used; else total_avail = 0; /* If there is no space on this device, skip it. */ if (total_avail == 0) continue; ret = find_free_dev_extent(trans, device, max_stripe_size * dev_stripes, &dev_offset, &max_avail); if (ret && ret != -ENOSPC) goto error; if (ret == 0) max_avail = max_stripe_size * dev_stripes; if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) { if (btrfs_test_opt(info, ENOSPC_DEBUG)) btrfs_debug(info, "%s: devid %llu has no free space, have=%llu want=%u", __func__, device->devid, max_avail, BTRFS_STRIPE_LEN * dev_stripes); continue; } if (ndevs == fs_devices->rw_devices) { WARN(1, "%s: found more than %llu devices\n", __func__, fs_devices->rw_devices); break; } devices_info[ndevs].dev_offset = dev_offset; devices_info[ndevs].max_avail = max_avail; devices_info[ndevs].total_avail = total_avail; devices_info[ndevs].dev = device; ++ndevs; } /* * now sort the devices by hole size / available space */ sort(devices_info, ndevs, sizeof(struct btrfs_device_info), btrfs_cmp_device_info, NULL); /* round down to number of usable stripes */ ndevs = round_down(ndevs, devs_increment); if (ndevs < devs_min) { ret = -ENOSPC; if (btrfs_test_opt(info, ENOSPC_DEBUG)) { btrfs_debug(info, "%s: not enough devices with free space: have=%d minimum required=%d", __func__, ndevs, devs_min); } goto error; } ndevs = min(ndevs, devs_max); /* * The primary goal is to maximize the number of stripes, so use as * many devices as possible, even if the stripes are not maximum sized. * * The DUP profile stores more than one stripe per device, the * max_avail is the total size so we have to adjust. */ stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes); num_stripes = ndevs * dev_stripes; /* * this will have to be fixed for RAID1 and RAID10 over * more drives */ data_stripes = (num_stripes - nparity) / ncopies; /* * Use the number of data stripes to figure out how big this chunk * is really going to be in terms of logical address space, * and compare that answer with the max chunk size. If it's higher, * we try to reduce stripe_size. */ if (stripe_size * data_stripes > max_chunk_size) { /* * Reduce stripe_size, round it up to a 16MB boundary again and * then use it, unless it ends up being even bigger than the * previous value we had already. */ stripe_size = min(round_up(div_u64(max_chunk_size, data_stripes), SZ_16M), stripe_size); } /* align to BTRFS_STRIPE_LEN */ stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN); map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS); if (!map) { ret = -ENOMEM; goto error; } map->num_stripes = num_stripes; for (i = 0; i < ndevs; ++i) { for (j = 0; j < dev_stripes; ++j) { int s = i * dev_stripes + j; map->stripes[s].dev = devices_info[i].dev; map->stripes[s].physical = devices_info[i].dev_offset + j * stripe_size; } } map->stripe_len = BTRFS_STRIPE_LEN; map->io_align = BTRFS_STRIPE_LEN; map->io_width = BTRFS_STRIPE_LEN; map->type = type; map->sub_stripes = sub_stripes; chunk_size = stripe_size * data_stripes; trace_btrfs_chunk_alloc(info, map, start, chunk_size); em = alloc_extent_map(); if (!em) { kfree(map); ret = -ENOMEM; goto error; } set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags); em->map_lookup = map; em->start = start; em->len = chunk_size; em->block_start = 0; em->block_len = em->len; em->orig_block_len = stripe_size; em_tree = &info->mapping_tree.map_tree; write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em, 0); if (ret) { write_unlock(&em_tree->lock); free_extent_map(em); goto error; } list_add_tail(&em->list, &trans->transaction->pending_chunks); refcount_inc(&em->refs); write_unlock(&em_tree->lock); ret = btrfs_make_block_group(trans, 0, type, start, chunk_size); if (ret) goto error_del_extent; for (i = 0; i < map->num_stripes; i++) btrfs_device_set_bytes_used(map->stripes[i].dev, map->stripes[i].dev->bytes_used + stripe_size); atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space); free_extent_map(em); check_raid56_incompat_flag(info, type); kfree(devices_info); return 0; error_del_extent: write_lock(&em_tree->lock); remove_extent_mapping(em_tree, em); write_unlock(&em_tree->lock); /* One for our allocation */ free_extent_map(em); /* One for the tree reference */ free_extent_map(em); /* One for the pending_chunks list reference */ free_extent_map(em); error: kfree(devices_info); return ret; } int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans, u64 chunk_offset, u64 chunk_size) { struct btrfs_fs_info *fs_info = trans->fs_info; struct btrfs_root *extent_root = fs_info->extent_root; struct btrfs_root *chunk_root = fs_info->chunk_root; struct btrfs_key key; struct btrfs_device *device; struct btrfs_chunk *chunk; struct btrfs_stripe *stripe; struct extent_map *em; struct map_lookup *map; size_t item_size; u64 dev_offset; u64 stripe_size; int i = 0; int ret = 0; em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size); if (IS_ERR(em)) return PTR_ERR(em); map = em->map_lookup; item_size = btrfs_chunk_item_size(map->num_stripes); stripe_size = em->orig_block_len; chunk = kzalloc(item_size, GFP_NOFS); if (!chunk) { ret = -ENOMEM; goto out; } /* * Take the device list mutex to prevent races with the final phase of * a device replace operation that replaces the device object associated * with the map's stripes, because the device object's id can change * at any time during that final phase of the device replace operation * (dev-replace.c:btrfs_dev_replace_finishing()). */ mutex_lock(&fs_info->fs_devices->device_list_mutex); for (i = 0; i < map->num_stripes; i++) { device = map->stripes[i].dev; dev_offset = map->stripes[i].physical; ret = btrfs_update_device(trans, device); if (ret) break; ret = btrfs_alloc_dev_extent(trans, device, chunk_offset, dev_offset, stripe_size); if (ret) break; } if (ret) { mutex_unlock(&fs_info->fs_devices->device_list_mutex); goto out; } stripe = &chunk->stripe; for (i = 0; i < map->num_stripes; i++) { device = map->stripes[i].dev; dev_offset = map->stripes[i].physical; btrfs_set_stack_stripe_devid(stripe, device->devid); btrfs_set_stack_stripe_offset(stripe, dev_offset); memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE); stripe++; } mutex_unlock(&fs_info->fs_devices->device_list_mutex); btrfs_set_stack_chunk_length(chunk, chunk_size); btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid); btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len); btrfs_set_stack_chunk_type(chunk, map->type); btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes); btrfs_set_stack_chunk_io_align(chunk, map->stripe_len); btrfs_set_stack_chunk_io_width(chunk, map->stripe_len); btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize); btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes); key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; key.type = BTRFS_CHUNK_ITEM_KEY; key.offset = chunk_offset; ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size); if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) { /* * TODO: Cleanup of inserted chunk root in case of * failure. */ ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size); } out: kfree(chunk); free_extent_map(em); return ret; } /* * Chunk allocation falls into two parts. The first part does work * that makes the new allocated chunk usable, but does not do any operation * that modifies the chunk tree. The second part does the work that * requires modifying the chunk tree. This division is important for the * bootstrap process of adding storage to a seed btrfs. */ int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type) { u64 chunk_offset; lockdep_assert_held(&trans->fs_info->chunk_mutex); chunk_offset = find_next_chunk(trans->fs_info); return __btrfs_alloc_chunk(trans, chunk_offset, type); } static noinline int init_first_rw_device(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info) { u64 chunk_offset; u64 sys_chunk_offset; u64 alloc_profile; int ret; chunk_offset = find_next_chunk(fs_info); alloc_profile = btrfs_metadata_alloc_profile(fs_info); ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile); if (ret) return ret; sys_chunk_offset = find_next_chunk(fs_info); alloc_profile = btrfs_system_alloc_profile(fs_info); ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile); return ret; } static inline int btrfs_chunk_max_errors(struct map_lookup *map) { int max_errors; if (map->type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10 | BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_DUP)) { max_errors = 1; } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) { max_errors = 2; } else { max_errors = 0; } return max_errors; } int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset) { struct extent_map *em; struct map_lookup *map; int readonly = 0; int miss_ndevs = 0; int i; em = btrfs_get_chunk_map(fs_info, chunk_offset, 1); if (IS_ERR(em)) return 1; map = em->map_lookup; for (i = 0; i < map->num_stripes; i++) { if (test_bit(BTRFS_DEV_STATE_MISSING, &map->stripes[i].dev->dev_state)) { miss_ndevs++; continue; } if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &map->stripes[i].dev->dev_state)) { readonly = 1; goto end; } } /* * If the number of missing devices is larger than max errors, * we can not write the data into that chunk successfully, so * set it readonly. */ if (miss_ndevs > btrfs_chunk_max_errors(map)) readonly = 1; end: free_extent_map(em); return readonly; } void btrfs_mapping_init(struct btrfs_mapping_tree *tree) { extent_map_tree_init(&tree->map_tree); } void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree) { struct extent_map *em; while (1) { write_lock(&tree->map_tree.lock); em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1); if (em) remove_extent_mapping(&tree->map_tree, em); write_unlock(&tree->map_tree.lock); if (!em) break; /* once for us */ free_extent_map(em); /* once for the tree */ free_extent_map(em); } } int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len) { struct extent_map *em; struct map_lookup *map; int ret; em = btrfs_get_chunk_map(fs_info, logical, len); if (IS_ERR(em)) /* * We could return errors for these cases, but that could get * ugly and we'd probably do the same thing which is just not do * anything else and exit, so return 1 so the callers don't try * to use other copies. */ return 1; map = em->map_lookup; if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1)) ret = map->num_stripes; else if (map->type & BTRFS_BLOCK_GROUP_RAID10) ret = map->sub_stripes; else if (map->type & BTRFS_BLOCK_GROUP_RAID5) ret = 2; else if (map->type & BTRFS_BLOCK_GROUP_RAID6) /* * There could be two corrupted data stripes, we need * to loop retry in order to rebuild the correct data. * * Fail a stripe at a time on every retry except the * stripe under reconstruction. */ ret = map->num_stripes; else ret = 1; free_extent_map(em); down_read(&fs_info->dev_replace.rwsem); if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) && fs_info->dev_replace.tgtdev) ret++; up_read(&fs_info->dev_replace.rwsem); return ret; } unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info, u64 logical) { struct extent_map *em; struct map_lookup *map; unsigned long len = fs_info->sectorsize; em = btrfs_get_chunk_map(fs_info, logical, len); if (!WARN_ON(IS_ERR(em))) { map = em->map_lookup; if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) len = map->stripe_len * nr_data_stripes(map); free_extent_map(em); } return len; } int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len) { struct extent_map *em; struct map_lookup *map; int ret = 0; em = btrfs_get_chunk_map(fs_info, logical, len); if(!WARN_ON(IS_ERR(em))) { map = em->map_lookup; if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) ret = 1; free_extent_map(em); } return ret; } static int find_live_mirror(struct btrfs_fs_info *fs_info, struct map_lookup *map, int first, int dev_replace_is_ongoing) { int i; int num_stripes; int preferred_mirror; int tolerance; struct btrfs_device *srcdev; ASSERT((map->type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10))); if (map->type & BTRFS_BLOCK_GROUP_RAID10) num_stripes = map->sub_stripes; else num_stripes = map->num_stripes; preferred_mirror = first + current->pid % num_stripes; if (dev_replace_is_ongoing && fs_info->dev_replace.cont_reading_from_srcdev_mode == BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID) srcdev = fs_info->dev_replace.srcdev; else srcdev = NULL; /* * try to avoid the drive that is the source drive for a * dev-replace procedure, only choose it if no other non-missing * mirror is available */ for (tolerance = 0; tolerance < 2; tolerance++) { if (map->stripes[preferred_mirror].dev->bdev && (tolerance || map->stripes[preferred_mirror].dev != srcdev)) return preferred_mirror; for (i = first; i < first + num_stripes; i++) { if (map->stripes[i].dev->bdev && (tolerance || map->stripes[i].dev != srcdev)) return i; } } /* we couldn't find one that doesn't fail. Just return something * and the io error handling code will clean up eventually */ return preferred_mirror; } static inline int parity_smaller(u64 a, u64 b) { return a > b; } /* Bubble-sort the stripe set to put the parity/syndrome stripes last */ static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes) { struct btrfs_bio_stripe s; int i; u64 l; int again = 1; while (again) { again = 0; for (i = 0; i < num_stripes - 1; i++) { if (parity_smaller(bbio->raid_map[i], bbio->raid_map[i+1])) { s = bbio->stripes[i]; l = bbio->raid_map[i]; bbio->stripes[i] = bbio->stripes[i+1]; bbio->raid_map[i] = bbio->raid_map[i+1]; bbio->stripes[i+1] = s; bbio->raid_map[i+1] = l; again = 1; } } } } static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes) { struct btrfs_bio *bbio = kzalloc( /* the size of the btrfs_bio */ sizeof(struct btrfs_bio) + /* plus the variable array for the stripes */ sizeof(struct btrfs_bio_stripe) * (total_stripes) + /* plus the variable array for the tgt dev */ sizeof(int) * (real_stripes) + /* * plus the raid_map, which includes both the tgt dev * and the stripes */ sizeof(u64) * (total_stripes), GFP_NOFS|__GFP_NOFAIL); atomic_set(&bbio->error, 0); refcount_set(&bbio->refs, 1); return bbio; } void btrfs_get_bbio(struct btrfs_bio *bbio) { WARN_ON(!refcount_read(&bbio->refs)); refcount_inc(&bbio->refs); } void btrfs_put_bbio(struct btrfs_bio *bbio) { if (!bbio) return; if (refcount_dec_and_test(&bbio->refs)) kfree(bbio); } /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */ /* * Please note that, discard won't be sent to target device of device * replace. */ static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info, u64 logical, u64 length, struct btrfs_bio **bbio_ret) { struct extent_map *em; struct map_lookup *map; struct btrfs_bio *bbio; u64 offset; u64 stripe_nr; u64 stripe_nr_end; u64 stripe_end_offset; u64 stripe_cnt; u64 stripe_len; u64 stripe_offset; u64 num_stripes; u32 stripe_index; u32 factor = 0; u32 sub_stripes = 0; u64 stripes_per_dev = 0; u32 remaining_stripes = 0; u32 last_stripe = 0; int ret = 0; int i; /* discard always return a bbio */ ASSERT(bbio_ret); em = btrfs_get_chunk_map(fs_info, logical, length); if (IS_ERR(em)) return PTR_ERR(em); map = em->map_lookup; /* we don't discard raid56 yet */ if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { ret = -EOPNOTSUPP; goto out; } offset = logical - em->start; length = min_t(u64, em->len - offset, length); stripe_len = map->stripe_len; /* * stripe_nr counts the total number of stripes we have to stride * to get to this block */ stripe_nr = div64_u64(offset, stripe_len); /* stripe_offset is the offset of this block in its stripe */ stripe_offset = offset - stripe_nr * stripe_len; stripe_nr_end = round_up(offset + length, map->stripe_len); stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len); stripe_cnt = stripe_nr_end - stripe_nr; stripe_end_offset = stripe_nr_end * map->stripe_len - (offset + length); /* * after this, stripe_nr is the number of stripes on this * device we have to walk to find the data, and stripe_index is * the number of our device in the stripe array */ num_stripes = 1; stripe_index = 0; if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) { if (map->type & BTRFS_BLOCK_GROUP_RAID0) sub_stripes = 1; else sub_stripes = map->sub_stripes; factor = map->num_stripes / sub_stripes; num_stripes = min_t(u64, map->num_stripes, sub_stripes * stripe_cnt); stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index); stripe_index *= sub_stripes; stripes_per_dev = div_u64_rem(stripe_cnt, factor, &remaining_stripes); div_u64_rem(stripe_nr_end - 1, factor, &last_stripe); last_stripe *= sub_stripes; } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP)) { num_stripes = map->num_stripes; } else { stripe_nr = div_u64_rem(stripe_nr, map->num_stripes, &stripe_index); } bbio = alloc_btrfs_bio(num_stripes, 0); if (!bbio) { ret = -ENOMEM; goto out; } for (i = 0; i < num_stripes; i++) { bbio->stripes[i].physical = map->stripes[stripe_index].physical + stripe_offset + stripe_nr * map->stripe_len; bbio->stripes[i].dev = map->stripes[stripe_index].dev; if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) { bbio->stripes[i].length = stripes_per_dev * map->stripe_len; if (i / sub_stripes < remaining_stripes) bbio->stripes[i].length += map->stripe_len; /* * Special for the first stripe and * the last stripe: * * |-------|...|-------| * |----------| * off end_off */ if (i < sub_stripes) bbio->stripes[i].length -= stripe_offset; if (stripe_index >= last_stripe && stripe_index <= (last_stripe + sub_stripes - 1)) bbio->stripes[i].length -= stripe_end_offset; if (i == sub_stripes - 1) stripe_offset = 0; } else { bbio->stripes[i].length = length; } stripe_index++; if (stripe_index == map->num_stripes) { stripe_index = 0; stripe_nr++; } } *bbio_ret = bbio; bbio->map_type = map->type; bbio->num_stripes = num_stripes; out: free_extent_map(em); return ret; } /* * In dev-replace case, for repair case (that's the only case where the mirror * is selected explicitly when calling btrfs_map_block), blocks left of the * left cursor can also be read from the target drive. * * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the * array of stripes. * For READ, it also needs to be supported using the same mirror number. * * If the requested block is not left of the left cursor, EIO is returned. This * can happen because btrfs_num_copies() returns one more in the dev-replace * case. */ static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info, u64 logical, u64 length, u64 srcdev_devid, int *mirror_num, u64 *physical) { struct btrfs_bio *bbio = NULL; int num_stripes; int index_srcdev = 0; int found = 0; u64 physical_of_found = 0; int i; int ret = 0; ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical, &length, &bbio, 0, 0); if (ret) { ASSERT(bbio == NULL); return ret; } num_stripes = bbio->num_stripes; if (*mirror_num > num_stripes) { /* * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror, * that means that the requested area is not left of the left * cursor */ btrfs_put_bbio(bbio); return -EIO; } /* * process the rest of the function using the mirror_num of the source * drive. Therefore look it up first. At the end, patch the device * pointer to the one of the target drive. */ for (i = 0; i < num_stripes; i++) { if (bbio->stripes[i].dev->devid != srcdev_devid) continue; /* * In case of DUP, in order to keep it simple, only add the * mirror with the lowest physical address */ if (found && physical_of_found <= bbio->stripes[i].physical) continue; index_srcdev = i; found = 1; physical_of_found = bbio->stripes[i].physical; } btrfs_put_bbio(bbio); ASSERT(found); if (!found) return -EIO; *mirror_num = index_srcdev + 1; *physical = physical_of_found; return ret; } static void handle_ops_on_dev_replace(enum btrfs_map_op op, struct btrfs_bio **bbio_ret, struct btrfs_dev_replace *dev_replace, int *num_stripes_ret, int *max_errors_ret) { struct btrfs_bio *bbio = *bbio_ret; u64 srcdev_devid = dev_replace->srcdev->devid; int tgtdev_indexes = 0; int num_stripes = *num_stripes_ret; int max_errors = *max_errors_ret; int i; if (op == BTRFS_MAP_WRITE) { int index_where_to_add; /* * duplicate the write operations while the dev replace * procedure is running. Since the copying of the old disk to * the new disk takes place at run time while the filesystem is * mounted writable, the regular write operations to the old * disk have to be duplicated to go to the new disk as well. * * Note that device->missing is handled by the caller, and that * the write to the old disk is already set up in the stripes * array. */ index_where_to_add = num_stripes; for (i = 0; i < num_stripes; i++) { if (bbio->stripes[i].dev->devid == srcdev_devid) { /* write to new disk, too */ struct btrfs_bio_stripe *new = bbio->stripes + index_where_to_add; struct btrfs_bio_stripe *old = bbio->stripes + i; new->physical = old->physical; new->length = old->length; new->dev = dev_replace->tgtdev; bbio->tgtdev_map[i] = index_where_to_add; index_where_to_add++; max_errors++; tgtdev_indexes++; } } num_stripes = index_where_to_add; } else if (op == BTRFS_MAP_GET_READ_MIRRORS) { int index_srcdev = 0; int found = 0; u64 physical_of_found = 0; /* * During the dev-replace procedure, the target drive can also * be used to read data in case it is needed to repair a corrupt * block elsewhere. This is possible if the requested area is * left of the left cursor. In this area, the target drive is a * full copy of the source drive. */ for (i = 0; i < num_stripes; i++) { if (bbio->stripes[i].dev->devid == srcdev_devid) { /* * In case of DUP, in order to keep it simple, * only add the mirror with the lowest physical * address */ if (found && physical_of_found <= bbio->stripes[i].physical) continue; index_srcdev = i; found = 1; physical_of_found = bbio->stripes[i].physical; } } if (found) { struct btrfs_bio_stripe *tgtdev_stripe = bbio->stripes + num_stripes; tgtdev_stripe->physical = physical_of_found; tgtdev_stripe->length = bbio->stripes[index_srcdev].length; tgtdev_stripe->dev = dev_replace->tgtdev; bbio->tgtdev_map[index_srcdev] = num_stripes; tgtdev_indexes++; num_stripes++; } } *num_stripes_ret = num_stripes; *max_errors_ret = max_errors; bbio->num_tgtdevs = tgtdev_indexes; *bbio_ret = bbio; } static bool need_full_stripe(enum btrfs_map_op op) { return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS); } static int __btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op, u64 logical, u64 *length, struct btrfs_bio **bbio_ret, int mirror_num, int need_raid_map) { struct extent_map *em; struct map_lookup *map; u64 offset; u64 stripe_offset; u64 stripe_nr; u64 stripe_len; u32 stripe_index; int i; int ret = 0; int num_stripes; int max_errors = 0; int tgtdev_indexes = 0; struct btrfs_bio *bbio = NULL; struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace; int dev_replace_is_ongoing = 0; int num_alloc_stripes; int patch_the_first_stripe_for_dev_replace = 0; u64 physical_to_patch_in_first_stripe = 0; u64 raid56_full_stripe_start = (u64)-1; if (op == BTRFS_MAP_DISCARD) return __btrfs_map_block_for_discard(fs_info, logical, *length, bbio_ret); em = btrfs_get_chunk_map(fs_info, logical, *length); if (IS_ERR(em)) return PTR_ERR(em); map = em->map_lookup; offset = logical - em->start; stripe_len = map->stripe_len; stripe_nr = offset; /* * stripe_nr counts the total number of stripes we have to stride * to get to this block */ stripe_nr = div64_u64(stripe_nr, stripe_len); stripe_offset = stripe_nr * stripe_len; if (offset < stripe_offset) { btrfs_crit(fs_info, "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu", stripe_offset, offset, em->start, logical, stripe_len); free_extent_map(em); return -EINVAL; } /* stripe_offset is the offset of this block in its stripe*/ stripe_offset = offset - stripe_offset; /* if we're here for raid56, we need to know the stripe aligned start */ if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { unsigned long full_stripe_len = stripe_len * nr_data_stripes(map); raid56_full_stripe_start = offset; /* allow a write of a full stripe, but make sure we don't * allow straddling of stripes */ raid56_full_stripe_start = div64_u64(raid56_full_stripe_start, full_stripe_len); raid56_full_stripe_start *= full_stripe_len; } if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) { u64 max_len; /* For writes to RAID[56], allow a full stripeset across all disks. For other RAID types and for RAID[56] reads, just allow a single stripe (on a single disk). */ if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && (op == BTRFS_MAP_WRITE)) { max_len = stripe_len * nr_data_stripes(map) - (offset - raid56_full_stripe_start); } else { /* we limit the length of each bio to what fits in a stripe */ max_len = stripe_len - stripe_offset; } *length = min_t(u64, em->len - offset, max_len); } else { *length = em->len - offset; } /* * This is for when we're called from btrfs_bio_fits_in_stripe and all * it cares about is the length */ if (!bbio_ret) goto out; down_read(&dev_replace->rwsem); dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace); /* * Hold the semaphore for read during the whole operation, write is * requested at commit time but must wait. */ if (!dev_replace_is_ongoing) up_read(&dev_replace->rwsem); if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 && !need_full_stripe(op) && dev_replace->tgtdev != NULL) { ret = get_extra_mirror_from_replace(fs_info, logical, *length, dev_replace->srcdev->devid, &mirror_num, &physical_to_patch_in_first_stripe); if (ret) goto out; else patch_the_first_stripe_for_dev_replace = 1; } else if (mirror_num > map->num_stripes) { mirror_num = 0; } num_stripes = 1; stripe_index = 0; if (map->type & BTRFS_BLOCK_GROUP_RAID0) { stripe_nr = div_u64_rem(stripe_nr, map->num_stripes, &stripe_index); if (!need_full_stripe(op)) mirror_num = 1; } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) { if (need_full_stripe(op)) num_stripes = map->num_stripes; else if (mirror_num) stripe_index = mirror_num - 1; else { stripe_index = find_live_mirror(fs_info, map, 0, dev_replace_is_ongoing); mirror_num = stripe_index + 1; } } else if (map->type & BTRFS_BLOCK_GROUP_DUP) { if (need_full_stripe(op)) { num_stripes = map->num_stripes; } else if (mirror_num) { stripe_index = mirror_num - 1; } else { mirror_num = 1; } } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) { u32 factor = map->num_stripes / map->sub_stripes; stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index); stripe_index *= map->sub_stripes; if (need_full_stripe(op)) num_stripes = map->sub_stripes; else if (mirror_num) stripe_index += mirror_num - 1; else { int old_stripe_index = stripe_index; stripe_index = find_live_mirror(fs_info, map, stripe_index, dev_replace_is_ongoing); mirror_num = stripe_index - old_stripe_index + 1; } } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) { /* push stripe_nr back to the start of the full stripe */ stripe_nr = div64_u64(raid56_full_stripe_start, stripe_len * nr_data_stripes(map)); /* RAID[56] write or recovery. Return all stripes */ num_stripes = map->num_stripes; max_errors = nr_parity_stripes(map); *length = map->stripe_len; stripe_index = 0; stripe_offset = 0; } else { /* * Mirror #0 or #1 means the original data block. * Mirror #2 is RAID5 parity block. * Mirror #3 is RAID6 Q block. */ stripe_nr = div_u64_rem(stripe_nr, nr_data_stripes(map), &stripe_index); if (mirror_num > 1) stripe_index = nr_data_stripes(map) + mirror_num - 2; /* We distribute the parity blocks across stripes */ div_u64_rem(stripe_nr + stripe_index, map->num_stripes, &stripe_index); if (!need_full_stripe(op) && mirror_num <= 1) mirror_num = 1; } } else { /* * after this, stripe_nr is the number of stripes on this * device we have to walk to find the data, and stripe_index is * the number of our device in the stripe array */ stripe_nr = div_u64_rem(stripe_nr, map->num_stripes, &stripe_index); mirror_num = stripe_index + 1; } if (stripe_index >= map->num_stripes) { btrfs_crit(fs_info, "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u", stripe_index, map->num_stripes); ret = -EINVAL; goto out; } num_alloc_stripes = num_stripes; if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) { if (op == BTRFS_MAP_WRITE) num_alloc_stripes <<= 1; if (op == BTRFS_MAP_GET_READ_MIRRORS) num_alloc_stripes++; tgtdev_indexes = num_stripes; } bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes); if (!bbio) { ret = -ENOMEM; goto out; } if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes); /* build raid_map */ if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map && (need_full_stripe(op) || mirror_num > 1)) { u64 tmp; unsigned rot; bbio->raid_map = (u64 *)((void *)bbio->stripes + sizeof(struct btrfs_bio_stripe) * num_alloc_stripes + sizeof(int) * tgtdev_indexes); /* Work out the disk rotation on this stripe-set */ div_u64_rem(stripe_nr, num_stripes, &rot); /* Fill in the logical address of each stripe */ tmp = stripe_nr * nr_data_stripes(map); for (i = 0; i < nr_data_stripes(map); i++) bbio->raid_map[(i+rot) % num_stripes] = em->start + (tmp + i) * map->stripe_len; bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE; if (map->type & BTRFS_BLOCK_GROUP_RAID6) bbio->raid_map[(i+rot+1) % num_stripes] = RAID6_Q_STRIPE; } for (i = 0; i < num_stripes; i++) { bbio->stripes[i].physical = map->stripes[stripe_index].physical + stripe_offset + stripe_nr * map->stripe_len; bbio->stripes[i].dev = map->stripes[stripe_index].dev; stripe_index++; } if (need_full_stripe(op)) max_errors = btrfs_chunk_max_errors(map); if (bbio->raid_map) sort_parity_stripes(bbio, num_stripes); if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL && need_full_stripe(op)) { handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes, &max_errors); } *bbio_ret = bbio; bbio->map_type = map->type; bbio->num_stripes = num_stripes; bbio->max_errors = max_errors; bbio->mirror_num = mirror_num; /* * this is the case that REQ_READ && dev_replace_is_ongoing && * mirror_num == num_stripes + 1 && dev_replace target drive is * available as a mirror */ if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) { WARN_ON(num_stripes > 1); bbio->stripes[0].dev = dev_replace->tgtdev; bbio->stripes[0].physical = physical_to_patch_in_first_stripe; bbio->mirror_num = map->num_stripes + 1; } out: if (dev_replace_is_ongoing) { lockdep_assert_held(&dev_replace->rwsem); /* Unlock and let waiting writers proceed */ up_read(&dev_replace->rwsem); } free_extent_map(em); return ret; } int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op, u64 logical, u64 *length, struct btrfs_bio **bbio_ret, int mirror_num) { return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, mirror_num, 0); } /* For Scrub/replace */ int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op, u64 logical, u64 *length, struct btrfs_bio **bbio_ret) { return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1); } int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start, u64 physical, u64 **logical, int *naddrs, int *stripe_len) { struct extent_map *em; struct map_lookup *map; u64 *buf; u64 bytenr; u64 length; u64 stripe_nr; u64 rmap_len; int i, j, nr = 0; em = btrfs_get_chunk_map(fs_info, chunk_start, 1); if (IS_ERR(em)) return -EIO; map = em->map_lookup; length = em->len; rmap_len = map->stripe_len; if (map->type & BTRFS_BLOCK_GROUP_RAID10) length = div_u64(length, map->num_stripes / map->sub_stripes); else if (map->type & BTRFS_BLOCK_GROUP_RAID0) length = div_u64(length, map->num_stripes); else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { length = div_u64(length, nr_data_stripes(map)); rmap_len = map->stripe_len * nr_data_stripes(map); } buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS); BUG_ON(!buf); /* -ENOMEM */ for (i = 0; i < map->num_stripes; i++) { if (map->stripes[i].physical > physical || map->stripes[i].physical + length <= physical) continue; stripe_nr = physical - map->stripes[i].physical; stripe_nr = div64_u64(stripe_nr, map->stripe_len); if (map->type & BTRFS_BLOCK_GROUP_RAID10) { stripe_nr = stripe_nr * map->num_stripes + i; stripe_nr = div_u64(stripe_nr, map->sub_stripes); } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) { stripe_nr = stripe_nr * map->num_stripes + i; } /* else if RAID[56], multiply by nr_data_stripes(). * Alternatively, just use rmap_len below instead of * map->stripe_len */ bytenr = chunk_start + stripe_nr * rmap_len; WARN_ON(nr >= map->num_stripes); for (j = 0; j < nr; j++) { if (buf[j] == bytenr) break; } if (j == nr) { WARN_ON(nr >= map->num_stripes); buf[nr++] = bytenr; } } *logical = buf; *naddrs = nr; *stripe_len = rmap_len; free_extent_map(em); return 0; } static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio) { bio->bi_private = bbio->private; bio->bi_end_io = bbio->end_io; bio_endio(bio); btrfs_put_bbio(bbio); } static void btrfs_end_bio(struct bio *bio) { struct btrfs_bio *bbio = bio->bi_private; int is_orig_bio = 0; if (bio->bi_status) { atomic_inc(&bbio->error); if (bio->bi_status == BLK_STS_IOERR || bio->bi_status == BLK_STS_TARGET) { unsigned int stripe_index = btrfs_io_bio(bio)->stripe_index; struct btrfs_device *dev; BUG_ON(stripe_index >= bbio->num_stripes); dev = bbio->stripes[stripe_index].dev; if (dev->bdev) { if (bio_op(bio) == REQ_OP_WRITE) btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS); else btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_READ_ERRS); if (bio->bi_opf & REQ_PREFLUSH) btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_FLUSH_ERRS); } } } if (bio == bbio->orig_bio) is_orig_bio = 1; btrfs_bio_counter_dec(bbio->fs_info); if (atomic_dec_and_test(&bbio->stripes_pending)) { if (!is_orig_bio) { bio_put(bio); bio = bbio->orig_bio; } btrfs_io_bio(bio)->mirror_num = bbio->mirror_num; /* only send an error to the higher layers if it is * beyond the tolerance of the btrfs bio */ if (atomic_read(&bbio->error) > bbio->max_errors) { bio->bi_status = BLK_STS_IOERR; } else { /* * this bio is actually up to date, we didn't * go over the max number of errors */ bio->bi_status = BLK_STS_OK; } btrfs_end_bbio(bbio, bio); } else if (!is_orig_bio) { bio_put(bio); } } /* * see run_scheduled_bios for a description of why bios are collected for * async submit. * * This will add one bio to the pending list for a device and make sure * the work struct is scheduled. */ static noinline void btrfs_schedule_bio(struct btrfs_device *device, struct bio *bio) { struct btrfs_fs_info *fs_info = device->fs_info; int should_queue = 1; struct btrfs_pending_bios *pending_bios; /* don't bother with additional async steps for reads, right now */ if (bio_op(bio) == REQ_OP_READ) { btrfsic_submit_bio(bio); return; } WARN_ON(bio->bi_next); bio->bi_next = NULL; spin_lock(&device->io_lock); if (op_is_sync(bio->bi_opf)) pending_bios = &device->pending_sync_bios; else pending_bios = &device->pending_bios; if (pending_bios->tail) pending_bios->tail->bi_next = bio; pending_bios->tail = bio; if (!pending_bios->head) pending_bios->head = bio; if (device->running_pending) should_queue = 0; spin_unlock(&device->io_lock); if (should_queue) btrfs_queue_work(fs_info->submit_workers, &device->work); } static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio, u64 physical, int dev_nr, int async) { struct btrfs_device *dev = bbio->stripes[dev_nr].dev; struct btrfs_fs_info *fs_info = bbio->fs_info; bio->bi_private = bbio; btrfs_io_bio(bio)->stripe_index = dev_nr; bio->bi_end_io = btrfs_end_bio; bio->bi_iter.bi_sector = physical >> 9; btrfs_debug_in_rcu(fs_info, "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u", bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector, (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid, bio->bi_iter.bi_size); bio_set_dev(bio, dev->bdev); btrfs_bio_counter_inc_noblocked(fs_info); if (async) btrfs_schedule_bio(dev, bio); else btrfsic_submit_bio(bio); } static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical) { atomic_inc(&bbio->error); if (atomic_dec_and_test(&bbio->stripes_pending)) { /* Should be the original bio. */ WARN_ON(bio != bbio->orig_bio); btrfs_io_bio(bio)->mirror_num = bbio->mirror_num; bio->bi_iter.bi_sector = logical >> 9; if (atomic_read(&bbio->error) > bbio->max_errors) bio->bi_status = BLK_STS_IOERR; else bio->bi_status = BLK_STS_OK; btrfs_end_bbio(bbio, bio); } } blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio, int mirror_num, int async_submit) { struct btrfs_device *dev; struct bio *first_bio = bio; u64 logical = (u64)bio->bi_iter.bi_sector << 9; u64 length = 0; u64 map_length; int ret; int dev_nr; int total_devs; struct btrfs_bio *bbio = NULL; length = bio->bi_iter.bi_size; map_length = length; btrfs_bio_counter_inc_blocked(fs_info); ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length, &bbio, mirror_num, 1); if (ret) { btrfs_bio_counter_dec(fs_info); return errno_to_blk_status(ret); } total_devs = bbio->num_stripes; bbio->orig_bio = first_bio; bbio->private = first_bio->bi_private; bbio->end_io = first_bio->bi_end_io; bbio->fs_info = fs_info; atomic_set(&bbio->stripes_pending, bbio->num_stripes); if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) && ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) { /* In this case, map_length has been set to the length of a single stripe; not the whole write */ if (bio_op(bio) == REQ_OP_WRITE) { ret = raid56_parity_write(fs_info, bio, bbio, map_length); } else { ret = raid56_parity_recover(fs_info, bio, bbio, map_length, mirror_num, 1); } btrfs_bio_counter_dec(fs_info); return errno_to_blk_status(ret); } if (map_length < length) { btrfs_crit(fs_info, "mapping failed logical %llu bio len %llu len %llu", logical, length, map_length); BUG(); } for (dev_nr = 0; dev_nr < total_devs; dev_nr++) { dev = bbio->stripes[dev_nr].dev; if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) || (bio_op(first_bio) == REQ_OP_WRITE && !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) { bbio_error(bbio, first_bio, logical); continue; } if (dev_nr < total_devs - 1) bio = btrfs_bio_clone(first_bio); else bio = first_bio; submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical, dev_nr, async_submit); } btrfs_bio_counter_dec(fs_info); return BLK_STS_OK; } struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices, u64 devid, u8 *uuid, u8 *fsid) { struct btrfs_device *device; while (fs_devices) { if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) { device = find_device(fs_devices, devid, uuid); if (device) return device; } fs_devices = fs_devices->seed; } return NULL; } static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices, u64 devid, u8 *dev_uuid) { struct btrfs_device *device; device = btrfs_alloc_device(NULL, &devid, dev_uuid); if (IS_ERR(device)) return device; list_add(&device->dev_list, &fs_devices->devices); device->fs_devices = fs_devices; fs_devices->num_devices++; set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); fs_devices->missing_devices++; return device; } /** * btrfs_alloc_device - allocate struct btrfs_device * @fs_info: used only for generating a new devid, can be NULL if * devid is provided (i.e. @devid != NULL). * @devid: a pointer to devid for this device. If NULL a new devid * is generated. * @uuid: a pointer to UUID for this device. If NULL a new UUID * is generated. * * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR() * on error. Returned struct is not linked onto any lists and must be * destroyed with btrfs_free_device. */ struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info, const u64 *devid, const u8 *uuid) { struct btrfs_device *dev; u64 tmp; if (WARN_ON(!devid && !fs_info)) return ERR_PTR(-EINVAL); dev = __alloc_device(); if (IS_ERR(dev)) return dev; if (devid) tmp = *devid; else { int ret; ret = find_next_devid(fs_info, &tmp); if (ret) { btrfs_free_device(dev); return ERR_PTR(ret); } } dev->devid = tmp; if (uuid) memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE); else generate_random_uuid(dev->uuid); btrfs_init_work(&dev->work, btrfs_submit_helper, pending_bios_fn, NULL, NULL); return dev; } /* Return -EIO if any error, otherwise return 0. */ static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info, struct extent_buffer *leaf, struct btrfs_chunk *chunk, u64 logical) { u64 length; u64 stripe_len; u16 num_stripes; u16 sub_stripes; u64 type; u64 features; bool mixed = false; length = btrfs_chunk_length(leaf, chunk); stripe_len = btrfs_chunk_stripe_len(leaf, chunk); num_stripes = btrfs_chunk_num_stripes(leaf, chunk); sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk); type = btrfs_chunk_type(leaf, chunk); if (!num_stripes) { btrfs_err(fs_info, "invalid chunk num_stripes: %u", num_stripes); return -EIO; } if (!IS_ALIGNED(logical, fs_info->sectorsize)) { btrfs_err(fs_info, "invalid chunk logical %llu", logical); return -EIO; } if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) { btrfs_err(fs_info, "invalid chunk sectorsize %u", btrfs_chunk_sector_size(leaf, chunk)); return -EIO; } if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) { btrfs_err(fs_info, "invalid chunk length %llu", length); return -EIO; } if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) { btrfs_err(fs_info, "invalid chunk stripe length: %llu", stripe_len); return -EIO; } if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) & type) { btrfs_err(fs_info, "unrecognized chunk type: %llu", ~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) & btrfs_chunk_type(leaf, chunk)); return -EIO; } if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) { btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type); return -EIO; } if ((type & BTRFS_BLOCK_GROUP_SYSTEM) && (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) { btrfs_err(fs_info, "system chunk with data or metadata type: 0x%llx", type); return -EIO; } features = btrfs_super_incompat_flags(fs_info->super_copy); if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) mixed = true; if (!mixed) { if ((type & BTRFS_BLOCK_GROUP_METADATA) && (type & BTRFS_BLOCK_GROUP_DATA)) { btrfs_err(fs_info, "mixed chunk type in non-mixed mode: 0x%llx", type); return -EIO; } } if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) || (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) || (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) || (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) || (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) || ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 && num_stripes != 1)) { btrfs_err(fs_info, "invalid num_stripes:sub_stripes %u:%u for profile %llu", num_stripes, sub_stripes, type & BTRFS_BLOCK_GROUP_PROFILE_MASK); return -EIO; } return 0; } static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info, u64 devid, u8 *uuid, bool error) { if (error) btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing", devid, uuid); else btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing", devid, uuid); } static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key, struct extent_buffer *leaf, struct btrfs_chunk *chunk) { struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree; struct map_lookup *map; struct extent_map *em; u64 logical; u64 length; u64 devid; u8 uuid[BTRFS_UUID_SIZE]; int num_stripes; int ret; int i; logical = key->offset; length = btrfs_chunk_length(leaf, chunk); num_stripes = btrfs_chunk_num_stripes(leaf, chunk); ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical); if (ret) return ret; read_lock(&map_tree->map_tree.lock); em = lookup_extent_mapping(&map_tree->map_tree, logical, 1); read_unlock(&map_tree->map_tree.lock); /* already mapped? */ if (em && em->start <= logical && em->start + em->len > logical) { free_extent_map(em); return 0; } else if (em) { free_extent_map(em); } em = alloc_extent_map(); if (!em) return -ENOMEM; map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS); if (!map) { free_extent_map(em); return -ENOMEM; } set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags); em->map_lookup = map; em->start = logical; em->len = length; em->orig_start = 0; em->block_start = 0; em->block_len = em->len; map->num_stripes = num_stripes; map->io_width = btrfs_chunk_io_width(leaf, chunk); map->io_align = btrfs_chunk_io_align(leaf, chunk); map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk); map->type = btrfs_chunk_type(leaf, chunk); map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk); map->verified_stripes = 0; for (i = 0; i < num_stripes; i++) { map->stripes[i].physical = btrfs_stripe_offset_nr(leaf, chunk, i); devid = btrfs_stripe_devid_nr(leaf, chunk, i); read_extent_buffer(leaf, uuid, (unsigned long) btrfs_stripe_dev_uuid_nr(chunk, i), BTRFS_UUID_SIZE); map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, devid, uuid, NULL); if (!map->stripes[i].dev && !btrfs_test_opt(fs_info, DEGRADED)) { free_extent_map(em); btrfs_report_missing_device(fs_info, devid, uuid, true); return -ENOENT; } if (!map->stripes[i].dev) { map->stripes[i].dev = add_missing_dev(fs_info->fs_devices, devid, uuid); if (IS_ERR(map->stripes[i].dev)) { free_extent_map(em); btrfs_err(fs_info, "failed to init missing dev %llu: %ld", devid, PTR_ERR(map->stripes[i].dev)); return PTR_ERR(map->stripes[i].dev); } btrfs_report_missing_device(fs_info, devid, uuid, false); } set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &(map->stripes[i].dev->dev_state)); } write_lock(&map_tree->map_tree.lock); ret = add_extent_mapping(&map_tree->map_tree, em, 0); write_unlock(&map_tree->map_tree.lock); if (ret < 0) { btrfs_err(fs_info, "failed to add chunk map, start=%llu len=%llu: %d", em->start, em->len, ret); } free_extent_map(em); return ret; } static void fill_device_from_item(struct extent_buffer *leaf, struct btrfs_dev_item *dev_item, struct btrfs_device *device) { unsigned long ptr; device->devid = btrfs_device_id(leaf, dev_item); device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item); device->total_bytes = device->disk_total_bytes; device->commit_total_bytes = device->disk_total_bytes; device->bytes_used = btrfs_device_bytes_used(leaf, dev_item); device->commit_bytes_used = device->bytes_used; device->type = btrfs_device_type(leaf, dev_item); device->io_align = btrfs_device_io_align(leaf, dev_item); device->io_width = btrfs_device_io_width(leaf, dev_item); device->sector_size = btrfs_device_sector_size(leaf, dev_item); WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID); clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state); ptr = btrfs_device_uuid(dev_item); read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE); } static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info, u8 *fsid) { struct btrfs_fs_devices *fs_devices; int ret; lockdep_assert_held(&uuid_mutex); ASSERT(fsid); fs_devices = fs_info->fs_devices->seed; while (fs_devices) { if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE)) return fs_devices; fs_devices = fs_devices->seed; } fs_devices = find_fsid(fsid, NULL); if (!fs_devices) { if (!btrfs_test_opt(fs_info, DEGRADED)) return ERR_PTR(-ENOENT); fs_devices = alloc_fs_devices(fsid, NULL); if (IS_ERR(fs_devices)) return fs_devices; fs_devices->seeding = 1; fs_devices->opened = 1; return fs_devices; } fs_devices = clone_fs_devices(fs_devices); if (IS_ERR(fs_devices)) return fs_devices; ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder); if (ret) { free_fs_devices(fs_devices); fs_devices = ERR_PTR(ret); goto out; } if (!fs_devices->seeding) { close_fs_devices(fs_devices); free_fs_devices(fs_devices); fs_devices = ERR_PTR(-EINVAL); goto out; } fs_devices->seed = fs_info->fs_devices->seed; fs_info->fs_devices->seed = fs_devices; out: return fs_devices; } static int read_one_dev(struct btrfs_fs_info *fs_info, struct extent_buffer *leaf, struct btrfs_dev_item *dev_item) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct btrfs_device *device; u64 devid; int ret; u8 fs_uuid[BTRFS_FSID_SIZE]; u8 dev_uuid[BTRFS_UUID_SIZE]; devid = btrfs_device_id(leaf, dev_item); read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item), BTRFS_UUID_SIZE); read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item), BTRFS_FSID_SIZE); if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) { fs_devices = open_seed_devices(fs_info, fs_uuid); if (IS_ERR(fs_devices)) return PTR_ERR(fs_devices); } device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid, fs_uuid); if (!device) { if (!btrfs_test_opt(fs_info, DEGRADED)) { btrfs_report_missing_device(fs_info, devid, dev_uuid, true); return -ENOENT; } device = add_missing_dev(fs_devices, devid, dev_uuid); if (IS_ERR(device)) { btrfs_err(fs_info, "failed to add missing dev %llu: %ld", devid, PTR_ERR(device)); return PTR_ERR(device); } btrfs_report_missing_device(fs_info, devid, dev_uuid, false); } else { if (!device->bdev) { if (!btrfs_test_opt(fs_info, DEGRADED)) { btrfs_report_missing_device(fs_info, devid, dev_uuid, true); return -ENOENT; } btrfs_report_missing_device(fs_info, devid, dev_uuid, false); } if (!device->bdev && !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) { /* * this happens when a device that was properly setup * in the device info lists suddenly goes bad. * device->bdev is NULL, and so we have to set * device->missing to one here */ device->fs_devices->missing_devices++; set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); } /* Move the device to its own fs_devices */ if (device->fs_devices != fs_devices) { ASSERT(test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)); list_move(&device->dev_list, &fs_devices->devices); device->fs_devices->num_devices--; fs_devices->num_devices++; device->fs_devices->missing_devices--; fs_devices->missing_devices++; device->fs_devices = fs_devices; } } if (device->fs_devices != fs_info->fs_devices) { BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)); if (device->generation != btrfs_device_generation(leaf, dev_item)) return -EINVAL; } fill_device_from_item(leaf, dev_item, device); set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { device->fs_devices->total_rw_bytes += device->total_bytes; atomic64_add(device->total_bytes - device->bytes_used, &fs_info->free_chunk_space); } ret = 0; return ret; } int btrfs_read_sys_array(struct btrfs_fs_info *fs_info) { struct btrfs_root *root = fs_info->tree_root; struct btrfs_super_block *super_copy = fs_info->super_copy; struct extent_buffer *sb; struct btrfs_disk_key *disk_key; struct btrfs_chunk *chunk; u8 *array_ptr; unsigned long sb_array_offset; int ret = 0; u32 num_stripes; u32 array_size; u32 len = 0; u32 cur_offset; u64 type; struct btrfs_key key; ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize); /* * This will create extent buffer of nodesize, superblock size is * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will * overallocate but we can keep it as-is, only the first page is used. */ sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET); if (IS_ERR(sb)) return PTR_ERR(sb); set_extent_buffer_uptodate(sb); btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0); /* * The sb extent buffer is artificial and just used to read the system array. * set_extent_buffer_uptodate() call does not properly mark all it's * pages up-to-date when the page is larger: extent does not cover the * whole page and consequently check_page_uptodate does not find all * the page's extents up-to-date (the hole beyond sb), * write_extent_buffer then triggers a WARN_ON. * * Regular short extents go through mark_extent_buffer_dirty/writeback cycle, * but sb spans only this function. Add an explicit SetPageUptodate call * to silence the warning eg. on PowerPC 64. */ if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE) SetPageUptodate(sb->pages[0]); write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE); array_size = btrfs_super_sys_array_size(super_copy); array_ptr = super_copy->sys_chunk_array; sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array); cur_offset = 0; while (cur_offset < array_size) { disk_key = (struct btrfs_disk_key *)array_ptr; len = sizeof(*disk_key); if (cur_offset + len > array_size) goto out_short_read; btrfs_disk_key_to_cpu(&key, disk_key); array_ptr += len; sb_array_offset += len; cur_offset += len; if (key.type == BTRFS_CHUNK_ITEM_KEY) { chunk = (struct btrfs_chunk *)sb_array_offset; /* * At least one btrfs_chunk with one stripe must be * present, exact stripe count check comes afterwards */ len = btrfs_chunk_item_size(1); if (cur_offset + len > array_size) goto out_short_read; num_stripes = btrfs_chunk_num_stripes(sb, chunk); if (!num_stripes) { btrfs_err(fs_info, "invalid number of stripes %u in sys_array at offset %u", num_stripes, cur_offset); ret = -EIO; break; } type = btrfs_chunk_type(sb, chunk); if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) { btrfs_err(fs_info, "invalid chunk type %llu in sys_array at offset %u", type, cur_offset); ret = -EIO; break; } len = btrfs_chunk_item_size(num_stripes); if (cur_offset + len > array_size) goto out_short_read; ret = read_one_chunk(fs_info, &key, sb, chunk); if (ret) break; } else { btrfs_err(fs_info, "unexpected item type %u in sys_array at offset %u", (u32)key.type, cur_offset); ret = -EIO; break; } array_ptr += len; sb_array_offset += len; cur_offset += len; } clear_extent_buffer_uptodate(sb); free_extent_buffer_stale(sb); return ret; out_short_read: btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u", len, cur_offset); clear_extent_buffer_uptodate(sb); free_extent_buffer_stale(sb); return -EIO; } /* * Check if all chunks in the fs are OK for read-write degraded mount * * If the @failing_dev is specified, it's accounted as missing. * * Return true if all chunks meet the minimal RW mount requirements. * Return false if any chunk doesn't meet the minimal RW mount requirements. */ bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info, struct btrfs_device *failing_dev) { struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree; struct extent_map *em; u64 next_start = 0; bool ret = true; read_lock(&map_tree->map_tree.lock); em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1); read_unlock(&map_tree->map_tree.lock); /* No chunk at all? Return false anyway */ if (!em) { ret = false; goto out; } while (em) { struct map_lookup *map; int missing = 0; int max_tolerated; int i; map = em->map_lookup; max_tolerated = btrfs_get_num_tolerated_disk_barrier_failures( map->type); for (i = 0; i < map->num_stripes; i++) { struct btrfs_device *dev = map->stripes[i].dev; if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) || dev->last_flush_error) missing++; else if (failing_dev && failing_dev == dev) missing++; } if (missing > max_tolerated) { if (!failing_dev) btrfs_warn(fs_info, "chunk %llu missing %d devices, max tolerance is %d for writable mount", em->start, missing, max_tolerated); free_extent_map(em); ret = false; goto out; } next_start = extent_map_end(em); free_extent_map(em); read_lock(&map_tree->map_tree.lock); em = lookup_extent_mapping(&map_tree->map_tree, next_start, (u64)(-1) - next_start); read_unlock(&map_tree->map_tree.lock); } out: return ret; } int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info) { struct btrfs_root *root = fs_info->chunk_root; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key key; struct btrfs_key found_key; int ret; int slot; u64 total_dev = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; /* * uuid_mutex is needed only if we are mounting a sprout FS * otherwise we don't need it. */ mutex_lock(&uuid_mutex); mutex_lock(&fs_info->chunk_mutex); /* * Read all device items, and then all the chunk items. All * device items are found before any chunk item (their object id * is smaller than the lowest possible object id for a chunk * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID). */ key.objectid = BTRFS_DEV_ITEMS_OBJECTID; key.offset = 0; key.type = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto error; while (1) { leaf = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret == 0) continue; if (ret < 0) goto error; break; } btrfs_item_key_to_cpu(leaf, &found_key, slot); if (found_key.type == BTRFS_DEV_ITEM_KEY) { struct btrfs_dev_item *dev_item; dev_item = btrfs_item_ptr(leaf, slot, struct btrfs_dev_item); ret = read_one_dev(fs_info, leaf, dev_item); if (ret) goto error; total_dev++; } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) { struct btrfs_chunk *chunk; chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk); ret = read_one_chunk(fs_info, &found_key, leaf, chunk); if (ret) goto error; } path->slots[0]++; } /* * After loading chunk tree, we've got all device information, * do another round of validation checks. */ if (total_dev != fs_info->fs_devices->total_devices) { btrfs_err(fs_info, "super_num_devices %llu mismatch with num_devices %llu found here", btrfs_super_num_devices(fs_info->super_copy), total_dev); ret = -EINVAL; goto error; } if (btrfs_super_total_bytes(fs_info->super_copy) < fs_info->fs_devices->total_rw_bytes) { btrfs_err(fs_info, "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu", btrfs_super_total_bytes(fs_info->super_copy), fs_info->fs_devices->total_rw_bytes); ret = -EINVAL; goto error; } ret = 0; error: mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&uuid_mutex); btrfs_free_path(path); return ret; } void btrfs_init_devices_late(struct btrfs_fs_info *fs_info) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct btrfs_device *device; while (fs_devices) { mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry(device, &fs_devices->devices, dev_list) device->fs_info = fs_info; mutex_unlock(&fs_devices->device_list_mutex); fs_devices = fs_devices->seed; } } static void __btrfs_reset_dev_stats(struct btrfs_device *dev) { int i; for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) btrfs_dev_stat_reset(dev, i); } int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info) { struct btrfs_key key; struct btrfs_key found_key; struct btrfs_root *dev_root = fs_info->dev_root; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct extent_buffer *eb; int slot; int ret = 0; struct btrfs_device *device; struct btrfs_path *path = NULL; int i; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry(device, &fs_devices->devices, dev_list) { int item_size; struct btrfs_dev_stats_item *ptr; key.objectid = BTRFS_DEV_STATS_OBJECTID; key.type = BTRFS_PERSISTENT_ITEM_KEY; key.offset = device->devid; ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0); if (ret) { __btrfs_reset_dev_stats(device); device->dev_stats_valid = 1; btrfs_release_path(path); continue; } slot = path->slots[0]; eb = path->nodes[0]; btrfs_item_key_to_cpu(eb, &found_key, slot); item_size = btrfs_item_size_nr(eb, slot); ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item); for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) { if (item_size >= (1 + i) * sizeof(__le64)) btrfs_dev_stat_set(device, i, btrfs_dev_stats_value(eb, ptr, i)); else btrfs_dev_stat_reset(device, i); } device->dev_stats_valid = 1; btrfs_dev_stat_print_on_load(device); btrfs_release_path(path); } mutex_unlock(&fs_devices->device_list_mutex); out: btrfs_free_path(path); return ret < 0 ? ret : 0; } static int update_dev_stat_item(struct btrfs_trans_handle *trans, struct btrfs_device *device) { struct btrfs_fs_info *fs_info = trans->fs_info; struct btrfs_root *dev_root = fs_info->dev_root; struct btrfs_path *path; struct btrfs_key key; struct extent_buffer *eb; struct btrfs_dev_stats_item *ptr; int ret; int i; key.objectid = BTRFS_DEV_STATS_OBJECTID; key.type = BTRFS_PERSISTENT_ITEM_KEY; key.offset = device->devid; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1); if (ret < 0) { btrfs_warn_in_rcu(fs_info, "error %d while searching for dev_stats item for device %s", ret, rcu_str_deref(device->name)); goto out; } if (ret == 0 && btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) { /* need to delete old one and insert a new one */ ret = btrfs_del_item(trans, dev_root, path); if (ret != 0) { btrfs_warn_in_rcu(fs_info, "delete too small dev_stats item for device %s failed %d", rcu_str_deref(device->name), ret); goto out; } ret = 1; } if (ret == 1) { /* need to insert a new item */ btrfs_release_path(path); ret = btrfs_insert_empty_item(trans, dev_root, path, &key, sizeof(*ptr)); if (ret < 0) { btrfs_warn_in_rcu(fs_info, "insert dev_stats item for device %s failed %d", rcu_str_deref(device->name), ret); goto out; } } eb = path->nodes[0]; ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item); for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) btrfs_set_dev_stats_value(eb, ptr, i, btrfs_dev_stat_read(device, i)); btrfs_mark_buffer_dirty(eb); out: btrfs_free_path(path); return ret; } /* * called from commit_transaction. Writes all changed device stats to disk. */ int btrfs_run_dev_stats(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct btrfs_device *device; int stats_cnt; int ret = 0; mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry(device, &fs_devices->devices, dev_list) { stats_cnt = atomic_read(&device->dev_stats_ccnt); if (!device->dev_stats_valid || stats_cnt == 0) continue; /* * There is a LOAD-LOAD control dependency between the value of * dev_stats_ccnt and updating the on-disk values which requires * reading the in-memory counters. Such control dependencies * require explicit read memory barriers. * * This memory barriers pairs with smp_mb__before_atomic in * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full * barrier implied by atomic_xchg in * btrfs_dev_stats_read_and_reset */ smp_rmb(); ret = update_dev_stat_item(trans, device); if (!ret) atomic_sub(stats_cnt, &device->dev_stats_ccnt); } mutex_unlock(&fs_devices->device_list_mutex); return ret; } void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index) { btrfs_dev_stat_inc(dev, index); btrfs_dev_stat_print_on_error(dev); } static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev) { if (!dev->dev_stats_valid) return; btrfs_err_rl_in_rcu(dev->fs_info, "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u", rcu_str_deref(dev->name), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS)); } static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev) { int i; for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) if (btrfs_dev_stat_read(dev, i) != 0) break; if (i == BTRFS_DEV_STAT_VALUES_MAX) return; /* all values == 0, suppress message */ btrfs_info_in_rcu(dev->fs_info, "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u", rcu_str_deref(dev->name), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS), btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS)); } int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info, struct btrfs_ioctl_get_dev_stats *stats) { struct btrfs_device *dev; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; int i; mutex_lock(&fs_devices->device_list_mutex); dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL); mutex_unlock(&fs_devices->device_list_mutex); if (!dev) { btrfs_warn(fs_info, "get dev_stats failed, device not found"); return -ENODEV; } else if (!dev->dev_stats_valid) { btrfs_warn(fs_info, "get dev_stats failed, not yet valid"); return -ENODEV; } else if (stats->flags & BTRFS_DEV_STATS_RESET) { for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) { if (stats->nr_items > i) stats->values[i] = btrfs_dev_stat_read_and_reset(dev, i); else btrfs_dev_stat_reset(dev, i); } } else { for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) if (stats->nr_items > i) stats->values[i] = btrfs_dev_stat_read(dev, i); } if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX) stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX; return 0; } void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path) { struct buffer_head *bh; struct btrfs_super_block *disk_super; int copy_num; if (!bdev) return; for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) { if (btrfs_read_dev_one_super(bdev, copy_num, &bh)) continue; disk_super = (struct btrfs_super_block *)bh->b_data; memset(&disk_super->magic, 0, sizeof(disk_super->magic)); set_buffer_dirty(bh); sync_dirty_buffer(bh); brelse(bh); } /* Notify udev that device has changed */ btrfs_kobject_uevent(bdev, KOBJ_CHANGE); /* Update ctime/mtime for device path for libblkid */ update_dev_time(device_path); } /* * Update the size of all devices, which is used for writing out the * super blocks. */ void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct btrfs_device *curr, *next; if (list_empty(&fs_devices->resized_devices)) return; mutex_lock(&fs_devices->device_list_mutex); mutex_lock(&fs_info->chunk_mutex); list_for_each_entry_safe(curr, next, &fs_devices->resized_devices, resized_list) { list_del_init(&curr->resized_list); curr->commit_total_bytes = curr->disk_total_bytes; } mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&fs_devices->device_list_mutex); } /* Must be invoked during the transaction commit */ void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans) { struct btrfs_fs_info *fs_info = trans->fs_info; struct extent_map *em; struct map_lookup *map; struct btrfs_device *dev; int i; if (list_empty(&trans->pending_chunks)) return; /* In order to kick the device replace finish process */ mutex_lock(&fs_info->chunk_mutex); list_for_each_entry(em, &trans->pending_chunks, list) { map = em->map_lookup; for (i = 0; i < map->num_stripes; i++) { dev = map->stripes[i].dev; dev->commit_bytes_used = dev->bytes_used; } } mutex_unlock(&fs_info->chunk_mutex); } void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; while (fs_devices) { fs_devices->fs_info = fs_info; fs_devices = fs_devices->seed; } } void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info) { struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; while (fs_devices) { fs_devices->fs_info = NULL; fs_devices = fs_devices->seed; } } /* * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10. */ int btrfs_bg_type_to_factor(u64 flags) { if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) return 2; return 1; } static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes) { int index = btrfs_bg_flags_to_raid_index(type); int ncopies = btrfs_raid_array[index].ncopies; int data_stripes; switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) { case BTRFS_BLOCK_GROUP_RAID5: data_stripes = num_stripes - 1; break; case BTRFS_BLOCK_GROUP_RAID6: data_stripes = num_stripes - 2; break; default: data_stripes = num_stripes / ncopies; break; } return div_u64(chunk_len, data_stripes); } static int verify_one_dev_extent(struct btrfs_fs_info *fs_info, u64 chunk_offset, u64 devid, u64 physical_offset, u64 physical_len) { struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree; struct extent_map *em; struct map_lookup *map; struct btrfs_device *dev; u64 stripe_len; bool found = false; int ret = 0; int i; read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, chunk_offset, 1); read_unlock(&em_tree->lock); if (!em) { btrfs_err(fs_info, "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk", physical_offset, devid); ret = -EUCLEAN; goto out; } map = em->map_lookup; stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes); if (physical_len != stripe_len) { btrfs_err(fs_info, "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu", physical_offset, devid, em->start, physical_len, stripe_len); ret = -EUCLEAN; goto out; } for (i = 0; i < map->num_stripes; i++) { if (map->stripes[i].dev->devid == devid && map->stripes[i].physical == physical_offset) { found = true; if (map->verified_stripes >= map->num_stripes) { btrfs_err(fs_info, "too many dev extents for chunk %llu found", em->start); ret = -EUCLEAN; goto out; } map->verified_stripes++; break; } } if (!found) { btrfs_err(fs_info, "dev extent physical offset %llu devid %llu has no corresponding chunk", physical_offset, devid); ret = -EUCLEAN; } /* Make sure no dev extent is beyond device bondary */ dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (!dev) { btrfs_err(fs_info, "failed to find devid %llu", devid); ret = -EUCLEAN; goto out; } /* It's possible this device is a dummy for seed device */ if (dev->disk_total_bytes == 0) { dev = find_device(fs_info->fs_devices->seed, devid, NULL); if (!dev) { btrfs_err(fs_info, "failed to find seed devid %llu", devid); ret = -EUCLEAN; goto out; } } if (physical_offset + physical_len > dev->disk_total_bytes) { btrfs_err(fs_info, "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu", devid, physical_offset, physical_len, dev->disk_total_bytes); ret = -EUCLEAN; goto out; } out: free_extent_map(em); return ret; } static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info) { struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree; struct extent_map *em; struct rb_node *node; int ret = 0; read_lock(&em_tree->lock); for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) { em = rb_entry(node, struct extent_map, rb_node); if (em->map_lookup->num_stripes != em->map_lookup->verified_stripes) { btrfs_err(fs_info, "chunk %llu has missing dev extent, have %d expect %d", em->start, em->map_lookup->verified_stripes, em->map_lookup->num_stripes); ret = -EUCLEAN; goto out; } } out: read_unlock(&em_tree->lock); return ret; } /* * Ensure that all dev extents are mapped to correct chunk, otherwise * later chunk allocation/free would cause unexpected behavior. * * NOTE: This will iterate through the whole device tree, which should be of * the same size level as the chunk tree. This slightly increases mount time. */ int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info) { struct btrfs_path *path; struct btrfs_root *root = fs_info->dev_root; struct btrfs_key key; u64 prev_devid = 0; u64 prev_dev_ext_end = 0; int ret = 0; key.objectid = 1; key.type = BTRFS_DEV_EXTENT_KEY; key.offset = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = READA_FORWARD; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) { ret = btrfs_next_item(root, path); if (ret < 0) goto out; /* No dev extents at all? Not good */ if (ret > 0) { ret = -EUCLEAN; goto out; } } while (1) { struct extent_buffer *leaf = path->nodes[0]; struct btrfs_dev_extent *dext; int slot = path->slots[0]; u64 chunk_offset; u64 physical_offset; u64 physical_len; u64 devid; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.type != BTRFS_DEV_EXTENT_KEY) break; devid = key.objectid; physical_offset = key.offset; dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent); chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext); physical_len = btrfs_dev_extent_length(leaf, dext); /* Check if this dev extent overlaps with the previous one */ if (devid == prev_devid && physical_offset < prev_dev_ext_end) { btrfs_err(fs_info, "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu", devid, physical_offset, prev_dev_ext_end); ret = -EUCLEAN; goto out; } ret = verify_one_dev_extent(fs_info, chunk_offset, devid, physical_offset, physical_len); if (ret < 0) goto out; prev_devid = devid; prev_dev_ext_end = physical_offset + physical_len; ret = btrfs_next_item(root, path); if (ret < 0) goto out; if (ret > 0) { ret = 0; break; } } /* Ensure all chunks have corresponding dev extents */ ret = verify_chunk_dev_extent_mapping(fs_info); out: btrfs_free_path(path); return ret; } /* * Check whether the given block group or device is pinned by any inode being * used as a swapfile. */ bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr) { struct btrfs_swapfile_pin *sp; struct rb_node *node; spin_lock(&fs_info->swapfile_pins_lock); node = fs_info->swapfile_pins.rb_node; while (node) { sp = rb_entry(node, struct btrfs_swapfile_pin, node); if (ptr < sp->ptr) node = node->rb_left; else if (ptr > sp->ptr) node = node->rb_right; else break; } spin_unlock(&fs_info->swapfile_pins_lock); return node != NULL; }
./CrossVul/dataset_final_sorted/CWE-476/c/bad_1223_3