code
stringlengths
1
1.72M
language
stringclasses
1 value
# Fat Defines... FAT_MAGIC = 0xcafebabe FAT_CIGAM = 0xbebafec #NXSwapLong(FAT_MAGIC) MH_MAGIC = 0xfeedface # the mach magic number MH_CIGAM = 0xcefaedfe # NXSwapInt(MH_MAGIC) MH_MAGIC_64 = 0xfeedfacf # the 64-bit mach magic number MH_CIGAM_64 = 0xcffaedfe # NXSwapInt(MH_MAGIC_64) MH_OBJECT = 0x1 # relocatable object file MH_EXECUTE = 0x2 # demand paged executable file MH_FVMLIB = 0x3 # fixed VM shared library file MH_CORE = 0x4 # core file MH_PRELOAD = 0x5 # preloaded executable file MH_DYLIB = 0x6 # dynamically bound shared library MH_DYLINKER = 0x7 # dynamic link editor MH_BUNDLE = 0x8 # dynamically bound bundle file MH_DYLIB_STUB = 0x9 # shared library stub for static MH_DSYM = 0xa # companion file with only debug MH_NOUNDEFS = 0x1 # the object file has no undefinedreferences MH_INCRLINK = 0x2 # the object file is the output of anincremental link against a base fileand can't be link edited again MH_DYLDLINK = 0x4 # the object file is input for thedynamic linker and can't be staticlylink edited again MH_BINDATLOAD = 0x8 # the object file's undefinedreferences are bound by the dynamiclinker when loaded. MH_PREBOUND = 0x10 # the file has its dynamic undefinedreferences prebound. MH_SPLIT_SEGS = 0x20 # the file has its read-only andread-write segments split MH_LAZY_INIT = 0x40 # the shared library init routine isto be run lazily via catching memoryfaults to its writeable segments(obsolete) MH_TWOLEVEL = 0x80 # the image is using two-level namespace bindings MH_FORCE_FLAT = 0x100 # the executable is forcing all imagesto use flat name space bindings MH_NOMULTIDEFS = 0x200 # this umbrella guarantees no multipledefintions of symbols in itssub-images so the two-level namespacehints can always be used. MH_NOFIXPREBINDING = 0x400 # do not have dyld notify theprebinding agent about thisexecutable MH_PREBINDABLE = 0x800 # the binary is not prebound but canhave its prebinding redone. only usedwhen MH_PREBOUND is not set. MH_ALLMODSBOUND = 0x1000 # this binary binds toall two-level namespace modules ofits dependent libraries. only usedwhen MH_PREBINDABLE and MH_TWOLEVELare both set. MH_CANONICAL = 0x4000 # the binary has been canonicalizedvia the unprebind operation MH_WEAK_DEFINES = 0x8000 # the final linked image containsexternal weak symbols MH_BINDS_TO_WEAK = 0x10000 # the final linked image usesweak symbols MH_ROOT_SAFE = 0x40000 # When this bit is set, the binarydeclares it is safe for use inprocesses with uid zero MH_SETUID_SAFE = 0x80000 # When this bit is set, the binarydeclares it is safe for use inprocesses when issetugid() is true MH_NO_REEXPORTED_DYLIBS = 0x100000 # When this bit is set on a dylib,the static linker does not need toexamine dependent dylibs to seeif any are re-exported MH_PIE = 0x200000 # When this bit is set, the OS willload the main executable at arandom address. Only used inMH_EXECUTE filetypes. # Constants for the cmd field of all load commands, the type LC_REQ_DYLD = 0x80000000 # When this bit is set, the OS willload the main executable at arandom address. Only used inMH_EXECUTE filetypes. LC_SEGMENT = 0x1 # segment of this file to be mapped LC_SYMTAB = 0x2 # link-edit stab symbol table info LC_SYMSEG = 0x3 # link-edit gdb symbol table info (obsolete) LC_THREAD = 0x4 # thread LC_UNIXTHREAD = 0x5 # unix thread (includes a stack) LC_LOADFVMLIB = 0x6 # load a specified fixed VM shared library LC_IDFVMLIB = 0x7 # fixed VM shared library identification LC_IDENT = 0x8 # object identification info (obsolete) LC_FVMFILE = 0x9 # fixed VM file inclusion (internal use) LC_PREPAGE = 0xa # prepage command (internal use) LC_DYSYMTAB = 0xb # dynamic link-edit symbol table info LC_LOAD_DYLIB = 0xc # load a dynamically linked shared library LC_ID_DYLIB = 0xd # dynamically linked shared lib ident LC_LOAD_DYLINKER = 0xe # load a dynamic linker LC_ID_DYLINKER = 0xf # dynamic linker identification LC_PREBOUND_DYLIB = 0x10 # modules prebound for a dynamically LC_ROUTINES = 0x11 # image routines LC_SUB_FRAMEWORK = 0x12 # sub framework LC_SUB_UMBRELLA = 0x13 # sub umbrella LC_SUB_CLIENT = 0x14 # sub client LC_SUB_LIBRARY = 0x15 # sub library LC_TWOLEVEL_HINTS = 0x16 # two-level namespace lookup hints LC_PREBIND_CKSUM = 0x17 # prebind checksum LC_SEGMENT_64 = 0x19 # 64-bit segment of this file to bemapped LC_ROUTINES_64 = 0x1a # 64-bit image routines LC_UUID = 0x1b # the uuid LC_CODE_SIGNATURE = 0x1d # local of code signature LC_SEGMENT_SPLIT_INFO = 0x1e # local of info to split segments LC_LAZY_LOAD_DYLIB = 0x20 # delay load of dylib until first use LC_ENCRYPTION_INFO = 0x21 # encrypted segment information SG_HIGHVM = 0x1 # the file contents for this segment is forthe high part of the VM space, the low partis zero filled (for stacks in core files) SG_FVMLIB = 0x2 # this segment is the VM that is allocated bya fixed VM library, for overlap checking inthe link editor SG_NORELOC = 0x4 # this segment has nothing that was relocatedin it and nothing relocated to it, that isit maybe safely replaced without relocation SG_PROTECTED_VERSION_1 = 0x8 # This segment is protected. If thesegment starts at file offset 0, thefirst page of the segment is notprotected. All other pages of thesegment are protected. SECTION_TYPE = 0x000000ff # 256 section types SECTION_ATTRIBUTES = 0xffffff00 # 24 section attributes S_REGULAR = 0x0 # regular section S_ZEROFILL = 0x1 # zero fill on demand section S_CSTRING_LITERALS = 0x2 # section with only literal C strings S_4BYTE_LITERALS = 0x3 # section with only 4 byte literals S_8BYTE_LITERALS = 0x4 # section with only 8 byte literals S_LITERAL_POINTERS = 0x5 # section with only pointers to S_NON_LAZY_SYMBOL_POINTERS = 0x6 # section with only non-lazysymbol pointers S_LAZY_SYMBOL_POINTERS = 0x7 # section with only lazy symbolpointers S_SYMBOL_STUBS = 0x8 # section with only symbolstubs, byte size of stub inthe reserved2 field S_MOD_INIT_FUNC_POINTERS = 0x9 # section with only functionpointers for initialization S_MOD_TERM_FUNC_POINTERS = 0xa # section with only functionpointers for termination S_COALESCED = 0xb # section contains symbols thatare to be coalesced S_GB_ZEROFILL = 0xc # zero fill on demand section(that can be larger than 4gigabytes) S_INTERPOSING = 0xd # section with only pairs offunction pointers forinterposing S_16BYTE_LITERALS = 0xe # section with only 16 byteliterals S_DTRACE_DOF = 0xf # section containsDTrace Object Format S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10 # section with only lazysymbol pointers to lazyloaded dylibs SECTION_ATTRIBUTES_USR = 0xff000000 # User setable attributes S_ATTR_PURE_INSTRUCTIONS = 0x80000000 # section contains only truemachine instructions S_ATTR_NO_TOC = 0x40000000 # section contains coalescedsymbols that are not to bein a ranlib table ofcontents S_ATTR_STRIP_STATIC_SYMS = 0x20000000 # ok to strip static symbolsin this section in fileswith the MH_DYLDLINK flag S_ATTR_NO_DEAD_STRIP = 0x10000000 # no dead stripping S_ATTR_LIVE_SUPPORT = 0x08000000 # blocks are live if theyreference live blocks S_ATTR_SELF_MODIFYING_CODE = 0x04000000 # Used with i386 code stubswritten on by dyld S_ATTR_DEBUG = 0x02000000 # a debug section SECTION_ATTRIBUTES_SYS = 0x00ffff00 # system setable attributes S_ATTR_SOME_INSTRUCTIONS = 0x00000400 # section contains somemachine instructions S_ATTR_EXT_RELOC = 0x00000200 # section has externalrelocation entries S_ATTR_LOC_RELOC = 0x00000100 # section has localrelocation entries INDIRECT_SYMBOL_LOCAL = 0x80000000 # section has localrelocation entries INDIRECT_SYMBOL_ABS = 0x40000000 # section has localrelocation entries CPU_TYPE_ANY = -1 CPU_TYPE_VAX = 1 CPU_TYPE_MC680 = 6 CPU_TYPE_X86 = 7 CPU_TYPE_X86_64 = 0x01000007 #CPU_TYPE_MIPS ((cpu_type_t) 8) */ #CPU_TYPE_MC98000 ((cpu_type_t) 10) #CPU_TYPE_HPPA ((cpu_type_t) 11) #CPU_TYPE_ARM ((cpu_type_t) 12) #CPU_TYPE_MC88000 ((cpu_type_t) 13) #CPU_TYPE_SPARC ((cpu_type_t) 14) #CPU_TYPE_I860 ((cpu_type_t) 15) #CPU_TYPE_ALPHA ((cpu_type_t) 16) */ #CPU_TYPE_POWERPC ((cpu_type_t) 18) #CPU_TYPE_POWERPC64 (CPU_TYPE_POWERPC | CPU_ARCH_ABI64)
Python
import vstruct import vstruct.primitives as vs_prim class fat_header(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self, bigend=True) self.magic = vs_prim.v_uint32() self.nfat_arch = vs_prim.v_uint32() class fat_arch(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self, bigend=True) self.cputype = vs_prim.v_uint32() # cpu specifier (int) */ self.cpusubtype = vs_prim.v_uint32() # machine specifier (int) */ self.offset = vs_prim.v_uint32() # file offset to this object file */ self.size = vs_prim.v_uint32() # size of this object file */ self.align = vs_prim.v_uint32() # alignment as a power of 2 */
Python
''' Structure definitions for the OSX MachO binary format. ''' import vstruct import vstruct.primitives as vs_prim from vstruct.defs.macho.const import * from vstruct.defs.macho.fat import * from vstruct.defs.macho.loader import *
Python
import vstruct import vstruct.primitives as vs_prim vm_prot_t = vs_prim.v_uint32 cpu_type_t = vs_prim.v_uint32 cpu_subtype_t = vs_prim.v_uint32 lc_str = vs_prim.v_uint32 class mach_header(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.magic = vs_prim.v_uint32() # mach magic number identifier self.cputype = cpu_type_t() # cpu specifier self.cpusubtype = cpu_subtype_t() # machine specifier self.filetype = vs_prim.v_uint32() # type of file self.ncmds = vs_prim.v_uint32() # number of load commands self.sizeofcmds = vs_prim.v_uint32() # the size of all the load commands self.flags = vs_prim.v_uint32() # flags class mach_header_64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.magic = vs_prim.v_uint32() # mach magic number identifier self.cputype = cpu_type_t() # cpu specifier self.cpusubtype = cpu_subtype_t() # machine specifier self.filetype = vs_prim.v_uint32() # type of file self.ncmds = vs_prim.v_uint32() # number of load commands self.sizeofcmds = vs_prim.v_uint32() # the size of all the load commands self.flags = vs_prim.v_uint32() # flags self.reserved = vs_prim.v_uint32() # reserved class load_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # type of load command self.cmdsize = vs_prim.v_uint32() # total size of command in bytes class segment_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SEGMENT self.cmdsize = vs_prim.v_uint32() # includes sizeof section structs self.segname[16] = vs_prim.v_uint8() # segment name self.vmaddr = vs_prim.v_uint32() # memory address of this segment self.vmsize = vs_prim.v_uint32() # memory size of this segment self.fileoff = vs_prim.v_uint32() # file offset of this segment self.filesize = vs_prim.v_uint32() # amount to map from the file self.maxprot = vm_prot_t() # maximum VM protection self.initprot = vm_prot_t() # initial VM protection self.nsects = vs_prim.v_uint32() # number of sections in segment self.flags = vs_prim.v_uint32() # flags class segment_command_64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SEGMENT_64 self.cmdsize = vs_prim.v_uint32() # includes sizeof section_64 structs self.segname[16] = vs_prim.v_uint8() # segment name self.vmaddr = vs_prim.v_uint64() # memory address of this segment self.vmsize = vs_prim.v_uint64() # memory size of this segment self.fileoff = vs_prim.v_uint64() # file offset of this segment self.filesize = vs_prim.v_uint64() # amount to map from the file self.maxprot = vm_prot_t() # maximum VM protection self.initprot = vm_prot_t() # initial VM protection self.nsects = vs_prim.v_uint32() # number of sections in segment self.flags = vs_prim.v_uint32() # flags class section(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.sectname[16] = vs_prim.v_uint8() # name of this section self.segname[16] = vs_prim.v_uint8() # segment this section goes in self.addr = vs_prim.v_uint32() # memory address of this section self.size = vs_prim.v_uint32() # size in bytes of this section self.offset = vs_prim.v_uint32() # file offset of this section self.align = vs_prim.v_uint32() # section alignment (power of 2) self.reloff = vs_prim.v_uint32() # file offset of relocation entries self.nreloc = vs_prim.v_uint32() # number of relocation entries self.flags = vs_prim.v_uint32() # flags (section type and attributes) self.reserved1 = vs_prim.v_uint32() # reserved (for offset or index) self.reserved2 = vs_prim.v_uint32() # reserved (for count or sizeof) class section_64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.sectname[16] = vs_prim.v_uint8() # name of this section self.segname[16] = vs_prim.v_uint8() # segment this section goes in self.addr = vs_prim.v_uint64() # memory address of this section self.size = vs_prim.v_uint64() # size in bytes of this section self.offset = vs_prim.v_uint32() # file offset of this section self.align = vs_prim.v_uint32() # section alignment (power of 2) self.reloff = vs_prim.v_uint32() # file offset of relocation entries self.nreloc = vs_prim.v_uint32() # number of relocation entries self.flags = vs_prim.v_uint32() # flags (section type and attributes) self.reserved1 = vs_prim.v_uint32() # reserved (for offset or index) self.reserved2 = vs_prim.v_uint32() # reserved (for count or sizeof) self.reserved3 = vs_prim.v_uint32() # reserved class fvmlib(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.name = lc_str() # library's target pathname self.minor_version = vs_prim.v_uint32() # library's minor version number self.header_addr = vs_prim.v_uint32() # library's header address class fvmlib_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_IDFVMLIB or LC_LOADFVMLIB self.cmdsize = vs_prim.v_uint32() # includes pathname string self.fvmlib = fvmlib() # the library identification class dylib(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.name = lc_str() # library's path name self.timestamp = vs_prim.v_uint32() # library's build time stamp self.current_version = vs_prim.v_uint32() # library's current version number self.compatibility_version = vs_prim.v_uint32() # library's compatibility vers number class dylib_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_ID_DYLIB, LC_LOAD_{,WEAK_}DYLIB, LC_REEXPORT_DYLIB self.cmdsize = vs_prim.v_uint32() # includes pathname string self.dylib = dylib() # the library identification class sub_framework_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SUB_FRAMEWORK self.cmdsize = vs_prim.v_uint32() # includes umbrella string self.umbrella = lc_str() # the umbrella framework name class sub_client_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SUB_CLIENT self.cmdsize = vs_prim.v_uint32() # includes client string self.client = lc_str() # the client name class sub_umbrella_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SUB_UMBRELLA self.cmdsize = vs_prim.v_uint32() # includes sub_umbrella string self.sub_umbrella = lc_str() # the sub_umbrella framework name class sub_library_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SUB_LIBRARY self.cmdsize = vs_prim.v_uint32() # includes sub_library string self.sub_library = lc_str() # the sub_library name class prebound_dylib_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_PREBOUND_DYLIB self.cmdsize = vs_prim.v_uint32() # includes strings self.name = lc_str() # library's path name self.nmodules = vs_prim.v_uint32() # number of modules in library self.linked_modules = lc_str() # bit vector of linked modules class dylinker_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_ID_DYLINKER or LC_LOAD_DYLINKER self.cmdsize = vs_prim.v_uint32() # includes pathname string self.name = lc_str() # dynamic linker's path name class thread_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_THREAD or LC_UNIXTHREAD self.cmdsize = vs_prim.v_uint32() # total size of this command class routines_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_ROUTINES self.cmdsize = vs_prim.v_uint32() # total size of this command self.init_address = vs_prim.v_uint32() # address of initialization routine self.init_module = vs_prim.v_uint32() # index into the module table that self.reserved1 = vs_prim.vs_prim.v_uint32() self.reserved2 = vs_prim.vs_prim.v_uint32() self.reserved3 = vs_prim.vs_prim.v_uint32() self.reserved4 = vs_prim.vs_prim.v_uint32() self.reserved5 = vs_prim.vs_prim.v_uint32() self.reserved6 = vs_prim.vs_prim.v_uint32() class routines_command_64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_ROUTINES_64 self.cmdsize = vs_prim.v_uint32() # total size of this command self.init_address = vs_prim.v_uint64() # address of initialization routine self.init_module = vs_prim.v_uint64() # index into the module table that self.reserved1 = vs_prim.vs_prim.v_uint64() self.reserved2 = vs_prim.vs_prim.v_uint64() self.reserved3 = vs_prim.vs_prim.v_uint64() self.reserved4 = vs_prim.vs_prim.v_uint64() self.reserved5 = vs_prim.vs_prim.v_uint64() self.reserved6 = vs_prim.vs_prim.v_uint64() class symtab_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SYMTAB self.cmdsize = vs_prim.v_uint32() # sizeof(struct symtab_command) self.symoff = vs_prim.v_uint32() # symbol table offset self.nsyms = vs_prim.v_uint32() # number of symbol table entries self.stroff = vs_prim.v_uint32() # string table offset self.strsize = vs_prim.v_uint32() # string table size in bytes class dysymtab_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_DYSYMTAB self.cmdsize = vs_prim.v_uint32() # sizeof(struct dysymtab_command) self.ilocalsym = vs_prim.v_uint32() # index to local symbols self.nlocalsym = vs_prim.v_uint32() # number of local symbols self.iextdefsym = vs_prim.v_uint32() # index to externally defined symbols self.nextdefsym = vs_prim.v_uint32() # number of externally defined symbols self.iundefsym = vs_prim.v_uint32() # index to undefined symbols self.nundefsym = vs_prim.v_uint32() # number of undefined symbols self.tocoff = vs_prim.v_uint32() # file offset to table of contents self.ntoc = vs_prim.v_uint32() # number of entries in table of contents self.modtaboff = vs_prim.v_uint32() # file offset to module table self.nmodtab = vs_prim.v_uint32() # number of module table entries self.extrefsymoff = vs_prim.v_uint32() # offset to referenced symbol table self.nextrefsyms = vs_prim.v_uint32() # number of referenced symbol table entries self.indirectsymoff = vs_prim.v_uint32() # file offset to the indirect symbol table self.nindirectsyms = vs_prim.v_uint32() # number of indirect symbol table entries self.extreloff = vs_prim.v_uint32() # offset to external relocation entries self.nextrel = vs_prim.v_uint32() # number of external relocation entries self.locreloff = vs_prim.v_uint32() # offset to local relocation entries self.nlocrel = vs_prim.v_uint32() # number of local relocation entries class dylib_table_of_contents(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.symbol_index = vs_prim.v_uint32() # the defined external symbol (index into the symbol table) self.module_index = vs_prim.v_uint32() # index into the module table this symbol is defined in class dylib_module(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.module_name = vs_prim.v_uint32() # the module name (index into string table) self.iextdefsym = vs_prim.v_uint32() # index into externally defined symbols self.nextdefsym = vs_prim.v_uint32() # number of externally defined symbols self.irefsym = vs_prim.v_uint32() # index into reference symbol table self.nrefsym = vs_prim.v_uint32() # number of reference symbol table entries self.ilocalsym = vs_prim.v_uint32() # index into symbols for local symbols self.nlocalsym = vs_prim.v_uint32() # number of local symbols self.iextrel = vs_prim.v_uint32() # index into external relocation entries self.nextrel = vs_prim.v_uint32() # number of external relocation entries self.iinit_iterm = vs_prim.v_uint32() # low 16 bits are the index into the init section, high 16 bits are the index into the term section self.ninit_nterm = vs_prim.v_uint32() # low 16 bits are the number of init section entries, high 16 bits are the number of term section entries self.objc_module_info_addr = vs_prim.v_uint32() # the (__OBJC,__module_info) section self.objc_module_info_size = vs_prim.v_uint32() # the (__OBJC,__module_info) section class dylib_module_64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.module_name = vs_prim.v_uint32() # the module name (index into string table) self.iextdefsym = vs_prim.v_uint32() # index into externally defined symbols self.nextdefsym = vs_prim.v_uint32() # number of externally defined symbols self.irefsym = vs_prim.v_uint32() # index into reference symbol table self.nrefsym = vs_prim.v_uint32() # number of reference symbol table entries self.ilocalsym = vs_prim.v_uint32() # index into symbols for local symbols self.nlocalsym = vs_prim.v_uint32() # number of local symbols self.iextrel = vs_prim.v_uint32() # index into external relocation entries self.nextrel = vs_prim.v_uint32() # number of external relocation entries self.iinit_iterm = vs_prim.v_uint32() # low 16 bits are the index into the init section, high 16 bits are the index into the term section self.ninit_nterm = vs_prim.v_uint32() # low 16 bits are the number of init section entries, high 16 bits are the number of term section entries self.objc_module_info_size = vs_prim.v_uint32() # the (__OBJC,__module_info) section self.objc_module_info_addr = vs_prim.v_uint64() # the (__OBJC,__module_info) section class dylib_reference(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.flags = vs_prim.v_uint32() # flags to indicate the type of reference class twolevel_hints_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_TWOLEVEL_HINTS self.cmdsize = vs_prim.v_uint32() # sizeof(struct twolevel_hints_command) self.offset = vs_prim.v_uint32() # offset to the hint table self.nhints = vs_prim.v_uint32() # number of hints in the hint table class twolevel_hint(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.itoc = vs_prim.v_uint32() # index into the table of contents class prebind_cksum_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_PREBIND_CKSUM self.cmdsize = vs_prim.v_uint32() # sizeof(struct prebind_cksum_command) self.cksum = vs_prim.v_uint32() # the check sum or zero class uuid_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_UUID self.cmdsize = vs_prim.v_uint32() # sizeof(struct uuid_command) self.uuid[16] = vs_prim.v_uint8() # the 128-bit uuid class rpath_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_RPATH self.cmdsize = vs_prim.v_uint32() # includes string self.path = lc_str() # path to add to run path class linkedit_data_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_CODE_SIGNATURE or LC_SEGMENT_SPLIT_INFO self.cmdsize = vs_prim.v_uint32() # sizeof(struct linkedit_data_command) self.dataoff = vs_prim.v_uint32() # file offset of data in __LINKEDIT segment self.datasize = vs_prim.v_uint32() # file size of data in __LINKEDIT segment class encryption_info_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_ENCRYPTION_INFO self.cmdsize = vs_prim.v_uint32() # sizeof(struct encryption_info_command) self.cryptoff = vs_prim.v_uint32() # file offset of encrypted range self.cryptsize = vs_prim.v_uint32() # file size of encrypted range self.cryptid = vs_prim.v_uint32() # which enryption system, 0 means not-encrypted yet class symseg_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_SYMSEG self.cmdsize = vs_prim.v_uint32() # sizeof(struct symseg_command) self.offset = vs_prim.v_uint32() # symbol segment offset self.size = vs_prim.v_uint32() # symbol segment size in bytes class ident_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_IDENT self.cmdsize = vs_prim.v_uint32() # strings that follow this command class fvmfile_command(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.cmd = vs_prim.v_uint32() # LC_FVMFILE self.cmdsize = vs_prim.v_uint32() # includes pathname string self.name = lc_str() # files pathname self.header_addr = vs_prim.v_uint32() # files virtual address
Python
import vstruct from vstruct.primitives import * class IMAGE_BASE_RELOCATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.SizeOfBlock = v_uint32() class IMAGE_DATA_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.Size = v_uint32() class IMAGE_DOS_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.e_magic = v_uint16() self.e_cblp = v_uint16() self.e_cp = v_uint16() self.e_crlc = v_uint16() self.e_cparhdr = v_uint16() self.e_minalloc = v_uint16() self.e_maxalloc = v_uint16() self.e_ss = v_uint16() self.e_sp = v_uint16() self.e_csum = v_uint16() self.e_ip = v_uint16() self.e_cs = v_uint16() self.e_lfarlc = v_uint16() self.e_ovno = v_uint16() self.e_res = vstruct.VArray([v_uint16() for i in range(4)]) self.e_oemid = v_uint16() self.e_oeminfo = v_uint16() self.e_res2 = vstruct.VArray([v_uint16() for i in range(10)]) self.e_lfanew = v_uint32() class IMAGE_EXPORT_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Characteristics = v_uint32() self.TimeDateStamp = v_uint32() self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.Name = v_uint32() self.Base = v_uint32() self.NumberOfFunctions = v_uint32() self.NumberOfNames = v_uint32() self.AddressOfFunctions = v_uint32() self.AddressOfNames = v_uint32() self.AddressOfOrdinals = v_uint32() class IMAGE_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Machine = v_uint16() self.NumberOfSections = v_uint16() self.TimeDateStamp = v_uint32() self.PointerToSymbolTable = v_uint32() self.NumberOfSymbols = v_uint32() self.SizeOfOptionalHeader = v_uint16() self.Ccharacteristics = v_uint16() class IMAGE_IMPORT_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OriginalFirstThunk = v_uint32() self.TimeDateStamp = v_uint32() self.ForwarderChain = v_uint32() self.Name = v_uint32() self.FirstThunk = v_uint32() class IMAGE_LOAD_CONFIG_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint32() self.TimeDateStamp = v_uint32() self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.GlobalFlagsClear = v_uint32() self.GlobalFlagsSet = v_uint32() self.CriticalSectionDefaultTimeout = v_uint32() self.DeCommitFreeBlockThreshold = v_uint32() self.DeCommitTotalFreeThreshold = v_uint32() self.LockPrefixTable = v_uint32() self.MaximumAllocationSize = v_uint32() self.VirtualMemoryThreshold = v_uint32() self.ProcessHeapFlags = v_uint32() self.ProcessAffinityMask = v_uint32() self.CSDVersion = v_uint16() self.Reserved1 = v_uint16() self.EditList = v_uint32() self.SecurityCookie = v_uint32() self.SEHandlerTable = v_uint32() self.SEHandlerCount = v_uint32() class IMAGE_NT_HEADERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_bytes(4) self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER() class IMAGE_NT_HEADERS64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_bytes(4) self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER64() class IMAGE_OPTIONAL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_bytes(2) self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.BaseOfData = v_uint32() self.ImageBase = v_uint32() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint32() self.SizeOfStackCommit = v_uint32() self.SizeOfHeapReserve = v_uint32() self.SizeOfHeapCommit = v_uint32() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = vstruct.VArray([IMAGE_DATA_DIRECTORY() for i in range(16)]) class IMAGE_OPTIONAL_HEADER64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_bytes(2) self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.ImageBase = v_uint64() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint64() self.SizeOfStackCommit = v_uint64() self.SizeOfHeapReserve = v_uint64() self.SizeOfHeapCommit = v_uint64() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = vstruct.VArray([IMAGE_DATA_DIRECTORY() for i in range(16)]) class IMAGE_RESOURCE_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Characteristics = v_uint32() self.TimeDateStamp = v_uint32() self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.NumberOfNamedEntries = v_uint16() self.NumberOfIdEntries = v_uint16() class IMAGE_SECTION_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = v_str(8) self.VirtualSize = v_uint32() self.VirtualAddress = v_uint32() self.SizeOfRawData = v_uint32() self.PointerToRawData = v_uint32() self.PointerToRelocations = v_uint32() self.PointerToLineNumbers = v_uint32() self.NumberOfRelocations = v_uint16() self.NumberOfLineNumbers = v_uint16() self.Characteristics = v_uint32() class IMAGE_RUNTIME_FUNCTION_ENTRY(vstruct.VStruct): """ Used in the .pdata section of a PE32+ for all non leaf functions. """ def __init__(self): vstruct.VStruct.__init__(self) self.BeginAddress = v_uint32() self.EndAddress = v_uint32() self.UnwindInfoAddress = v_uint32()
Python
# Version: 6.1 # Architecture: amd64 import vstruct from vstruct.primitives import * KPROCESS_STATE = v_enum() KPROCESS_STATE.ProcessInMemory = 0 KPROCESS_STATE.ProcessOutOfMemory = 1 KPROCESS_STATE.ProcessInTransition = 2 KPROCESS_STATE.ProcessOutTransition = 3 KPROCESS_STATE.ProcessInSwap = 4 KPROCESS_STATE.ProcessOutSwap = 5 KPROCESS_STATE.ProcessAllSwapStates = 6 PS_STD_HANDLE_STATE = v_enum() PS_STD_HANDLE_STATE.PsNeverDuplicate = 0 PS_STD_HANDLE_STATE.PsRequestDuplicate = 1 PS_STD_HANDLE_STATE.PsAlwaysDuplicate = 2 PS_STD_HANDLE_STATE.PsMaxStdHandleStates = 3 WHEA_ERROR_SEVERITY = v_enum() WHEA_ERROR_SEVERITY.WheaErrSevRecoverable = 0 WHEA_ERROR_SEVERITY.WheaErrSevFatal = 1 WHEA_ERROR_SEVERITY.WheaErrSevCorrected = 2 WHEA_ERROR_SEVERITY.WheaErrSevInformational = 3 REG_NOTIFY_CLASS = v_enum() REG_NOTIFY_CLASS.RegNtDeleteKey = 0 REG_NOTIFY_CLASS.RegNtPreDeleteKey = 1 REG_NOTIFY_CLASS.RegNtSetValueKey = 2 REG_NOTIFY_CLASS.RegNtPreSetValueKey = 3 REG_NOTIFY_CLASS.RegNtDeleteValueKey = 4 REG_NOTIFY_CLASS.RegNtPreDeleteValueKey = 5 REG_NOTIFY_CLASS.RegNtSetInformationKey = 6 REG_NOTIFY_CLASS.RegNtPreSetInformationKey = 7 REG_NOTIFY_CLASS.RegNtRenameKey = 8 REG_NOTIFY_CLASS.RegNtPreRenameKey = 9 REG_NOTIFY_CLASS.RegNtEnumerateKey = 10 REG_NOTIFY_CLASS.RegNtPreEnumerateKey = 11 REG_NOTIFY_CLASS.RegNtEnumerateValueKey = 12 REG_NOTIFY_CLASS.RegNtPreEnumerateValueKey = 13 REG_NOTIFY_CLASS.RegNtQueryKey = 14 REG_NOTIFY_CLASS.RegNtPreQueryKey = 15 REG_NOTIFY_CLASS.RegNtQueryValueKey = 16 REG_NOTIFY_CLASS.RegNtPreQueryValueKey = 17 REG_NOTIFY_CLASS.RegNtQueryMultipleValueKey = 18 REG_NOTIFY_CLASS.RegNtPreQueryMultipleValueKey = 19 REG_NOTIFY_CLASS.RegNtPreCreateKey = 20 REG_NOTIFY_CLASS.RegNtPostCreateKey = 21 REG_NOTIFY_CLASS.RegNtPreOpenKey = 22 REG_NOTIFY_CLASS.RegNtPostOpenKey = 23 REG_NOTIFY_CLASS.RegNtKeyHandleClose = 24 REG_NOTIFY_CLASS.RegNtPreKeyHandleClose = 25 REG_NOTIFY_CLASS.RegNtPostDeleteKey = 26 REG_NOTIFY_CLASS.RegNtPostSetValueKey = 27 REG_NOTIFY_CLASS.RegNtPostDeleteValueKey = 28 REG_NOTIFY_CLASS.RegNtPostSetInformationKey = 29 REG_NOTIFY_CLASS.RegNtPostRenameKey = 30 REG_NOTIFY_CLASS.RegNtPostEnumerateKey = 31 REG_NOTIFY_CLASS.RegNtPostEnumerateValueKey = 32 REG_NOTIFY_CLASS.RegNtPostQueryKey = 33 REG_NOTIFY_CLASS.RegNtPostQueryValueKey = 34 REG_NOTIFY_CLASS.RegNtPostQueryMultipleValueKey = 35 REG_NOTIFY_CLASS.RegNtPostKeyHandleClose = 36 REG_NOTIFY_CLASS.RegNtPreCreateKeyEx = 37 REG_NOTIFY_CLASS.RegNtPostCreateKeyEx = 38 REG_NOTIFY_CLASS.RegNtPreOpenKeyEx = 39 REG_NOTIFY_CLASS.RegNtPostOpenKeyEx = 40 REG_NOTIFY_CLASS.RegNtPreFlushKey = 41 REG_NOTIFY_CLASS.RegNtPostFlushKey = 42 REG_NOTIFY_CLASS.RegNtPreLoadKey = 43 REG_NOTIFY_CLASS.RegNtPostLoadKey = 44 REG_NOTIFY_CLASS.RegNtPreUnLoadKey = 45 REG_NOTIFY_CLASS.RegNtPostUnLoadKey = 46 REG_NOTIFY_CLASS.RegNtPreQueryKeySecurity = 47 REG_NOTIFY_CLASS.RegNtPostQueryKeySecurity = 48 REG_NOTIFY_CLASS.RegNtPreSetKeySecurity = 49 REG_NOTIFY_CLASS.RegNtPostSetKeySecurity = 50 REG_NOTIFY_CLASS.RegNtCallbackObjectContextCleanup = 51 REG_NOTIFY_CLASS.RegNtPreRestoreKey = 52 REG_NOTIFY_CLASS.RegNtPostRestoreKey = 53 REG_NOTIFY_CLASS.RegNtPreSaveKey = 54 REG_NOTIFY_CLASS.RegNtPostSaveKey = 55 REG_NOTIFY_CLASS.RegNtPreReplaceKey = 56 REG_NOTIFY_CLASS.RegNtPostReplaceKey = 57 REG_NOTIFY_CLASS.MaxRegNtNotifyClass = 58 DEVICE_RELATION_TYPE = v_enum() DEVICE_RELATION_TYPE.BusRelations = 0 DEVICE_RELATION_TYPE.EjectionRelations = 1 DEVICE_RELATION_TYPE.PowerRelations = 2 DEVICE_RELATION_TYPE.RemovalRelations = 3 DEVICE_RELATION_TYPE.TargetDeviceRelation = 4 DEVICE_RELATION_TYPE.SingleBusRelations = 5 DEVICE_RELATION_TYPE.TransportRelations = 6 FILE_INFORMATION_CLASS = v_enum() FILE_INFORMATION_CLASS.FileDirectoryInformation = 0 FILE_INFORMATION_CLASS.FileFullDirectoryInformation = 1 FILE_INFORMATION_CLASS.FileBothDirectoryInformation = 2 FILE_INFORMATION_CLASS.FileBasicInformation = 3 FILE_INFORMATION_CLASS.FileStandardInformation = 4 FILE_INFORMATION_CLASS.FileInternalInformation = 5 FILE_INFORMATION_CLASS.FileEaInformation = 6 FILE_INFORMATION_CLASS.FileAccessInformation = 7 FILE_INFORMATION_CLASS.FileNameInformation = 8 FILE_INFORMATION_CLASS.FileRenameInformation = 9 FILE_INFORMATION_CLASS.FileLinkInformation = 10 FILE_INFORMATION_CLASS.FileNamesInformation = 11 FILE_INFORMATION_CLASS.FileDispositionInformation = 12 FILE_INFORMATION_CLASS.FilePositionInformation = 13 FILE_INFORMATION_CLASS.FileFullEaInformation = 14 FILE_INFORMATION_CLASS.FileModeInformation = 15 FILE_INFORMATION_CLASS.FileAlignmentInformation = 16 FILE_INFORMATION_CLASS.FileAllInformation = 17 FILE_INFORMATION_CLASS.FileAllocationInformation = 18 FILE_INFORMATION_CLASS.FileEndOfFileInformation = 19 FILE_INFORMATION_CLASS.FileAlternateNameInformation = 20 FILE_INFORMATION_CLASS.FileStreamInformation = 21 FILE_INFORMATION_CLASS.FilePipeInformation = 22 FILE_INFORMATION_CLASS.FilePipeLocalInformation = 23 FILE_INFORMATION_CLASS.FilePipeRemoteInformation = 24 FILE_INFORMATION_CLASS.FileMailslotQueryInformation = 25 FILE_INFORMATION_CLASS.FileMailslotSetInformation = 26 FILE_INFORMATION_CLASS.FileCompressionInformation = 27 FILE_INFORMATION_CLASS.FileObjectIdInformation = 28 FILE_INFORMATION_CLASS.FileCompletionInformation = 29 FILE_INFORMATION_CLASS.FileMoveClusterInformation = 30 FILE_INFORMATION_CLASS.FileQuotaInformation = 31 FILE_INFORMATION_CLASS.FileReparsePointInformation = 32 FILE_INFORMATION_CLASS.FileNetworkOpenInformation = 33 FILE_INFORMATION_CLASS.FileAttributeTagInformation = 34 FILE_INFORMATION_CLASS.FileTrackingInformation = 35 FILE_INFORMATION_CLASS.FileIdBothDirectoryInformation = 36 FILE_INFORMATION_CLASS.FileIdFullDirectoryInformation = 37 FILE_INFORMATION_CLASS.FileValidDataLengthInformation = 38 FILE_INFORMATION_CLASS.FileShortNameInformation = 39 FILE_INFORMATION_CLASS.FileIoCompletionNotificationInformation = 40 FILE_INFORMATION_CLASS.FileIoStatusBlockRangeInformation = 41 FILE_INFORMATION_CLASS.FileIoPriorityHintInformation = 42 FILE_INFORMATION_CLASS.FileSfioReserveInformation = 43 FILE_INFORMATION_CLASS.FileSfioVolumeInformation = 44 FILE_INFORMATION_CLASS.FileHardLinkInformation = 45 FILE_INFORMATION_CLASS.FileProcessIdsUsingFileInformation = 46 FILE_INFORMATION_CLASS.FileNormalizedNameInformation = 47 FILE_INFORMATION_CLASS.FileNetworkPhysicalNameInformation = 48 FILE_INFORMATION_CLASS.FileIdGlobalTxDirectoryInformation = 49 FILE_INFORMATION_CLASS.FileIsRemoteDeviceInformation = 50 FILE_INFORMATION_CLASS.FileAttributeCacheInformation = 51 FILE_INFORMATION_CLASS.FileNumaNodeInformation = 52 FILE_INFORMATION_CLASS.FileStandardLinkInformation = 53 FILE_INFORMATION_CLASS.FileRemoteProtocolInformation = 54 FILE_INFORMATION_CLASS.FileMaximumInformation = 55 ALTERNATIVE_ARCHITECTURE_TYPE = v_enum() ALTERNATIVE_ARCHITECTURE_TYPE.StandardDesign = 0 ALTERNATIVE_ARCHITECTURE_TYPE.NEC98x86 = 1 ALTERNATIVE_ARCHITECTURE_TYPE.EndAlternatives = 2 BUS_QUERY_ID_TYPE = v_enum() BUS_QUERY_ID_TYPE.BusQueryDeviceID = 0 BUS_QUERY_ID_TYPE.BusQueryHardwareIDs = 1 BUS_QUERY_ID_TYPE.BusQueryCompatibleIDs = 2 BUS_QUERY_ID_TYPE.BusQueryInstanceID = 3 BUS_QUERY_ID_TYPE.BusQueryDeviceSerialNumber = 4 BUS_QUERY_ID_TYPE.BusQueryContainerID = 5 KOBJECTS = v_enum() KOBJECTS.EventNotificationObject = 0 KOBJECTS.EventSynchronizationObject = 1 KOBJECTS.MutantObject = 2 KOBJECTS.ProcessObject = 3 KOBJECTS.QueueObject = 4 KOBJECTS.SemaphoreObject = 5 KOBJECTS.ThreadObject = 6 KOBJECTS.GateObject = 7 KOBJECTS.TimerNotificationObject = 8 KOBJECTS.TimerSynchronizationObject = 9 KOBJECTS.Spare2Object = 10 KOBJECTS.Spare3Object = 11 KOBJECTS.Spare4Object = 12 KOBJECTS.Spare5Object = 13 KOBJECTS.Spare6Object = 14 KOBJECTS.Spare7Object = 15 KOBJECTS.Spare8Object = 16 KOBJECTS.Spare9Object = 17 KOBJECTS.ApcObject = 18 KOBJECTS.DpcObject = 19 KOBJECTS.DeviceQueueObject = 20 KOBJECTS.EventPairObject = 21 KOBJECTS.InterruptObject = 22 KOBJECTS.ProfileObject = 23 KOBJECTS.ThreadedDpcObject = 24 KOBJECTS.MaximumKernelObject = 25 NT_PRODUCT_TYPE = v_enum() NT_PRODUCT_TYPE.NtProductWinNt = 0 NT_PRODUCT_TYPE.NtProductLanManNt = 1 NT_PRODUCT_TYPE.NtProductServer = 2 DEVICE_POWER_STATE = v_enum() DEVICE_POWER_STATE.PowerDeviceUnspecified = 0 DEVICE_POWER_STATE.PowerDeviceD0 = 1 DEVICE_POWER_STATE.PowerDeviceD1 = 2 DEVICE_POWER_STATE.PowerDeviceD2 = 3 DEVICE_POWER_STATE.PowerDeviceD3 = 4 DEVICE_POWER_STATE.PowerDeviceMaximum = 5 WHEA_ERROR_SOURCE_TYPE = v_enum() WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeMCE = 0 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeCMC = 1 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeCPE = 2 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeNMI = 3 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypePCIe = 4 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeGeneric = 5 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeINIT = 6 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeBOOT = 7 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeSCIGeneric = 8 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFMCA = 9 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFCMC = 10 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFCPE = 11 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeMax = 12 PROC_HYPERVISOR_STATE = v_enum() PROC_HYPERVISOR_STATE.ProcHypervisorNone = 0 PROC_HYPERVISOR_STATE.ProcHypervisorPresent = 1 PROC_HYPERVISOR_STATE.ProcHypervisorPower = 2 RTL_GENERIC_COMPARE_RESULTS = v_enum() RTL_GENERIC_COMPARE_RESULTS.GenericLessThan = 0 RTL_GENERIC_COMPARE_RESULTS.GenericGreaterThan = 1 RTL_GENERIC_COMPARE_RESULTS.GenericEqual = 2 KWAIT_BLOCK_STATE = v_enum() KWAIT_BLOCK_STATE.WaitBlockBypassStart = 0 KWAIT_BLOCK_STATE.WaitBlockBypassComplete = 1 KWAIT_BLOCK_STATE.WaitBlockActive = 2 KWAIT_BLOCK_STATE.WaitBlockInactive = 3 KWAIT_BLOCK_STATE.WaitBlockAllStates = 4 PF_FILE_ACCESS_TYPE = v_enum() PF_FILE_ACCESS_TYPE.PfFileAccessTypeRead = 0 PF_FILE_ACCESS_TYPE.PfFileAccessTypeWrite = 1 PF_FILE_ACCESS_TYPE.PfFileAccessTypeMax = 2 PROCESSOR_CACHE_TYPE = v_enum() PROCESSOR_CACHE_TYPE.CacheUnified = 0 PROCESSOR_CACHE_TYPE.CacheInstruction = 1 PROCESSOR_CACHE_TYPE.CacheData = 2 PROCESSOR_CACHE_TYPE.CacheTrace = 3 PS_ATTRIBUTE_NUM = v_enum() PS_ATTRIBUTE_NUM.PsAttributeParentProcess = 0 PS_ATTRIBUTE_NUM.PsAttributeDebugObject = 1 PS_ATTRIBUTE_NUM.PsAttributeToken = 2 PS_ATTRIBUTE_NUM.PsAttributeClientId = 3 PS_ATTRIBUTE_NUM.PsAttributeTebAddress = 4 PS_ATTRIBUTE_NUM.PsAttributeImageName = 5 PS_ATTRIBUTE_NUM.PsAttributeImageInfo = 6 PS_ATTRIBUTE_NUM.PsAttributeMemoryReserve = 7 PS_ATTRIBUTE_NUM.PsAttributePriorityClass = 8 PS_ATTRIBUTE_NUM.PsAttributeErrorMode = 9 PS_ATTRIBUTE_NUM.PsAttributeStdHandleInfo = 10 PS_ATTRIBUTE_NUM.PsAttributeHandleList = 11 PS_ATTRIBUTE_NUM.PsAttributeGroupAffinity = 12 PS_ATTRIBUTE_NUM.PsAttributePreferredNode = 13 PS_ATTRIBUTE_NUM.PsAttributeIdealProcessor = 14 PS_ATTRIBUTE_NUM.PsAttributeUmsThread = 15 PS_ATTRIBUTE_NUM.PsAttributeExecuteOptions = 16 PS_ATTRIBUTE_NUM.PsAttributeMax = 17 MCA_EXCEPTION_TYPE = v_enum() MCA_EXCEPTION_TYPE.HAL_MCE_RECORD = 0 MCA_EXCEPTION_TYPE.HAL_MCA_RECORD = 1 EVENT_TYPE = v_enum() EVENT_TYPE.NotificationEvent = 0 EVENT_TYPE.SynchronizationEvent = 1 TP_CALLBACK_PRIORITY = v_enum() TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_HIGH = 0 TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_NORMAL = 1 TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_LOW = 2 TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_INVALID = 3 FSINFOCLASS = v_enum() FSINFOCLASS.FileFsVolumeInformation = 0 FSINFOCLASS.FileFsLabelInformation = 1 FSINFOCLASS.FileFsSizeInformation = 2 FSINFOCLASS.FileFsDeviceInformation = 3 FSINFOCLASS.FileFsAttributeInformation = 4 FSINFOCLASS.FileFsControlInformation = 5 FSINFOCLASS.FileFsFullSizeInformation = 6 FSINFOCLASS.FileFsObjectIdInformation = 7 FSINFOCLASS.FileFsDriverPathInformation = 8 FSINFOCLASS.FileFsVolumeFlagsInformation = 9 FSINFOCLASS.FileFsMaximumInformation = 10 INTERLOCKED_RESULT = v_enum() INTERLOCKED_RESULT.ResultNegative = 0 INTERLOCKED_RESULT.ResultZero = 1 INTERLOCKED_RESULT.ResultPositive = 2 WORKING_SET_TYPE = v_enum() WORKING_SET_TYPE.WorkingSetTypeUser = 0 WORKING_SET_TYPE.WorkingSetTypeSession = 1 WORKING_SET_TYPE.WorkingSetTypeSystemTypes = 2 WORKING_SET_TYPE.WorkingSetTypeSystemCache = 3 WORKING_SET_TYPE.WorkingSetTypePagedPool = 4 WORKING_SET_TYPE.WorkingSetTypeSystemPtes = 5 WORKING_SET_TYPE.WorkingSetTypeMaximum = 6 POOL_TYPE = v_enum() POOL_TYPE.NonPagedPool = 0 POOL_TYPE.PagedPool = 1 POOL_TYPE.NonPagedPoolMustSucceed = 2 POOL_TYPE.DontUseThisType = 3 POOL_TYPE.NonPagedPoolCacheAligned = 4 POOL_TYPE.PagedPoolCacheAligned = 5 POOL_TYPE.NonPagedPoolCacheAlignedMustS = 6 POOL_TYPE.MaxPoolType = 7 POOL_TYPE.NonPagedPoolSession = 8 POOL_TYPE.PagedPoolSession = 9 POOL_TYPE.NonPagedPoolMustSucceedSession = 10 POOL_TYPE.DontUseThisTypeSession = 11 POOL_TYPE.NonPagedPoolCacheAlignedSession = 12 POOL_TYPE.PagedPoolCacheAlignedSession = 13 POOL_TYPE.NonPagedPoolCacheAlignedMustSSession = 14 IO_PRIORITY_HINT = v_enum() IO_PRIORITY_HINT.IoPriorityVeryLow = 0 IO_PRIORITY_HINT.IoPriorityLow = 1 IO_PRIORITY_HINT.IoPriorityNormal = 2 IO_PRIORITY_HINT.IoPriorityHigh = 3 IO_PRIORITY_HINT.IoPriorityCritical = 4 IO_PRIORITY_HINT.MaxIoPriorityTypes = 5 MODE = v_enum() MODE.KernelMode = 0 MODE.UserMode = 1 MODE.MaximumMode = 2 FS_FILTER_SECTION_SYNC_TYPE = v_enum() FS_FILTER_SECTION_SYNC_TYPE.SyncTypeOther = 0 FS_FILTER_SECTION_SYNC_TYPE.SyncTypeCreateSection = 1 OB_OPEN_REASON = v_enum() OB_OPEN_REASON.ObCreateHandle = 0 OB_OPEN_REASON.ObOpenHandle = 1 OB_OPEN_REASON.ObDuplicateHandle = 2 OB_OPEN_REASON.ObInheritHandle = 3 OB_OPEN_REASON.ObMaxOpenReason = 4 HEAP_FAILURE_TYPE = v_enum() HEAP_FAILURE_TYPE.heap_failure_internal = 0 HEAP_FAILURE_TYPE.heap_failure_unknown = 1 HEAP_FAILURE_TYPE.heap_failure_generic = 2 HEAP_FAILURE_TYPE.heap_failure_entry_corruption = 3 HEAP_FAILURE_TYPE.heap_failure_multiple_entries_corruption = 4 HEAP_FAILURE_TYPE.heap_failure_virtual_block_corruption = 5 HEAP_FAILURE_TYPE.heap_failure_buffer_overrun = 6 HEAP_FAILURE_TYPE.heap_failure_buffer_underrun = 7 HEAP_FAILURE_TYPE.heap_failure_block_not_busy = 8 HEAP_FAILURE_TYPE.heap_failure_invalid_argument = 9 HEAP_FAILURE_TYPE.heap_failure_usage_after_free = 10 HEAP_FAILURE_TYPE.heap_failure_cross_heap_operation = 11 HEAP_FAILURE_TYPE.heap_failure_freelists_corruption = 12 HEAP_FAILURE_TYPE.heap_failure_listentry_corruption = 13 PS_IFEO_KEY_STATE = v_enum() PS_IFEO_KEY_STATE.PsReadIFEOAllValues = 0 PS_IFEO_KEY_STATE.PsSkipIFEODebugger = 1 PS_IFEO_KEY_STATE.PsSkipAllIFEO = 2 PS_IFEO_KEY_STATE.PsMaxIFEOKeyStates = 3 POWER_STATE_TYPE = v_enum() POWER_STATE_TYPE.SystemPowerState = 0 POWER_STATE_TYPE.DevicePowerState = 1 IRQ_PRIORITY = v_enum() IRQ_PRIORITY.IrqPriorityUndefined = 0 IRQ_PRIORITY.IrqPriorityLow = 1 IRQ_PRIORITY.IrqPriorityNormal = 2 IRQ_PRIORITY.IrqPriorityHigh = 3 KWAIT_STATE = v_enum() KWAIT_STATE.WaitInProgress = 0 KWAIT_STATE.WaitCommitted = 1 KWAIT_STATE.WaitAborted = 2 KWAIT_STATE.MaximumWaitState = 3 LSA_FOREST_TRUST_RECORD_TYPE = v_enum() LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName = 0 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx = 1 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo = 2 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustRecordTypeLast = 3 IO_ALLOCATION_ACTION = v_enum() IO_ALLOCATION_ACTION.KeepObject = 0 IO_ALLOCATION_ACTION.DeallocateObject = 1 IO_ALLOCATION_ACTION.DeallocateObjectKeepRegisters = 2 EXCEPTION_DISPOSITION = v_enum() EXCEPTION_DISPOSITION.ExceptionContinueExecution = 0 EXCEPTION_DISPOSITION.ExceptionContinueSearch = 1 EXCEPTION_DISPOSITION.ExceptionNestedException = 2 EXCEPTION_DISPOSITION.ExceptionCollidedUnwind = 3 SECURITY_OPERATION_CODE = v_enum() SECURITY_OPERATION_CODE.SetSecurityDescriptor = 0 SECURITY_OPERATION_CODE.QuerySecurityDescriptor = 1 SECURITY_OPERATION_CODE.DeleteSecurityDescriptor = 2 SECURITY_OPERATION_CODE.AssignSecurityDescriptor = 3 PP_NPAGED_LOOKASIDE_NUMBER = v_enum() PP_NPAGED_LOOKASIDE_NUMBER.LookasideSmallIrpList = 0 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMediumIrpList = 1 PP_NPAGED_LOOKASIDE_NUMBER.LookasideLargeIrpList = 2 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMdlList = 3 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCreateInfoList = 4 PP_NPAGED_LOOKASIDE_NUMBER.LookasideNameBufferList = 5 PP_NPAGED_LOOKASIDE_NUMBER.LookasideTwilightList = 6 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCompletionList = 7 PP_NPAGED_LOOKASIDE_NUMBER.LookasideScratchBufferList = 8 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMaximumList = 9 WHEA_ERROR_PACKET_DATA_FORMAT = v_enum() WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatIPFSalRecord = 0 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatXPFMCA = 1 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatMemory = 2 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIExpress = 3 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatNMIPort = 4 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIXBus = 5 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIXDevice = 6 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatGeneric = 7 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatMax = 8 FS_FILTER_STREAM_FO_NOTIFICATION_TYPE = v_enum() FS_FILTER_STREAM_FO_NOTIFICATION_TYPE.NotifyTypeCreate = 0 FS_FILTER_STREAM_FO_NOTIFICATION_TYPE.NotifyTypeRetired = 1 DISPLAYCONFIG_SCANLINE_ORDERING = v_enum() DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = 0 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = 1 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = 2 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = 3 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = 4 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32 = 5 SECURITY_IMPERSONATION_LEVEL = v_enum() SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous = 0 SECURITY_IMPERSONATION_LEVEL.SecurityIdentification = 1 SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation = 2 SECURITY_IMPERSONATION_LEVEL.SecurityDelegation = 3 DEVICE_USAGE_NOTIFICATION_TYPE = v_enum() DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeUndefined = 0 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypePaging = 1 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeHibernation = 2 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeDumpFile = 3 POWER_ACTION = v_enum() POWER_ACTION.PowerActionNone = 0 POWER_ACTION.PowerActionReserved = 1 POWER_ACTION.PowerActionSleep = 2 POWER_ACTION.PowerActionHibernate = 3 POWER_ACTION.PowerActionShutdown = 4 POWER_ACTION.PowerActionShutdownReset = 5 POWER_ACTION.PowerActionShutdownOff = 6 POWER_ACTION.PowerActionWarmEject = 7 INTERFACE_TYPE = v_enum() INTERFACE_TYPE.InterfaceTypeUndefined = 0 INTERFACE_TYPE.Internal = 1 INTERFACE_TYPE.Isa = 2 INTERFACE_TYPE.Eisa = 3 INTERFACE_TYPE.MicroChannel = 4 INTERFACE_TYPE.TurboChannel = 5 INTERFACE_TYPE.PCIBus = 6 INTERFACE_TYPE.VMEBus = 7 INTERFACE_TYPE.NuBus = 8 INTERFACE_TYPE.PCMCIABus = 9 INTERFACE_TYPE.CBus = 10 INTERFACE_TYPE.MPIBus = 11 INTERFACE_TYPE.MPSABus = 12 INTERFACE_TYPE.ProcessorInternal = 13 INTERFACE_TYPE.InternalPowerBus = 14 INTERFACE_TYPE.PNPISABus = 15 INTERFACE_TYPE.PNPBus = 16 INTERFACE_TYPE.Vmcs = 17 INTERFACE_TYPE.MaximumInterfaceType = 18 PS_RESOURCE_TYPE = v_enum() PS_RESOURCE_TYPE.PsResourceNonPagedPool = 0 PS_RESOURCE_TYPE.PsResourcePagedPool = 1 PS_RESOURCE_TYPE.PsResourcePageFile = 2 PS_RESOURCE_TYPE.PsResourceWorkingSet = 3 PS_RESOURCE_TYPE.PsResourceCpuRate = 4 PS_RESOURCE_TYPE.PsResourceMax = 5 MM_PAGE_ACCESS_TYPE = v_enum() MM_PAGE_ACCESS_TYPE.MmPteAccessType = 0 MM_PAGE_ACCESS_TYPE.MmCcReadAheadType = 1 MM_PAGE_ACCESS_TYPE.MmPfnRepurposeType = 2 MM_PAGE_ACCESS_TYPE.MmMaximumPageAccessType = 3 WHEA_ERROR_TYPE = v_enum() WHEA_ERROR_TYPE.WheaErrTypeProcessor = 0 WHEA_ERROR_TYPE.WheaErrTypeMemory = 1 WHEA_ERROR_TYPE.WheaErrTypePCIExpress = 2 WHEA_ERROR_TYPE.WheaErrTypeNMI = 3 WHEA_ERROR_TYPE.WheaErrTypePCIXBus = 4 WHEA_ERROR_TYPE.WheaErrTypePCIXDevice = 5 WHEA_ERROR_TYPE.WheaErrTypeGeneric = 6 HARDWARE_COUNTER_TYPE = v_enum() HARDWARE_COUNTER_TYPE.PMCCounter = 0 HARDWARE_COUNTER_TYPE.MaxHardwareCounterType = 1 ReplacesCorHdrNumericDefines = v_enum() ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY = 0 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED = 1 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY = 2 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED = 3 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = 4 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA = 5 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR_V2 = 6 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR = 7 ReplacesCorHdrNumericDefines.COR_VERSION_MINOR = 8 ReplacesCorHdrNumericDefines.COR_DELETED_NAME_LENGTH = 9 ReplacesCorHdrNumericDefines.COR_VTABLEGAP_NAME_LENGTH = 10 ReplacesCorHdrNumericDefines.NATIVE_TYPE_MAX_CB = 11 ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 12 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_METHODRVA = 13 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_EHRVA = 14 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_BASICBLOCK = 15 ReplacesCorHdrNumericDefines.COR_VTABLE_32BIT = 16 ReplacesCorHdrNumericDefines.COR_VTABLE_64BIT = 17 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED = 18 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = 19 ReplacesCorHdrNumericDefines.COR_VTABLE_CALL_MOST_DERIVED = 20 ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE = 21 ReplacesCorHdrNumericDefines.MAX_CLASS_NAME = 22 ReplacesCorHdrNumericDefines.MAX_PACKAGE_NAME = 23 SYSTEM_POWER_STATE = v_enum() SYSTEM_POWER_STATE.PowerSystemUnspecified = 0 SYSTEM_POWER_STATE.PowerSystemWorking = 1 SYSTEM_POWER_STATE.PowerSystemSleeping1 = 2 SYSTEM_POWER_STATE.PowerSystemSleeping2 = 3 SYSTEM_POWER_STATE.PowerSystemSleeping3 = 4 SYSTEM_POWER_STATE.PowerSystemHibernate = 5 SYSTEM_POWER_STATE.PowerSystemShutdown = 6 SYSTEM_POWER_STATE.PowerSystemMaximum = 7 MEMORY_CACHING_TYPE_ORIG = v_enum() MEMORY_CACHING_TYPE_ORIG.MmFrameBufferCached = 0 DEVICE_TEXT_TYPE = v_enum() DEVICE_TEXT_TYPE.DeviceTextDescription = 0 DEVICE_TEXT_TYPE.DeviceTextLocationInformation = 1 PS_CREATE_STATE = v_enum() PS_CREATE_STATE.PsCreateInitialState = 0 PS_CREATE_STATE.PsCreateFailOnFileOpen = 1 PS_CREATE_STATE.PsCreateFailOnSectionCreate = 2 PS_CREATE_STATE.PsCreateFailExeFormat = 3 PS_CREATE_STATE.PsCreateFailMachineMismatch = 4 PS_CREATE_STATE.PsCreateFailExeName = 5 PS_CREATE_STATE.PsCreateSuccess = 6 PS_CREATE_STATE.PsCreateMaximumStates = 7 class KEXECUTE_OPTIONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExecuteDisable = v_uint8() class IO_PRIORITY_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint32() self.ThreadPriority = v_uint32() self.PagePriority = v_uint32() self.IoPriority = v_uint32() class SID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.SubAuthorityCount = v_uint8() self.IdentifierAuthority = SID_IDENTIFIER_AUTHORITY() self.SubAuthority = v_bytes(size=4) # FIXME Unknown Array Type class WHEA_ERROR_PACKET_V2(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.Version = v_uint32() self.Length = v_uint32() self.Flags = WHEA_ERROR_PACKET_FLAGS() self.ErrorType = v_uint32() self.ErrorSeverity = v_uint32() self.ErrorSourceId = v_uint32() self.ErrorSourceType = v_uint32() self.NotifyType = GUID() self.Context = v_uint64() self.DataFormat = v_uint32() self.Reserved1 = v_uint32() self.DataOffset = v_uint32() self.DataLength = v_uint32() self.PshedDataOffset = v_uint32() self.PshedDataLength = v_uint32() class GROUP_AFFINITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mask = v_uint64() self.Group = v_uint16() self.Reserved = v_bytes(size=6) # FIXME Unknown Array Type class UMS_CONTROL_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class _unnamed_8000(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdType = v_uint32() class CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DosPath = UNICODE_STRING() self.Handle = v_ptr64() class KREQUEST_PACKET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentPacket = v_bytes(size=24) # FIXME Unknown Array Type self.WorkerRoutine = v_ptr64() class PERFINFO_GROUPMASK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Masks = v_bytes(size=32) # FIXME Unknown Array Type class HARDWARE_PTE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint64() class HANDLE_TABLE_ENTRY_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AuditMask = v_uint32() class SINGLE_LIST_ENTRY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_uint32() class _unnamed_10205(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length40 = v_uint32() self.Alignment40 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class _unnamed_9413(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Balance = v_uint64() class _unnamed_10201(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Priority = v_uint32() self.Reserved1 = v_uint32() self.Reserved2 = v_uint32() class PS_CPU_QUOTA_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.SessionId = v_uint32() self.CpuShareWeight = v_uint32() self.CapturedWeightData = PSP_CPU_SHARE_CAPTURED_WEIGHT_DATA() self.DuplicateInputMarker = v_uint32() self._pad0040 = v_bytes(size=28) self.CycleCredit = v_uint64() self.BlockCurrentGeneration = v_uint32() self.CpuCyclePercent = v_uint32() self.CyclesFinishedForCurrentGeneration = v_uint8() self._pad0080 = v_bytes(size=47) self.Cpu = v_uint8() class RTL_TRACE_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self._pad0008 = v_bytes(size=4) self.Database = v_ptr64() self.NextSegment = v_ptr64() self.TotalSize = v_uint64() self.SegmentStart = v_ptr64() self.SegmentEnd = v_ptr64() self.SegmentFree = v_ptr64() class CM_PARTIAL_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.PartialDescriptors = v_uint32() class DEVICE_CAPABILITIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.DeviceD1 = v_uint32() self.Address = v_uint32() self.UINumber = v_uint32() self.DeviceState = v_uint32() self.SystemWake = v_uint32() self.DeviceWake = v_uint32() self.D1Latency = v_uint32() self.D2Latency = v_uint32() self.D3Latency = v_uint32() class _unnamed_7991(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = v_uint8() class HEAP_FAILURE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint32() self.StructureSize = v_uint32() self.FailureType = v_uint32() self._pad0010 = v_bytes(size=4) self.HeapAddress = v_ptr64() self.Address = v_ptr64() self.Param1 = v_ptr64() self.Param2 = v_ptr64() self.Param3 = v_ptr64() self.PreviousBlock = v_ptr64() self.NextBlock = v_ptr64() self.ExpectedEncodedEntry = HEAP_ENTRY() self.ExpectedDecodedEntry = HEAP_ENTRY() self.StackTrace = v_bytes(size=256) # FIXME Unknown Array Type class RTL_BALANCED_LINKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Parent = v_ptr64() self.LeftChild = v_ptr64() self.RightChild = v_ptr64() self.Balance = v_uint8() self.Reserved = v_bytes(size=3) # FIXME Unknown Array Type class _unnamed_9396(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Generic = _unnamed_9633() class KPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.ProfileListHead = LIST_ENTRY() self.DirectoryTableBase = v_uint64() self.ThreadListHead = LIST_ENTRY() self.ProcessLock = v_uint64() self.Affinity = KAFFINITY_EX() self.ReadyListHead = LIST_ENTRY() self.SwapListEntry = SINGLE_LIST_ENTRY() self.ActiveProcessors = KAFFINITY_EX() self.AutoAlignment = v_uint32() self.BasePriority = v_uint8() self.QuantumReset = v_uint8() self.Visited = v_uint8() self.Unused3 = v_uint8() self.ThreadSeed = v_bytes(size=16) # FIXME Unknown Array Type self.IdealNode = v_bytes(size=8) # FIXME Unknown Array Type self.IdealGlobalNode = v_uint16() self.Flags = KEXECUTE_OPTIONS() self.Unused1 = v_uint8() self.Unused2 = v_uint32() self.Unused4 = v_uint32() self.StackCount = KSTACK_COUNT() self.ProcessListEntry = LIST_ENTRY() self.CycleTime = v_uint64() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.InstrumentationCallback = v_ptr64() self.LdtSystemDescriptor = KGDTENTRY64() self.LdtBaseAddress = v_ptr64() self.LdtProcessLock = KGUARDED_MUTEX() self.LdtFreeSelectorHint = v_uint16() self.LdtTableLength = v_uint16() class DEVICE_OBJECT_POWER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class HEAP_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint64() self.TagIndex = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.TagName = v_bytes(size=48) # FIXME Unknown Array Type class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Primary = v_uint32() class TP_CALLBACK_ENVIRON_V3(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint32() self._pad0008 = v_bytes(size=4) self.Pool = v_ptr64() self.CleanupGroup = v_ptr64() self.CleanupGroupCancelCallback = v_ptr64() self.RaceDll = v_ptr64() self.ActivationContext = v_ptr64() self.FinalizationCallback = v_ptr64() self.u = _unnamed_5516() self.CallbackPriority = v_uint32() self.Size = v_uint32() class _unnamed_7904(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.StartSid = v_ptr64() self.SidList = v_ptr64() self.SidListLength = v_uint32() class WHEA_ERROR_PACKET_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PreviousError = v_uint32() class ALPC_PROCESS_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = EX_PUSH_LOCK() self.ViewListHead = LIST_ENTRY() self.PagedPoolQuotaCache = v_uint64() class OBJECT_HANDLE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HandleAttributes = v_uint32() self.GrantedAccess = v_uint32() class _unnamed_7861(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OutputBufferLength = v_uint32() self._pad0008 = v_bytes(size=4) self.InputBufferLength = v_uint32() self._pad0010 = v_bytes(size=4) self.FsControlCode = v_uint32() self._pad0018 = v_bytes(size=4) self.Type3InputBuffer = v_ptr64() class PROC_PERF_DOMAIN(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Link = LIST_ENTRY() self.Master = v_ptr64() self.Members = KAFFINITY_EX() self.FeedbackHandler = v_ptr64() self.GetFFHThrottleState = v_ptr64() self.BoostPolicyHandler = v_ptr64() self.PerfSelectionHandler = v_ptr64() self.PerfHandler = v_ptr64() self.Processors = v_ptr64() self.PerfChangeTime = v_uint64() self.ProcessorCount = v_uint32() self.PreviousFrequencyMhz = v_uint32() self.CurrentFrequencyMhz = v_uint32() self.PreviousFrequency = v_uint32() self.CurrentFrequency = v_uint32() self.CurrentPerfContext = v_uint32() self.DesiredFrequency = v_uint32() self.MaxFrequency = v_uint32() self.MinPerfPercent = v_uint32() self.MinThrottlePercent = v_uint32() self.MaxPercent = v_uint32() self.MinPercent = v_uint32() self.ConstrainedMaxPercent = v_uint32() self.ConstrainedMinPercent = v_uint32() self.Coordination = v_uint8() self._pad00b4 = v_bytes(size=3) self.PerfChangeIntervalCount = v_uint32() class XSTATE_CONFIGURATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EnabledFeatures = v_uint64() self.Size = v_uint32() self.OptimizedSave = v_uint32() self.Features = v_uint32() class PS_CLIENT_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ImpersonationData = v_uint64() class RTL_AVL_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BalancedRoot = RTL_BALANCED_LINKS() self.OrderedPointer = v_ptr64() self.WhichOrderedElement = v_uint32() self.NumberGenericTableElements = v_uint32() self.DepthOfTree = v_uint32() self._pad0038 = v_bytes(size=4) self.RestartKey = v_ptr64() self.DeleteCount = v_uint32() self._pad0048 = v_bytes(size=4) self.CompareRoutine = v_ptr64() self.AllocateRoutine = v_ptr64() self.FreeRoutine = v_ptr64() self.TableContext = v_ptr64() class RTL_TRACE_DATABASE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Flags = v_uint32() self.Tag = v_uint32() self._pad0010 = v_bytes(size=4) self.SegmentList = v_ptr64() self.MaximumSize = v_uint64() self.CurrentSize = v_uint64() self.Owner = v_ptr64() self.Lock = RTL_CRITICAL_SECTION() self.NoOfBuckets = v_uint32() self._pad0060 = v_bytes(size=4) self.Buckets = v_ptr64() self.HashFunction = v_ptr64() self.NoOfTraces = v_uint64() self.NoOfHits = v_uint64() self.HashCounter = v_bytes(size=64) # FIXME Unknown Array Type class OWNER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwnerThread = v_uint64() self.IoPriorityBoosted = v_uint32() class DEVOBJ_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self._pad0008 = v_bytes(size=4) self.DeviceObject = v_ptr64() self.PowerFlags = v_uint32() self._pad0018 = v_bytes(size=4) self.Dope = v_ptr64() self.ExtensionFlags = v_uint32() self._pad0028 = v_bytes(size=4) self.DeviceNode = v_ptr64() self.AttachedTo = v_ptr64() self.StartIoCount = v_uint32() self.StartIoKey = v_uint32() self.StartIoFlags = v_uint32() self._pad0048 = v_bytes(size=4) self.Vpb = v_ptr64() self.DependentList = LIST_ENTRY() self.ProviderList = LIST_ENTRY() class HEAP_LOCAL_SEGMENT_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Hint = v_ptr64() self.ActiveSubsegment = v_ptr64() self.CachedItems = v_bytes(size=128) # FIXME Unknown Array Type self.SListHeader = SLIST_HEADER() self.Counters = HEAP_BUCKET_COUNTERS() self.LocalData = v_ptr64() self.LastOpSequence = v_uint32() self.BucketIndex = v_uint16() self.LastUsed = v_uint16() class _unnamed_8005(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceTextType = v_uint32() self._pad0008 = v_bytes(size=4) self.LocaleId = v_uint32() class HEAP_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalMemoryReserved = v_uint64() self.TotalMemoryCommitted = v_uint64() self.TotalMemoryLargeUCR = v_uint64() self.TotalSizeInVirtualBlocks = v_uint64() self.TotalSegments = v_uint32() self.TotalUCRs = v_uint32() self.CommittOps = v_uint32() self.DeCommitOps = v_uint32() self.LockAcquires = v_uint32() self.LockCollisions = v_uint32() self.CommitRate = v_uint32() self.DecommittRate = v_uint32() self.CommitFailures = v_uint32() self.InBlockCommitFailures = v_uint32() self.CompactHeapCalls = v_uint32() self.CompactedUCRs = v_uint32() self.AllocAndFreeOps = v_uint32() self.InBlockDeccommits = v_uint32() self.InBlockDeccomitSize = v_uint64() self.HighWatermarkSize = v_uint64() self.LastPolledSize = v_uint64() class MAILSLOT_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MailslotQuota = v_uint32() self.MaximumMessageSize = v_uint32() self.ReadTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class FS_FILTER_CALLBACK_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbackData = v_uint32() self.Operation = v_uint8() self.Reserved = v_uint8() self._pad0008 = v_bytes(size=2) self.DeviceObject = v_ptr64() self.FileObject = v_ptr64() self.Parameters = FS_FILTER_PARAMETERS() class REQUEST_MAILBOX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() self.RequestSummary = v_uint64() self.RequestPacket = KREQUEST_PACKET() class PPM_IDLE_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DomainMembers = KAFFINITY_EX() self.IdleCheck = v_ptr64() self.IdleHandler = v_ptr64() self.Context = v_ptr64() self.Latency = v_uint32() self.Power = v_uint32() self.TimeCheck = v_uint32() self.StateFlags = v_uint32() self.PromotePercent = v_uint8() self.DemotePercent = v_uint8() self.PromotePercentBase = v_uint8() self.DemotePercentBase = v_uint8() self.StateType = v_uint8() class ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OperationID = LUID() self.SecurityEvaluated = v_uint8() self.GenerateAudit = v_uint8() self.GenerateOnClose = v_uint8() self.PrivilegesAllocated = v_uint8() self.Flags = v_uint32() self.RemainingDesiredAccess = v_uint32() self.PreviouslyGrantedAccess = v_uint32() self.OriginalDesiredAccess = v_uint32() self._pad0020 = v_bytes(size=4) self.SubjectSecurityContext = SECURITY_SUBJECT_CONTEXT() self.SecurityDescriptor = v_ptr64() self.AuxData = v_ptr64() self.Privileges = _unnamed_7557() self.AuditPrivileges = v_uint8() self._pad0080 = v_bytes(size=3) self.ObjectName = UNICODE_STRING() self.ObjectTypeName = UNICODE_STRING() class FILE_STANDARD_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.NumberOfLinks = v_uint32() self.DeletePending = v_uint8() self.Directory = v_uint8() class _unnamed_9633(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length = v_uint32() class PROC_IDLE_ACCOUNTING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StateCount = v_uint32() self.TotalTransitions = v_uint32() self.ResetCount = v_uint32() self._pad0010 = v_bytes(size=4) self.StartTime = v_uint64() self.BucketLimits = v_bytes(size=128) # FIXME Unknown Array Type self.State = v_bytes(size=128) # FIXME Unknown Array Type class _unnamed_9636(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint16() self.Group = v_uint16() self.Vector = v_uint32() self.Affinity = v_uint64() class GDI_TEB_BATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint32() self._pad0008 = v_bytes(size=4) self.HDC = v_uint64() self.Buffer = v_bytes(size=1240) # FIXME Unknown Array Type class THREAD_PERFORMANCE_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.ProcessorNumber = PROCESSOR_NUMBER() self.ContextSwitches = v_uint32() self.HwCountersCount = v_uint32() self.UpdateCount = v_uint64() self.WaitReasonBitMap = v_uint64() self.HardwareCounters = v_uint64() self.CycleTime = COUNTER_READING() self.HwCounters = COUNTER_READING() class PAGEFAULT_HISTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class ECP_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class SECTION_OBJECT_POINTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSectionObject = v_ptr64() self.SharedCacheMap = v_ptr64() self.ImageSectionObject = v_ptr64() class MDL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() self.Size = v_uint16() self.MdlFlags = v_uint16() self._pad0010 = v_bytes(size=4) self.Process = v_ptr64() self.MappedSystemVa = v_ptr64() self.StartVa = v_ptr64() self.ByteCount = v_uint32() self.ByteOffset = v_uint32() class KTRAP_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P1Home = v_uint64() self.P2Home = v_uint64() self.P3Home = v_uint64() self.P4Home = v_uint64() self.P5 = v_uint64() self.PreviousMode = v_uint8() self.PreviousIrql = v_uint8() self.FaultIndicator = v_uint8() self.ExceptionActive = v_uint8() self.MxCsr = v_uint32() self.Rax = v_uint64() self.Rcx = v_uint64() self.Rdx = v_uint64() self.R8 = v_uint64() self.R9 = v_uint64() self.R10 = v_uint64() self.R11 = v_uint64() self.GsBase = v_uint64() self.Xmm0 = M128A() self.Xmm1 = M128A() self.Xmm2 = M128A() self.Xmm3 = M128A() self.Xmm4 = M128A() self.Xmm5 = M128A() self.FaultAddress = v_uint64() self.Dr0 = v_uint64() self.Dr1 = v_uint64() self.Dr2 = v_uint64() self.Dr3 = v_uint64() self.Dr6 = v_uint64() self.Dr7 = v_uint64() self.DebugControl = v_uint64() self.LastBranchToRip = v_uint64() self.LastBranchFromRip = v_uint64() self.LastExceptionToRip = v_uint64() self.LastExceptionFromRip = v_uint64() self.SegDs = v_uint16() self.SegEs = v_uint16() self.SegFs = v_uint16() self.SegGs = v_uint16() self.TrapFrame = v_uint64() self.Rbx = v_uint64() self.Rdi = v_uint64() self.Rsi = v_uint64() self.Rbp = v_uint64() self.ErrorCode = v_uint64() self.Rip = v_uint64() self.SegCs = v_uint16() self.Fill0 = v_uint8() self.Logging = v_uint8() self.Fill1 = v_bytes(size=4) # FIXME Unknown Array Type self.EFlags = v_uint32() self.Fill2 = v_uint32() self.Rsp = v_uint64() self.SegSs = v_uint16() self.Fill3 = v_uint16() self.CodePatchCycle = v_uint32() class MCI_ADDR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_uint32() self.Reserved = v_uint32() class IO_TIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.TimerFlag = v_uint16() self._pad0008 = v_bytes(size=4) self.TimerList = LIST_ENTRY() self.TimerRoutine = v_ptr64() self.Context = v_ptr64() self.DeviceObject = v_ptr64() class WHEA_REVISION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinorRevision = v_uint8() self.MajorRevision = v_uint8() class TP_CLEANUP_GROUP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class PROC_IDLE_SNAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Time = v_uint64() self.Idle = v_uint64() class _unnamed_7700(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceQueueEntry = KDEVICE_QUEUE_ENTRY() self._pad0020 = v_bytes(size=8) self.Thread = v_ptr64() self.AuxiliaryBuffer = v_ptr64() self.ListEntry = LIST_ENTRY() self.CurrentStackLocation = v_ptr64() self.OriginalFileObject = v_ptr64() class SECURITY_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.Sbz1 = v_uint8() self.Control = v_uint16() self._pad0008 = v_bytes(size=4) self.Owner = v_ptr64() self.Group = v_ptr64() self.Sacl = v_ptr64() self.Dacl = v_ptr64() class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SectionOffset = v_uint32() self.SectionLength = v_uint32() self.Revision = WHEA_REVISION() self.ValidBits = WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS() self.Reserved = v_uint8() self.Flags = WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS() self.SectionType = GUID() self.FRUId = GUID() self.SectionSeverity = v_uint32() self.FRUText = v_bytes(size=20) # FIXME Unknown Array Type class OBJECT_TYPE_INITIALIZER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.ObjectTypeFlags = v_uint8() self._pad0004 = v_bytes(size=1) self.ObjectTypeCode = v_uint32() self.InvalidAttributes = v_uint32() self.GenericMapping = GENERIC_MAPPING() self.ValidAccessMask = v_uint32() self.RetainAccess = v_uint32() self.PoolType = v_uint32() self.DefaultPagedPoolCharge = v_uint32() self.DefaultNonPagedPoolCharge = v_uint32() self.DumpProcedure = v_ptr64() self.OpenProcedure = v_ptr64() self.CloseProcedure = v_ptr64() self.DeleteProcedure = v_ptr64() self.ParseProcedure = v_ptr64() self.SecurityProcedure = v_ptr64() self.QueryNameProcedure = v_ptr64() self.OkayToCloseProcedure = v_ptr64() class TP_DIRECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Callback = v_ptr64() self.NumaNode = v_uint32() self.IdealProcessor = v_uint8() class XSTATE_SAVE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Prev = v_ptr64() self.Thread = v_ptr64() self.Level = v_uint8() self._pad0018 = v_bytes(size=7) self.XStateContext = XSTATE_CONTEXT() class HEAP_ENTRY_EXTRA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocatorBackTraceIndex = v_uint16() self.TagIndex = v_uint16() self._pad0008 = v_bytes(size=4) self.Settable = v_uint64() class HEAP_PSEUDO_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint64() class PAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() class RTL_BITMAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfBitMap = v_uint32() self._pad0008 = v_bytes(size=4) self.Buffer = v_ptr64() class LARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class NPAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() class _unnamed_7557(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InitialPrivilegeSet = INITIAL_PRIVILEGE_SET() class _unnamed_7828(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.FileInformationClass = v_uint32() class _unnamed_7825(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.CompletionFilter = v_uint32() class _unnamed_5486(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class VPB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Flags = v_uint16() self.VolumeLabelLength = v_uint16() self.DeviceObject = v_ptr64() self.RealDevice = v_ptr64() self.SerialNumber = v_uint32() self.ReferenceCount = v_uint32() self.VolumeLabel = v_bytes(size=64) # FIXME Unknown Array Type class PP_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P = v_ptr64() self.L = v_ptr64() class OBJECT_NAME_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = UNICODE_STRING() class IO_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.Descriptors = v_uint32() class KUSER_SHARED_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TickCountLowDeprecated = v_uint32() self.TickCountMultiplier = v_uint32() self.InterruptTime = KSYSTEM_TIME() self.SystemTime = KSYSTEM_TIME() self.TimeZoneBias = KSYSTEM_TIME() self.ImageNumberLow = v_uint16() self.ImageNumberHigh = v_uint16() self.NtSystemRoot = v_bytes(size=520) # FIXME Unknown Array Type self.MaxStackTraceDepth = v_uint32() self.CryptoExponent = v_uint32() self.TimeZoneId = v_uint32() self.LargePageMinimum = v_uint32() self.Reserved2 = v_bytes(size=28) # FIXME Unknown Array Type self.NtProductType = v_uint32() self.ProductTypeIsValid = v_uint8() self._pad026c = v_bytes(size=3) self.NtMajorVersion = v_uint32() self.NtMinorVersion = v_uint32() self.ProcessorFeatures = v_bytes(size=64) # FIXME Unknown Array Type self.Reserved1 = v_uint32() self.Reserved3 = v_uint32() self.TimeSlip = v_uint32() self.AlternativeArchitecture = v_uint32() self.AltArchitecturePad = v_bytes(size=4) # FIXME Unknown Array Type self.SystemExpirationDate = LARGE_INTEGER() self.SuiteMask = v_uint32() self.KdDebuggerEnabled = v_uint8() self.NXSupportPolicy = v_uint8() self._pad02d8 = v_bytes(size=2) self.ActiveConsoleId = v_uint32() self.DismountCount = v_uint32() self.ComPlusPackage = v_uint32() self.LastSystemRITEventTickCount = v_uint32() self.NumberOfPhysicalPages = v_uint32() self.SafeBootMode = v_uint8() self.TscQpcData = v_uint8() self.TscQpcPad = v_bytes(size=2) # FIXME Unknown Array Type self.SharedDataFlags = v_uint32() self.DataFlagsPad = v_bytes(size=4) # FIXME Unknown Array Type self.TestRetInstruction = v_uint64() self.SystemCall = v_uint32() self.SystemCallReturn = v_uint32() self.SystemCallPad = v_bytes(size=24) # FIXME Unknown Array Type self.TickCount = KSYSTEM_TIME() self.TickCountPad = v_bytes(size=4) # FIXME Unknown Array Type self.Cookie = v_uint32() self.CookiePad = v_bytes(size=4) # FIXME Unknown Array Type self.ConsoleSessionForegroundProcessId = v_uint64() self.Wow64SharedInformation = v_bytes(size=64) # FIXME Unknown Array Type self.UserModeGlobalLogger = v_bytes(size=32) # FIXME Unknown Array Type self.ImageFileExecutionOptions = v_uint32() self.LangGenerationCount = v_uint32() self.Reserved5 = v_uint64() self.InterruptTimeBias = v_uint64() self.TscQpcBias = v_uint64() self.ActiveProcessorCount = v_uint32() self.ActiveGroupCount = v_uint16() self.Reserved4 = v_uint16() self.AitSamplingValue = v_uint32() self.AppCompatFlag = v_uint32() self.SystemDllNativeRelocation = v_uint64() self.SystemDllWowRelocation = v_uint32() self.XStatePad = v_bytes(size=4) # FIXME Unknown Array Type self.XState = XSTATE_CONFIGURATION() class SYSTEM_POWER_STATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved1 = v_uint32() class _unnamed_10186(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinimumVector = v_uint32() self.MaximumVector = v_uint32() self.AffinityPolicy = v_uint16() self.Group = v_uint16() self.PriorityPolicy = v_uint32() self.TargetedProcessors = v_uint64() class FS_FILTER_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AcquireForModifiedPageWriter = _unnamed_9724() class HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.SegmentSignature = v_uint32() self.SegmentFlags = v_uint32() self.SegmentListEntry = LIST_ENTRY() self.Heap = v_ptr64() self.BaseAddress = v_ptr64() self.NumberOfPages = v_uint32() self._pad0040 = v_bytes(size=4) self.FirstEntry = v_ptr64() self.LastValidEntry = v_ptr64() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.SegmentAllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self._pad0060 = v_bytes(size=4) self.UCRSegmentList = LIST_ENTRY() self.Flags = v_uint32() self.ForceFlags = v_uint32() self.CompatibilityFlags = v_uint32() self.EncodeFlagMask = v_uint32() self.Encoding = HEAP_ENTRY() self.PointerKey = v_uint64() self.Interceptor = v_uint32() self.VirtualMemoryThreshold = v_uint32() self.Signature = v_uint32() self._pad00a8 = v_bytes(size=4) self.SegmentReserve = v_uint64() self.SegmentCommit = v_uint64() self.DeCommitFreeBlockThreshold = v_uint64() self.DeCommitTotalFreeThreshold = v_uint64() self.TotalFreeSize = v_uint64() self.MaximumAllocationSize = v_uint64() self.ProcessHeapsListIndex = v_uint16() self.HeaderValidateLength = v_uint16() self._pad00e0 = v_bytes(size=4) self.HeaderValidateCopy = v_ptr64() self.NextAvailableTagIndex = v_uint16() self.MaximumTagIndex = v_uint16() self._pad00f0 = v_bytes(size=4) self.TagEntries = v_ptr64() self.UCRList = LIST_ENTRY() self.AlignRound = v_uint64() self.AlignMask = v_uint64() self.VirtualAllocdBlocks = LIST_ENTRY() self.SegmentList = LIST_ENTRY() self.AllocatorBackTraceIndex = v_uint16() self._pad013c = v_bytes(size=2) self.NonDedicatedListLength = v_uint32() self.BlocksIndex = v_ptr64() self.UCRIndex = v_ptr64() self.PseudoTagEntries = v_ptr64() self.FreeLists = LIST_ENTRY() self.LockVariable = v_ptr64() self.CommitRoutine = v_ptr64() self.FrontEndHeap = v_ptr64() self.FrontHeapLockCount = v_uint16() self.FrontEndHeapType = v_uint8() self._pad0188 = v_bytes(size=5) self.Counters = HEAP_COUNTERS() self.TuningParameters = HEAP_TUNING_PARAMETERS() class IO_STATUS_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self._pad0008 = v_bytes(size=4) self.Information = v_uint64() class PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class CM_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = v_uint32() class EPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pcb = KPROCESS() self.ProcessLock = EX_PUSH_LOCK() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.RundownProtect = EX_RUNDOWN_REF() self.UniqueProcessId = v_ptr64() self.ActiveProcessLinks = LIST_ENTRY() self.ProcessQuotaUsage = v_bytes(size=16) # FIXME Unknown Array Type self.ProcessQuotaPeak = v_bytes(size=16) # FIXME Unknown Array Type self.CommitCharge = v_uint64() self.QuotaBlock = v_ptr64() self.CpuQuotaBlock = v_ptr64() self.PeakVirtualSize = v_uint64() self.VirtualSize = v_uint64() self.SessionProcessLinks = LIST_ENTRY() self.DebugPort = v_ptr64() self.ExceptionPortData = v_ptr64() self.ObjectTable = v_ptr64() self.Token = EX_FAST_REF() self.WorkingSetPage = v_uint64() self.AddressCreationLock = EX_PUSH_LOCK() self.RotateInProgress = v_ptr64() self.ForkInProgress = v_ptr64() self.HardwareTrigger = v_uint64() self.PhysicalVadRoot = v_ptr64() self.CloneRoot = v_ptr64() self.NumberOfPrivatePages = v_uint64() self.NumberOfLockedPages = v_uint64() self.Win32Process = v_ptr64() self.Job = v_ptr64() self.SectionObject = v_ptr64() self.SectionBaseAddress = v_ptr64() self.Cookie = v_uint32() self.Spare8 = v_uint32() self.WorkingSetWatch = v_ptr64() self.Win32WindowStation = v_ptr64() self.InheritedFromUniqueProcessId = v_ptr64() self.LdtInformation = v_ptr64() self.Spare = v_ptr64() self.ConsoleHostProcess = v_uint64() self.DeviceMap = v_ptr64() self.EtwDataSource = v_ptr64() self.FreeTebHint = v_ptr64() self.PageDirectoryPte = HARDWARE_PTE() self.Session = v_ptr64() self.ImageFileName = v_bytes(size=15) # FIXME Unknown Array Type self.PriorityClass = v_uint8() self.JobLinks = LIST_ENTRY() self.LockedPagesList = v_ptr64() self.ThreadListHead = LIST_ENTRY() self.SecurityPort = v_ptr64() self.Wow64Process = v_ptr64() self.ActiveThreads = v_uint32() self.ImagePathHash = v_uint32() self.DefaultHardErrorProcessing = v_uint32() self.LastThreadExitStatus = v_uint32() self.Peb = v_ptr64() self.PrefetchTrace = EX_FAST_REF() self.ReadOperationCount = LARGE_INTEGER() self.WriteOperationCount = LARGE_INTEGER() self.OtherOperationCount = LARGE_INTEGER() self.ReadTransferCount = LARGE_INTEGER() self.WriteTransferCount = LARGE_INTEGER() self.OtherTransferCount = LARGE_INTEGER() self.CommitChargeLimit = v_uint64() self.CommitChargePeak = v_uint64() self.AweInfo = v_ptr64() self.SeAuditProcessCreationInfo = SE_AUDIT_PROCESS_CREATION_INFO() self.Vm = MMSUPPORT() self.MmProcessLinks = LIST_ENTRY() self.HighestUserAddress = v_ptr64() self.ModifiedPageCount = v_uint32() self.Flags2 = v_uint32() self.Flags = v_uint32() self.ExitStatus = v_uint32() self.VadRoot = MM_AVL_TABLE() self.AlpcContext = ALPC_PROCESS_CONTEXT() self.TimerResolutionLink = LIST_ENTRY() self.RequestedTimerResolution = v_uint32() self.ActiveThreadsHighWatermark = v_uint32() self.SmallestTimerResolution = v_uint32() self._pad04c0 = v_bytes(size=4) self.TimerResolutionStackRecord = v_ptr64() class TP_TASK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Callbacks = v_ptr64() self.NumaNode = v_uint32() self.IdealProcessor = v_uint8() self._pad0010 = v_bytes(size=3) self.PostGuard = TP_NBQ_GUARD() self.NBQNode = v_ptr64() class TEB_ACTIVE_FRAME_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self._pad0008 = v_bytes(size=4) self.FrameName = v_ptr64() class KTIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.DueTime = ULARGE_INTEGER() self.TimerListEntry = LIST_ENTRY() self.Dpc = v_ptr64() self.Processor = v_uint32() self.Period = v_uint32() class _unnamed_7896(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Srb = v_ptr64() class CM_PARTIAL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Flags = v_uint16() self.u = _unnamed_9396() class OBJECT_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.RootDirectory = v_ptr64() self.ObjectName = v_ptr64() self.Attributes = v_uint32() self._pad0020 = v_bytes(size=4) self.SecurityDescriptor = v_ptr64() self.SecurityQualityOfService = v_ptr64() class CM_FULL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.PartialResourceList = CM_PARTIAL_RESOURCE_LIST() class KTIMER_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TimerExpiry = v_bytes(size=512) # FIXME Unknown Array Type self.TimerEntries = v_bytes(size=512) # FIXME Unknown Array Type class FAST_IO_DISPATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFastIoDispatch = v_uint32() self._pad0008 = v_bytes(size=4) self.FastIoCheckIfPossible = v_ptr64() self.FastIoRead = v_ptr64() self.FastIoWrite = v_ptr64() self.FastIoQueryBasicInfo = v_ptr64() self.FastIoQueryStandardInfo = v_ptr64() self.FastIoLock = v_ptr64() self.FastIoUnlockSingle = v_ptr64() self.FastIoUnlockAll = v_ptr64() self.FastIoUnlockAllByKey = v_ptr64() self.FastIoDeviceControl = v_ptr64() self.AcquireFileForNtCreateSection = v_ptr64() self.ReleaseFileForNtCreateSection = v_ptr64() self.FastIoDetachDevice = v_ptr64() self.FastIoQueryNetworkOpenInfo = v_ptr64() self.AcquireForModWrite = v_ptr64() self.MdlRead = v_ptr64() self.MdlReadComplete = v_ptr64() self.PrepareMdlWrite = v_ptr64() self.MdlWriteComplete = v_ptr64() self.FastIoReadCompressed = v_ptr64() self.FastIoWriteCompressed = v_ptr64() self.MdlReadCompleteCompressed = v_ptr64() self.MdlWriteCompleteCompressed = v_ptr64() self.FastIoQueryOpen = v_ptr64() self.ReleaseForModWrite = v_ptr64() self.AcquireForCcFlush = v_ptr64() self.ReleaseForCcFlush = v_ptr64() class RTL_DYNAMIC_HASH_TABLE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ChainHead = v_ptr64() self.PrevLinkage = v_ptr64() self.Signature = v_uint64() class MMWSL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class PROC_IDLE_STATE_ACCOUNTING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalTime = v_uint64() self.IdleTransitions = v_uint32() self.FailedTransitions = v_uint32() self.InvalidBucketIndex = v_uint32() self._pad0018 = v_bytes(size=4) self.MinTime = v_uint64() self.MaxTime = v_uint64() self.IdleTimeBuckets = v_uint64() class KGDTENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LimitLow = v_uint16() self.BaseLow = v_uint16() self.Bytes = _unnamed_6010() self.BaseUpper = v_uint32() self.MustBeZero = v_uint32() class KSPECIAL_REGISTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Cr0 = v_uint64() self.Cr2 = v_uint64() self.Cr3 = v_uint64() self.Cr4 = v_uint64() self.KernelDr0 = v_uint64() self.KernelDr1 = v_uint64() self.KernelDr2 = v_uint64() self.KernelDr3 = v_uint64() self.KernelDr6 = v_uint64() self.KernelDr7 = v_uint64() self.Gdtr = KDESCRIPTOR() self.Idtr = KDESCRIPTOR() self.Tr = v_uint16() self.Ldtr = v_uint16() self.MxCsr = v_uint32() self.DebugControl = v_uint64() self.LastBranchToRip = v_uint64() self.LastBranchFromRip = v_uint64() self.LastExceptionToRip = v_uint64() self.LastExceptionFromRip = v_uint64() self.Cr8 = v_uint64() self.MsrGsBase = v_uint64() self.MsrGsSwap = v_uint64() self.MsrStar = v_uint64() self.MsrLStar = v_uint64() self.MsrCStar = v_uint64() self.MsrSyscallMask = v_uint64() class _unnamed_9666(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length48 = v_uint32() class RTL_CRITICAL_SECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DebugInfo = v_ptr64() self.LockCount = v_uint32() self.RecursionCount = v_uint32() self.OwningThread = v_ptr64() self.LockSemaphore = v_ptr64() self.SpinCount = v_uint64() class _unnamed_9663(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length40 = v_uint32() class KSYSTEM_TIME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.High1Time = v_uint32() self.High2Time = v_uint32() class PROC_IDLE_STATE_BUCKET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalTime = v_uint64() self.MinTime = v_uint64() self.MaxTime = v_uint64() self.Count = v_uint32() class RTL_STD_LIST_HEAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() self.Lock = RTL_STACK_DATABASE_LOCK() class _unnamed_9669(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length64 = v_uint32() class DPH_HEAP_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.pNextAlloc = v_ptr64() self._pad0020 = v_bytes(size=24) self.pUserAllocation = v_ptr64() self.pVirtualBlock = v_ptr64() self.nVirtualBlockSize = v_uint64() self.nVirtualAccessSize = v_uint64() self.nUserRequestedSize = v_uint64() self.nUserActualSize = v_uint64() self.UserValue = v_ptr64() self.UserFlags = v_uint32() self._pad0060 = v_bytes(size=4) self.StackTrace = v_ptr64() self.AdjacencyEntry = LIST_ENTRY() self.pVirtualRegion = v_ptr64() class _unnamed_7639(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UserApcRoutine = v_ptr64() self.UserApcContext = v_ptr64() class LUID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Luid = LUID() self.Attributes = v_uint32() class _unnamed_8013(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InPath = v_uint8() self.Reserved = v_bytes(size=3) # FIXME Unknown Array Type self._pad0008 = v_bytes(size=4) self.Type = v_uint32() class IMAGE_NT_HEADERS64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER64() class HEAP_BUCKET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BlockUnits = v_uint16() self.SizeIndex = v_uint8() self.UseAffinity = v_uint8() class KTHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.CycleTime = v_uint64() self.QuantumTarget = v_uint64() self.InitialStack = v_ptr64() self.StackLimit = v_ptr64() self.KernelStack = v_ptr64() self.ThreadLock = v_uint64() self.WaitRegister = KWAIT_STATUS_REGISTER() self.Running = v_uint8() self.Alerted = v_bytes(size=2) # FIXME Unknown Array Type self.KernelStackResident = v_uint32() self.ApcState = KAPC_STATE() self.DeferredProcessor = v_uint32() self._pad0088 = v_bytes(size=4) self.ApcQueueLock = v_uint64() self.WaitStatus = v_uint64() self.WaitBlockList = v_ptr64() self.WaitListEntry = LIST_ENTRY() self.Queue = v_ptr64() self.Teb = v_ptr64() self.Timer = KTIMER() self.AutoAlignment = v_uint32() self.Spare0 = v_uint32() self.WaitBlock = v_uint32() self.QueueListEntry = LIST_ENTRY() self.TrapFrame = v_ptr64() self.FirstArgument = v_ptr64() self.CallbackStack = v_ptr64() self.ApcStateIndex = v_uint8() self.BasePriority = v_uint8() self.PriorityDecrement = v_uint8() self.Preempted = v_uint8() self.AdjustReason = v_uint8() self.AdjustIncrement = v_uint8() self.PreviousMode = v_uint8() self.Saturation = v_uint8() self.SystemCallNumber = v_uint32() self.FreezeCount = v_uint32() self.UserAffinity = GROUP_AFFINITY() self.Process = v_ptr64() self.Affinity = GROUP_AFFINITY() self.IdealProcessor = v_uint32() self.UserIdealProcessor = v_uint32() self.ApcStatePointer = v_bytes(size=16) # FIXME Unknown Array Type self.SavedApcState = KAPC_STATE() self.Win32Thread = v_ptr64() self.StackBase = v_ptr64() self.SuspendApc = KAPC() self.SuspendSemaphore = KSEMAPHORE() self.ThreadListEntry = LIST_ENTRY() self.MutantListHead = LIST_ENTRY() self.SListFaultAddress = v_ptr64() self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() self.ThreadCounters = v_ptr64() self.XStateSave = v_ptr64() class _unnamed_8934(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BankNumber = v_uint8() self.Reserved2 = v_bytes(size=7) # FIXME Unknown Array Type self.Status = MCI_STATS() self.Address = MCI_ADDR() self.Misc = v_uint64() class _unnamed_7758(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.Key = v_uint32() self._pad0010 = v_bytes(size=4) self.ByteOffset = LARGE_INTEGER() class CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P1Home = v_uint64() self.P2Home = v_uint64() self.P3Home = v_uint64() self.P4Home = v_uint64() self.P5Home = v_uint64() self.P6Home = v_uint64() self.ContextFlags = v_uint32() self.MxCsr = v_uint32() self.SegCs = v_uint16() self.SegDs = v_uint16() self.SegEs = v_uint16() self.SegFs = v_uint16() self.SegGs = v_uint16() self.SegSs = v_uint16() self.EFlags = v_uint32() self.Dr0 = v_uint64() self.Dr1 = v_uint64() self.Dr2 = v_uint64() self.Dr3 = v_uint64() self.Dr6 = v_uint64() self.Dr7 = v_uint64() self.Rax = v_uint64() self.Rcx = v_uint64() self.Rdx = v_uint64() self.Rbx = v_uint64() self.Rsp = v_uint64() self.Rbp = v_uint64() self.Rsi = v_uint64() self.Rdi = v_uint64() self.R8 = v_uint64() self.R9 = v_uint64() self.R10 = v_uint64() self.R11 = v_uint64() self.R12 = v_uint64() self.R13 = v_uint64() self.R14 = v_uint64() self.R15 = v_uint64() self.Rip = v_uint64() self.FltSave = XSAVE_FORMAT() self.VectorRegister = XSAVE_FORMAT() self.VectorControl = v_uint64() self.DebugControl = v_uint64() self.LastBranchToRip = v_uint64() self.LastBranchFromRip = v_uint64() self.LastExceptionToRip = v_uint64() self.LastExceptionFromRip = v_uint64() class MCI_STATS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MciStatus = _unnamed_8929() class _unnamed_7751(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityContext = v_ptr64() self.Options = v_uint32() self._pad0010 = v_bytes(size=4) self.Reserved = v_uint16() self.ShareAccess = v_uint16() self._pad0018 = v_bytes(size=4) self.Parameters = v_ptr64() class _unnamed_8940(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_uint64() self.Type = v_uint64() class PROC_PERF_LOAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BusyPercentage = v_uint8() self.FrequencyPercentage = v_uint8() class AUX_ACCESS_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegesUsed = v_ptr64() self.GenericMapping = GENERIC_MAPPING() self.AccessesToAudit = v_uint32() self.MaximumAuditMask = v_uint32() self.TransactionId = GUID() self.NewSecurityDescriptor = v_ptr64() self.ExistingSecurityDescriptor = v_ptr64() self.ParentSecurityDescriptor = v_ptr64() self.DeRefSecurityDescriptor = v_ptr64() self.SDLock = v_ptr64() self.AccessReasons = ACCESS_REASONS() class HEAP_LOCAL_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeletedSubSegments = SLIST_HEADER() self.CrtZone = v_ptr64() self.LowFragHeap = v_ptr64() self.Sequence = v_uint32() self._pad0030 = v_bytes(size=12) self.SegmentInfo = v_uint32() class DPH_BLOCK_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartStamp = v_uint32() self._pad0008 = v_bytes(size=4) self.Heap = v_ptr64() self.RequestedSize = v_uint64() self.ActualSize = v_uint64() self.FreeQueue = LIST_ENTRY() self.StackTrace = v_ptr64() self.Padding = v_uint32() self.EndStamp = v_uint32() class PF_KERNEL_GLOBALS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AccessBufferAgeThreshold = v_uint64() self.AccessBufferRef = EX_RUNDOWN_REF() self.AccessBufferExistsEvent = KEVENT() self.AccessBufferMax = v_uint32() self._pad0040 = v_bytes(size=20) self.AccessBufferList = SLIST_HEADER() self.StreamSequenceNumber = v_uint32() self.Flags = v_uint32() self.ScenarioPrefetchCount = v_uint32() class _unnamed_7918(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() class EVENT_DATA_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Ptr = v_uint64() self.Size = v_uint32() self.Reserved = v_uint32() class _unnamed_8834(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FilePointerIndex = v_uint32() class _unnamed_8835(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FilePointerIndex = v_uint32() class _unnamed_7858(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.FsInformationClass = v_uint32() class IO_DRIVER_CREATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self._pad0008 = v_bytes(size=6) self.ExtraCreateParameter = v_ptr64() self.DeviceObjectHint = v_ptr64() self.TxnParameters = v_ptr64() class EJOB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Event = KEVENT() self.JobLinks = LIST_ENTRY() self.ProcessListHead = LIST_ENTRY() self.JobLock = ERESOURCE() self.TotalUserTime = LARGE_INTEGER() self.TotalKernelTime = LARGE_INTEGER() self.ThisPeriodTotalUserTime = LARGE_INTEGER() self.ThisPeriodTotalKernelTime = LARGE_INTEGER() self.TotalPageFaultCount = v_uint32() self.TotalProcesses = v_uint32() self.ActiveProcesses = v_uint32() self.TotalTerminatedProcesses = v_uint32() self.PerProcessUserTimeLimit = LARGE_INTEGER() self.PerJobUserTimeLimit = LARGE_INTEGER() self.MinimumWorkingSetSize = v_uint64() self.MaximumWorkingSetSize = v_uint64() self.LimitFlags = v_uint32() self.ActiveProcessLimit = v_uint32() self.Affinity = KAFFINITY_EX() self.PriorityClass = v_uint8() self._pad0128 = v_bytes(size=7) self.AccessState = v_ptr64() self.UIRestrictionsClass = v_uint32() self.EndOfJobTimeAction = v_uint32() self.CompletionPort = v_ptr64() self.CompletionKey = v_ptr64() self.SessionId = v_uint32() self.SchedulingClass = v_uint32() self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() self.ProcessMemoryLimit = v_uint64() self.JobMemoryLimit = v_uint64() self.PeakProcessMemoryUsed = v_uint64() self.PeakJobMemoryUsed = v_uint64() self.CurrentJobMemoryUsed = v_uint64() self.MemoryLimitsLock = EX_PUSH_LOCK() self.JobSetLinks = LIST_ENTRY() self.MemberLevel = v_uint32() self.JobFlags = v_uint32() class HANDLE_TRACE_DEBUG_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.RefCount = v_uint32() self.TableSize = v_uint32() self.BitMaskFlags = v_uint32() self._pad0010 = v_bytes(size=4) self.CloseCompactionLock = FAST_MUTEX() self.CurrentStackIndex = v_uint32() self._pad0050 = v_bytes(size=4) self.TraceDb = v_uint32() class KPROCESSOR_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SpecialRegisters = KSPECIAL_REGISTERS() self._pad00e0 = v_bytes(size=8) self.ContextFrame = CONTEXT() class KAPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.SpareByte0 = v_uint8() self.Size = v_uint8() self.SpareByte1 = v_uint8() self.SpareLong0 = v_uint32() self.Thread = v_ptr64() self.ApcListEntry = LIST_ENTRY() self.KernelRoutine = v_ptr64() self.RundownRoutine = v_ptr64() self.NormalRoutine = v_ptr64() self.NormalContext = v_ptr64() self.SystemArgument1 = v_ptr64() self.SystemArgument2 = v_ptr64() self.ApcStateIndex = v_uint8() self.ApcMode = v_uint8() self.Inserted = v_uint8() class RTL_STACK_DATABASE_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = RTL_SRWLOCK() class SID_IDENTIFIER_AUTHORITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Value = v_bytes(size=6) # FIXME Unknown Array Type class _unnamed_9235(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AsULONG = v_uint32() class XSTATE_FEATURE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint32() self.Size = v_uint32() class WHEA_TIMESTAMP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Seconds = v_uint64() class ACTIVATION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class RTL_CRITICAL_SECTION_DEBUG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.CreatorBackTraceIndex = v_uint16() self._pad0008 = v_bytes(size=4) self.CriticalSection = v_ptr64() self.ProcessLocksList = LIST_ENTRY() self.EntryCount = v_uint32() self.ContentionCount = v_uint32() self.Flags = v_uint32() self.CreatorBackTraceIndexHigh = v_uint16() self.SpareUSHORT = v_uint16() class DISPATCHER_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.TimerControlFlags = v_uint8() self.ThreadControlFlags = v_uint8() self.TimerMiscFlags = v_uint8() self.SignalState = v_uint32() self.WaitListHead = LIST_ENTRY() class ASSEMBLY_STORAGE_MAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class PROCESSOR_POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdleStates = v_ptr64() self.IdleTimeLast = v_uint64() self.IdleTimeTotal = v_uint64() self.IdleTimeEntry = v_uint64() self.IdleAccounting = v_ptr64() self.Hypervisor = v_uint32() self.PerfHistoryTotal = v_uint32() self.ThermalConstraint = v_uint8() self.PerfHistoryCount = v_uint8() self.PerfHistorySlot = v_uint8() self.Reserved = v_uint8() self.LastSysTime = v_uint32() self.WmiDispatchPtr = v_uint64() self.WmiInterfaceEnabled = v_uint32() self._pad0048 = v_bytes(size=4) self.FFHThrottleStateInfo = PPM_FFH_THROTTLE_STATE_INFO() self.PerfActionDpc = KDPC() self.PerfActionMask = v_uint32() self._pad00b0 = v_bytes(size=4) self.IdleCheck = PROC_IDLE_SNAP() self.PerfCheck = PROC_IDLE_SNAP() self.Domain = v_ptr64() self.PerfConstraint = v_ptr64() self.Load = v_ptr64() self.PerfHistory = v_ptr64() self.Utility = v_uint32() self.OverUtilizedHistory = v_uint32() self.AffinityCount = v_uint32() self.AffinityHistory = v_uint32() class _unnamed_8058(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemContext = v_uint32() self._pad0008 = v_bytes(size=4) self.Type = v_uint32() self._pad0010 = v_bytes(size=4) self.State = POWER_STATE() self._pad0018 = v_bytes(size=4) self.ShutdownType = v_uint32() class POWER_SEQUENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SequenceD1 = v_uint32() self.SequenceD2 = v_uint32() self.SequenceD3 = v_uint32() class DPH_HEAP_ROOT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.HeapFlags = v_uint32() self.HeapCritSect = v_ptr64() self.nRemoteLockAcquired = v_uint32() self._pad0018 = v_bytes(size=4) self.pVirtualStorageListHead = v_ptr64() self.pVirtualStorageListTail = v_ptr64() self.nVirtualStorageRanges = v_uint32() self._pad0030 = v_bytes(size=4) self.nVirtualStorageBytes = v_uint64() self.BusyNodesTable = RTL_AVL_TABLE() self.NodeToAllocate = v_ptr64() self.nBusyAllocations = v_uint32() self._pad00b0 = v_bytes(size=4) self.nBusyAllocationBytesCommitted = v_uint64() self.pFreeAllocationListHead = v_ptr64() self.pFreeAllocationListTail = v_ptr64() self.nFreeAllocations = v_uint32() self._pad00d0 = v_bytes(size=4) self.nFreeAllocationBytesCommitted = v_uint64() self.AvailableAllocationHead = LIST_ENTRY() self.nAvailableAllocations = v_uint32() self._pad00f0 = v_bytes(size=4) self.nAvailableAllocationBytesCommitted = v_uint64() self.pUnusedNodeListHead = v_ptr64() self.pUnusedNodeListTail = v_ptr64() self.nUnusedNodes = v_uint32() self._pad0110 = v_bytes(size=4) self.nBusyAllocationBytesAccessible = v_uint64() self.pNodePoolListHead = v_ptr64() self.pNodePoolListTail = v_ptr64() self.nNodePools = v_uint32() self._pad0130 = v_bytes(size=4) self.nNodePoolBytes = v_uint64() self.NextHeap = LIST_ENTRY() self.ExtraFlags = v_uint32() self.Seed = v_uint32() self.NormalHeap = v_ptr64() self.CreateStackTrace = v_ptr64() self.FirstThread = v_ptr64() class JOB_ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class SECURITY_QUALITY_OF_SERVICE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.ImpersonationLevel = v_uint32() self.ContextTrackingMode = v_uint8() self.EffectiveOnly = v_uint8() class COMPRESSED_DATA_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CompressionFormatAndEngine = v_uint16() self.CompressionUnitShift = v_uint8() self.ChunkShift = v_uint8() self.ClusterShift = v_uint8() self.Reserved = v_uint8() self.NumberOfChunks = v_uint16() self.CompressedChunkSizes = v_bytes(size=4) # FIXME Unknown Array Type class KSTACK_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StackControl = KERNEL_STACK_CONTROL() self.NpxFrame = XSAVE_FORMAT() class WHEA_ERROR_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = WHEA_ERROR_RECORD_HEADER() self.SectionDescriptor = WHEA_ERROR_RECORD_HEADER() class PS_PER_CPU_QUOTA_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SortedListEntry = LIST_ENTRY() self.IdleOnlyListHead = LIST_ENTRY() self.CycleBaseAllowance = v_uint64() self.CyclesRemaining = v_uint64() self.CurrentGeneration = v_uint32() class PROC_PERF_CONSTRAINT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Prcb = v_ptr64() self.PerfContext = v_uint64() self.PercentageCap = v_uint32() self.ThermalCap = v_uint32() self.TargetFrequency = v_uint32() self.AcumulatedFullFrequency = v_uint32() self.AcumulatedZeroFrequency = v_uint32() self.FrequencyHistoryTotal = v_uint32() self.AverageFrequency = v_uint32() class LUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class CLIENT_ID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UniqueProcess = v_ptr64() self.UniqueThread = v_ptr64() class IMAGE_OPTIONAL_HEADER64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint16() self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.ImageBase = v_uint64() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint64() self.SizeOfStackCommit = v_uint64() self.SizeOfHeapReserve = v_uint64() self.SizeOfHeapCommit = v_uint64() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = v_uint32() class RTL_STACK_TRACE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashChain = RTL_STD_LIST_ENTRY() self.TraceCount = v_uint16() self.IndexHigh = v_uint16() self.Index = v_uint16() self.Depth = v_uint16() self.BackTrace = v_bytes(size=256) # FIXME Unknown Array Type class OBJECT_DUMP_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Stream = v_ptr64() self.Detail = v_uint32() class HANDLE_TRACE_DB_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientId = CLIENT_ID() self.Handle = v_ptr64() self.Type = v_uint32() self._pad0020 = v_bytes(size=4) self.StackTrace = v_bytes(size=128) # FIXME Unknown Array Type class GENERAL_LOOKASIDE_POOL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.AllocateEx = v_ptr64() self.FreeEx = v_ptr64() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class RTL_SRWLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locked = v_uint64() class STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self._pad0008 = v_bytes(size=4) self.Buffer = v_ptr64() class _unnamed_7211(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() class TP_POOL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class LIST_ENTRY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint32() self.Blink = v_uint32() class KDESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pad = v_bytes(size=6) # FIXME Unknown Array Type self.Limit = v_uint16() self.Base = v_ptr64() class SINGLE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() class PPM_FFH_THROTTLE_STATE_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EnableLogging = v_uint8() self._pad0004 = v_bytes(size=3) self.MismatchCount = v_uint32() self.Initialized = v_uint8() self._pad0010 = v_bytes(size=7) self.LastValue = v_uint64() self.LastLogTickCount = LARGE_INTEGER() class _unnamed_7819(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.FileName = v_ptr64() self.FileInformationClass = v_uint32() self._pad0018 = v_bytes(size=4) self.FileIndex = v_uint32() class KDEVICE_QUEUE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceListEntry = LIST_ENTRY() self.SortKey = v_uint32() self.Inserted = v_uint8() class CACHED_KSTACK_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SListHead = SLIST_HEADER() self.MinimumFree = v_uint32() self.Misses = v_uint32() self.MissesLast = v_uint32() self.Pad0 = v_uint32() class _unnamed_10196(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.MinBusNumber = v_uint32() self.MaxBusNumber = v_uint32() self.Reserved = v_uint32() class _unnamed_10193(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinimumChannel = v_uint32() self.MaximumChannel = v_uint32() class EX_FAST_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr64() class INTERLOCK_SEQ(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Depth = v_uint16() self.FreeEntryOffset = v_uint16() self.Sequence = v_uint32() class KSPIN_LOCK_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() self.Lock = v_ptr64() class RTL_ACTIVATION_CONTEXT_STACK_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Previous = v_ptr64() self.ActivationContext = v_ptr64() self.Flags = v_uint32() class FS_FILTER_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbacks = v_uint32() self.Reserved = v_uint32() self.PreAcquireForSectionSynchronization = v_ptr64() self.PostAcquireForSectionSynchronization = v_ptr64() self.PreReleaseForSectionSynchronization = v_ptr64() self.PostReleaseForSectionSynchronization = v_ptr64() self.PreAcquireForCcFlush = v_ptr64() self.PostAcquireForCcFlush = v_ptr64() self.PreReleaseForCcFlush = v_ptr64() self.PostReleaseForCcFlush = v_ptr64() self.PreAcquireForModifiedPageWriter = v_ptr64() self.PostAcquireForModifiedPageWriter = v_ptr64() self.PreReleaseForModifiedPageWriter = v_ptr64() self.PostReleaseForModifiedPageWriter = v_ptr64() class HANDLE_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr64() self.GrantedAccess = v_uint32() class IO_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Option = v_uint8() self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Spare1 = v_uint8() self.Flags = v_uint16() self.Spare2 = v_uint16() self.u = _unnamed_9587() class EX_PUSH_LOCK_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locks = v_bytes(size=256) # FIXME Unknown Array Type class RTL_TRACE_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Count = v_uint32() self.Size = v_uint32() self._pad0010 = v_bytes(size=4) self.UserCount = v_uint64() self.UserSize = v_uint64() self.UserContext = v_ptr64() self.Next = v_ptr64() self.Trace = v_ptr64() class _unnamed_7969(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Capabilities = v_ptr64() class SCSI_REQUEST_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class ETHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Tcb = KTHREAD() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self._pad0378 = v_bytes(size=8) self.ExitStatus = v_uint32() self._pad0380 = v_bytes(size=4) self.PostBlockList = LIST_ENTRY() self.TerminationPort = v_ptr64() self.ActiveTimerListLock = v_uint64() self.ActiveTimerListHead = LIST_ENTRY() self.Cid = CLIENT_ID() self.KeyedWaitSemaphore = KSEMAPHORE() self.ClientSecurity = PS_CLIENT_SECURITY_CONTEXT() self.IrpList = LIST_ENTRY() self.TopLevelIrp = v_uint64() self.DeviceToVerify = v_ptr64() self.CpuQuotaApc = v_ptr64() self.Win32StartAddress = v_ptr64() self.LegacyPowerObject = v_ptr64() self.ThreadListEntry = LIST_ENTRY() self.RundownProtect = EX_RUNDOWN_REF() self.ThreadLock = EX_PUSH_LOCK() self.ReadClusterSize = v_uint32() self.MmLockOrdering = v_uint32() self.CrossThreadFlags = v_uint32() self.SameThreadPassiveFlags = v_uint32() self.SameThreadApcFlags = v_uint32() self.CacheManagerActive = v_uint8() self.DisablePageFaultClustering = v_uint8() self.ActiveFaultCount = v_uint8() self.LockOrderState = v_uint8() self.AlpcMessageId = v_uint64() self.AlpcMessage = v_ptr64() self.AlpcWaitListEntry = LIST_ENTRY() self.CacheManagerCount = v_uint32() self.IoBoostCount = v_uint32() self.IrpListLock = v_uint64() self.ReservedForSynchTracking = v_ptr64() self.CmCallbackListHead = SINGLE_LIST_ENTRY() class FAST_MUTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self._pad0008 = v_bytes(size=4) self.Owner = v_ptr64() self.Contention = v_uint32() self._pad0018 = v_bytes(size=4) self.Event = KEVENT() self.OldIrql = v_uint32() class WHEA_ERROR_RECORD_HEADER_VALIDBITS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PlatformId = v_uint32() class KDEVICE_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self._pad0008 = v_bytes(size=4) self.DeviceListHead = LIST_ENTRY() self.Lock = v_uint64() self.Busy = v_uint8() class IO_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityQos = v_ptr64() self.AccessState = v_ptr64() self.DesiredAccess = v_uint32() self.FullCreateOptions = v_uint32() class TERMINATION_PORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() self.Port = v_ptr64() class PROC_HISTORY_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Utility = v_uint16() self.Frequency = v_uint8() self.Reserved = v_uint8() class _unnamed_7831(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.FileInformationClass = v_uint32() self._pad0010 = v_bytes(size=4) self.FileObject = v_ptr64() self.ReplaceIfExists = v_uint8() self.AdvanceOnly = v_uint8() class IO_CLIENT_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextExtension = v_ptr64() self.ClientIdentificationAddress = v_ptr64() class INITIAL_PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class WHEA_ERROR_RECORD_HEADER_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Recovered = v_uint32() class KTIMER_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = v_uint64() self.Entry = LIST_ENTRY() self.Time = ULARGE_INTEGER() class _unnamed_9653(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data = v_bytes(size=12) # FIXME Unknown Array Type class KWAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitListEntry = LIST_ENTRY() self.Thread = v_ptr64() self.Object = v_ptr64() self.NextWaitBlock = v_ptr64() self.WaitKey = v_uint16() self.WaitType = v_uint8() self.BlockState = v_uint8() self.SpareLong = v_uint32() class _unnamed_9655(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = v_uint32() self.Length = v_uint32() self.Reserved = v_uint32() class _unnamed_9659(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSize = v_uint32() self.Reserved1 = v_uint32() self.Reserved2 = v_uint32() class ACTIVATION_CONTEXT_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class _unnamed_7624(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AsynchronousParameters = _unnamed_7639() class _unnamed_7627(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Overlay = _unnamed_7700() class _unnamed_7621(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MasterIrp = v_ptr64() class FILE_NETWORK_OPEN_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.FileAttributes = v_uint32() class HEAP_USERDATA_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SFreeListEntry = SINGLE_LIST_ENTRY() self.Reserved = v_ptr64() self.SizeIndex = v_uint64() self.Signature = v_uint64() class _unnamed_8025(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PowerState = v_uint32() class RTL_DRIVE_LETTER_CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint16() self.Length = v_uint16() self.TimeStamp = v_uint32() self.DosPath = STRING() class KIDTENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OffsetLow = v_uint16() self.Selector = v_uint16() self.IstIndex = v_uint16() self.OffsetMiddle = v_uint16() self.OffsetHigh = v_uint32() self.Reserved1 = v_uint32() class CACHE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint8() self.Associativity = v_uint8() self.LineSize = v_uint16() self.Size = v_uint32() self.Type = v_uint32() class ULARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class _unnamed_8922(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mca = _unnamed_8934() class TEB_ACTIVE_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self._pad0008 = v_bytes(size=4) self.Previous = v_ptr64() self.Context = v_ptr64() class GENERAL_LOOKASIDE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.AllocateEx = v_ptr64() self.FreeEx = v_ptr64() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class _unnamed_8929(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.McaErrorCode = v_uint16() self.ModelErrorCode = v_uint16() self.OtherInformation = v_uint32() class _unnamed_7723(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityContext = v_ptr64() self.Options = v_uint32() self._pad0010 = v_bytes(size=4) self.FileAttributes = v_uint16() self.ShareAccess = v_uint16() self._pad0018 = v_bytes(size=4) self.EaLength = v_uint32() class KWAIT_STATUS_REGISTER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint8() class NAMED_PIPE_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NamedPipeType = v_uint32() self.ReadMode = v_uint32() self.CompletionMode = v_uint32() self.MaximumInstances = v_uint32() self.InboundQuota = v_uint32() self.OutboundQuota = v_uint32() self.DefaultTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class _unnamed_7866(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_ptr64() self.Key = v_uint32() self._pad0010 = v_bytes(size=4) self.ByteOffset = LARGE_INTEGER() class NT_TIB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionList = v_ptr64() self.StackBase = v_ptr64() self.StackLimit = v_ptr64() self.SubSystemTib = v_ptr64() self.FiberData = v_ptr64() self.ArbitraryUserPointer = v_ptr64() self.Self = v_ptr64() class RTL_STD_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() class POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemState = v_uint32() class UNICODE_STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self._pad0008 = v_bytes(size=4) self.Buffer = v_ptr64() class HEAP_LIST_LOOKUP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExtendedLookup = v_ptr64() self.ArraySize = v_uint32() self.ExtraItem = v_uint32() self.ItemCount = v_uint32() self.OutOfRangeItems = v_uint32() self.BaseIndex = v_uint32() self._pad0020 = v_bytes(size=4) self.ListHead = v_ptr64() self.ListsInUseUlong = v_ptr64() self.ListHints = v_ptr64() class EPROCESS_QUOTA_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class HEAP_DEBUGGING_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterceptorFunction = v_ptr64() self.InterceptorValue = v_uint16() self._pad000c = v_bytes(size=2) self.ExtendedOptions = v_uint32() self.StackTraceDepth = v_uint32() self._pad0018 = v_bytes(size=4) self.MinTotalBlockSize = v_uint64() self.MaxTotalBlockSize = v_uint64() self.HeapLeakEnumerationRoutine = v_ptr64() class PEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InheritedAddressSpace = v_uint8() self.ReadImageFileExecOptions = v_uint8() self.BeingDebugged = v_uint8() self.BitField = v_uint8() self._pad0008 = v_bytes(size=4) self.Mutant = v_ptr64() self.ImageBaseAddress = v_ptr64() self.Ldr = v_ptr64() self.ProcessParameters = v_ptr64() self.SubSystemData = v_ptr64() self.ProcessHeap = v_ptr64() self.FastPebLock = v_ptr64() self.AtlThunkSListPtr = v_ptr64() self.IFEOKey = v_ptr64() self.CrossProcessFlags = v_uint32() self._pad0058 = v_bytes(size=4) self.KernelCallbackTable = v_ptr64() self.SystemReserved = v_bytes(size=4) # FIXME Unknown Array Type self.AtlThunkSListPtr32 = v_uint32() self.ApiSetMap = v_ptr64() self.TlsExpansionCounter = v_uint32() self._pad0078 = v_bytes(size=4) self.TlsBitmap = v_ptr64() self.TlsBitmapBits = v_bytes(size=8) # FIXME Unknown Array Type self.ReadOnlySharedMemoryBase = v_ptr64() self.HotpatchInformation = v_ptr64() self.ReadOnlyStaticServerData = v_ptr64() self.AnsiCodePageData = v_ptr64() self.OemCodePageData = v_ptr64() self.UnicodeCaseTableData = v_ptr64() self.NumberOfProcessors = v_uint32() self.NtGlobalFlag = v_uint32() self.CriticalSectionTimeout = LARGE_INTEGER() self.HeapSegmentReserve = v_uint64() self.HeapSegmentCommit = v_uint64() self.HeapDeCommitTotalFreeThreshold = v_uint64() self.HeapDeCommitFreeBlockThreshold = v_uint64() self.NumberOfHeaps = v_uint32() self.MaximumNumberOfHeaps = v_uint32() self.ProcessHeaps = v_ptr64() self.GdiSharedHandleTable = v_ptr64() self.ProcessStarterHelper = v_ptr64() self.GdiDCAttributeList = v_uint32() self._pad0110 = v_bytes(size=4) self.LoaderLock = v_ptr64() self.OSMajorVersion = v_uint32() self.OSMinorVersion = v_uint32() self.OSBuildNumber = v_uint16() self.OSCSDVersion = v_uint16() self.OSPlatformId = v_uint32() self.ImageSubsystem = v_uint32() self.ImageSubsystemMajorVersion = v_uint32() self.ImageSubsystemMinorVersion = v_uint32() self._pad0138 = v_bytes(size=4) self.ActiveProcessAffinityMask = v_uint64() self.GdiHandleBuffer = v_bytes(size=240) # FIXME Unknown Array Type self.PostProcessInitRoutine = v_ptr64() self.TlsExpansionBitmap = v_ptr64() self.TlsExpansionBitmapBits = v_bytes(size=128) # FIXME Unknown Array Type self.SessionId = v_uint32() self._pad02c8 = v_bytes(size=4) self.AppCompatFlags = ULARGE_INTEGER() self.AppCompatFlagsUser = ULARGE_INTEGER() self.pShimData = v_ptr64() self.AppCompatInfo = v_ptr64() self.CSDVersion = UNICODE_STRING() self.ActivationContextData = v_ptr64() self.ProcessAssemblyStorageMap = v_ptr64() self.SystemDefaultActivationContextData = v_ptr64() self.SystemAssemblyStorageMap = v_ptr64() self.MinimumStackCommit = v_uint64() self.FlsCallback = v_ptr64() self.FlsListHead = LIST_ENTRY() self.FlsBitmap = v_ptr64() self.FlsBitmapBits = v_bytes(size=16) # FIXME Unknown Array Type self.FlsHighIndex = v_uint32() self._pad0358 = v_bytes(size=4) self.WerRegistrationData = v_ptr64() self.WerShipAssertPtr = v_ptr64() self.pContextData = v_ptr64() self.pImageHeaderHash = v_ptr64() self.TracingFlags = v_uint32() class _unnamed_7927(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_ptr64() self.Size = v_uint16() self.Version = v_uint16() self._pad0010 = v_bytes(size=4) self.Interface = v_ptr64() self.InterfaceSpecificData = v_ptr64() class STACK_TRACE_DATABASE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved = v_bytes(size=104) # FIXME Unknown Array Type self.Reserved2 = v_ptr64() self.PeakHashCollisionListLength = v_uint64() self.LowerMemoryStart = v_ptr64() self.PreCommitted = v_uint8() self.DumpInProgress = v_uint8() self._pad0088 = v_bytes(size=6) self.CommitBase = v_ptr64() self.CurrentLowerCommitLimit = v_ptr64() self.CurrentUpperCommitLimit = v_ptr64() self.NextFreeLowerMemory = v_ptr64() self.NextFreeUpperMemory = v_ptr64() self.NumberOfEntriesLookedUp = v_uint32() self.NumberOfEntriesAdded = v_uint32() self.EntryIndexArray = v_ptr64() self.NumberOfEntriesAllocated = v_uint32() self.NumberOfEntriesAvailable = v_uint32() self.NumberOfAllocationFailures = v_uint32() self._pad00d0 = v_bytes(size=4) self.FreeLists = v_uint32() self.NumberOfBuckets = v_uint32() self._pad02d8 = v_bytes(size=4) self.Buckets = v_uint32() class _unnamed_7844(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() class KDPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.Importance = v_uint8() self.Number = v_uint16() self._pad0008 = v_bytes(size=4) self.DpcListEntry = LIST_ENTRY() self.DeferredRoutine = v_ptr64() self.DeferredContext = v_ptr64() self.SystemArgument1 = v_ptr64() self.SystemArgument2 = v_ptr64() self.DpcData = v_ptr64() class KEVENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class KSEMAPHORE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.Limit = v_uint32() class MM_PAGE_ACCESS_INFO_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Link = SINGLE_LIST_ENTRY() self.Type = v_uint32() self.EmptySequenceNumber = v_uint32() self.CreateTime = v_uint64() self.EmptyTime = v_uint64() self.PageEntry = v_ptr64() self.FileEntry = v_ptr64() self.FirstFileEntry = v_ptr64() self.Process = v_ptr64() self.SessionId = v_uint32() class OBJECT_TYPE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TypeList = LIST_ENTRY() self.Name = UNICODE_STRING() self.DefaultObject = v_ptr64() self.Index = v_uint8() self._pad002c = v_bytes(size=3) self.TotalNumberOfObjects = v_uint32() self.TotalNumberOfHandles = v_uint32() self.HighWaterNumberOfObjects = v_uint32() self.HighWaterNumberOfHandles = v_uint32() self._pad0040 = v_bytes(size=4) self.TypeInfo = OBJECT_TYPE_INITIALIZER() self.TypeLock = EX_PUSH_LOCK() self.Key = v_uint32() self._pad00c0 = v_bytes(size=4) self.CallbackList = LIST_ENTRY() class HANDLE_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TableCode = v_uint64() self.QuotaProcess = v_ptr64() self.UniqueProcessId = v_ptr64() self.HandleLock = EX_PUSH_LOCK() self.HandleTableList = LIST_ENTRY() self.HandleContentionEvent = EX_PUSH_LOCK() self.DebugInfo = v_ptr64() self.ExtraInfoPages = v_uint32() self.Flags = v_uint32() self.FirstFreeHandle = v_uint32() self._pad0050 = v_bytes(size=4) self.LastFreeHandleEntry = v_ptr64() self.HandleCount = v_uint32() self.NextHandleNeedingPool = v_uint32() self.HandleCountHighWatermark = v_uint32() class MMSUPPORT_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WorkingSetType = v_uint8() self.SessionMaster = v_uint8() self.MemoryPriority = v_uint8() self.WsleDeleted = v_uint8() class HEAP_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = _unnamed_8532() class EXCEPTION_REGISTRATION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() self.Handler = v_ptr64() class FILE_BASIC_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.FileAttributes = v_uint32() class LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_ptr64() self.Blink = v_ptr64() class M128A(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Low = v_uint64() self.High = v_uint64() class RTL_DYNAMIC_HASH_TABLE_ENUMERATOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashEntry = RTL_DYNAMIC_HASH_TABLE_ENTRY() self.ChainHead = v_ptr64() self.BucketIndex = v_uint32() class _unnamed_8069(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocatedResources = v_ptr64() self.AllocatedResourcesTranslated = v_ptr64() class KERNEL_STACK_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Current = KERNEL_STACK_SEGMENT() self.Previous = KERNEL_STACK_SEGMENT() class _unnamed_7661(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Create = _unnamed_7723() class GUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data1 = v_uint32() self.Data2 = v_uint16() self.Data3 = v_uint16() self.Data4 = v_bytes(size=8) # FIXME Unknown Array Type class HEAP_UCR_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.SegmentEntry = LIST_ENTRY() self.Address = v_ptr64() self.Size = v_uint64() class MCA_EXCEPTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VersionNumber = v_uint32() self.ExceptionType = v_uint32() self.TimeStamp = LARGE_INTEGER() self.ProcessorNumber = v_uint32() self.Reserved1 = v_uint32() self.u = _unnamed_8922() self.ExtCnt = v_uint32() self.Reserved3 = v_uint32() self.ExtReg = v_bytes(size=192) # FIXME Unknown Array Type class PSP_CPU_QUOTA_APC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class KAPC_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ApcListHead = v_bytes(size=192) # FIXME Unknown Array Type self.Process = v_ptr64() self.KernelApcInProgress = v_uint8() self.KernelApcPending = v_uint8() self.UserApcPending = v_uint8() class SLIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr64() class COUNTER_READING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() self.Index = v_uint32() self.Start = v_uint64() self.Total = v_uint64() class KDPC_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DpcListHead = LIST_ENTRY() self.DpcLock = v_uint64() self.DpcQueueDepth = v_uint32() self.DpcCount = v_uint32() class _unnamed_8532(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CriticalSection = RTL_CRITICAL_SECTION() class _unnamed_7892(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Vpb = v_ptr64() self.DeviceObject = v_ptr64() class IO_STATUS_BLOCK32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self.Information = v_uint32() class XSAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LegacyState = XSAVE_FORMAT() self.Header = XSAVE_AREA_HEADER() class GENERIC_MAPPING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GenericRead = v_uint32() self.GenericWrite = v_uint32() self.GenericExecute = v_uint32() self.GenericAll = v_uint32() class IRP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self._pad0008 = v_bytes(size=4) self.MdlAddress = v_ptr64() self.Flags = v_uint32() self._pad0018 = v_bytes(size=4) self.AssociatedIrp = _unnamed_7621() self.ThreadListEntry = LIST_ENTRY() self.IoStatus = IO_STATUS_BLOCK() self.RequestorMode = v_uint8() self.PendingReturned = v_uint8() self.StackCount = v_uint8() self.CurrentLocation = v_uint8() self.Cancel = v_uint8() self.CancelIrql = v_uint8() self.ApcEnvironment = v_uint8() self.AllocationFlags = v_uint8() self.UserIosb = v_ptr64() self.UserEvent = v_ptr64() self.Overlay = _unnamed_7624() self.CancelRoutine = v_ptr64() self.UserBuffer = v_ptr64() self.Tail = _unnamed_7627() class KTHREAD_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitReasonBitMap = v_uint64() self.UserData = v_ptr64() self.Flags = v_uint32() self.ContextSwitches = v_uint32() self.CycleTimeBias = v_uint64() self.HardwareCounters = v_uint64() self.HwCounter = v_uint64() class HEAP_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PreviousBlockPrivateData = v_ptr64() self.Size = v_uint16() self.Flags = v_uint8() self.SmallTagIndex = v_uint8() self.PreviousSize = v_uint16() self.SegmentOffset = v_uint8() self.UnusedBytes = v_uint8() class DRIVER_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self._pad0008 = v_bytes(size=4) self.DeviceObject = v_ptr64() self.Flags = v_uint32() self._pad0018 = v_bytes(size=4) self.DriverStart = v_ptr64() self.DriverSize = v_uint32() self._pad0028 = v_bytes(size=4) self.DriverSection = v_ptr64() self.DriverExtension = v_ptr64() self.DriverName = UNICODE_STRING() self.HardwareDatabase = v_ptr64() self.FastIoDispatch = v_ptr64() self.DriverInit = v_ptr64() self.DriverStartIo = v_ptr64() self.DriverUnload = v_ptr64() self.MajorFunction = v_bytes(size=224) # FIXME Unknown Array Type class _unnamed_6629(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Depth = v_uint64() self.HeaderType = v_uint64() class _unnamed_6628(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Depth = v_uint64() self.HeaderType = v_uint64() class _unnamed_6627(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Depth = v_uint64() self.HeaderType = v_uint64() class FILE_GET_QUOTA_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextEntryOffset = v_uint32() self.SidLength = v_uint32() self.Sid = SID() class _unnamed_5473(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class KGATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class IO_COMPLETION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = v_ptr64() self.Key = v_ptr64() class DRIVER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DriverObject = v_ptr64() self.AddDevice = v_ptr64() self.Count = v_uint32() self._pad0018 = v_bytes(size=4) self.ServiceKeyName = UNICODE_STRING() self.ClientDriverExtension = v_ptr64() self.FsFilterCallbacks = v_ptr64() class TP_NBQ_GUARD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GuardLinks = LIST_ENTRY() self.Guards = v_bytes(size=16) # FIXME Unknown Array Type class flags(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Removable = v_uint8() class MM_AVL_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BalancedRoot = MMADDRESS_NODE() self.DepthOfTree = v_uint64() self.NodeHint = v_ptr64() self.NodeFreeHint = v_ptr64() class WHEA_PERSISTENCE_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint64() class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FRUId = v_uint8() class _unnamed_10215(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length64 = v_uint32() self.Alignment64 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class EXCEPTION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionCode = v_uint32() self.ExceptionFlags = v_uint32() self.ExceptionRecord = v_ptr64() self.ExceptionAddress = v_ptr64() self.NumberParameters = v_uint32() self._pad0020 = v_bytes(size=4) self.ExceptionInformation = v_bytes(size=120) # FIXME Unknown Array Type class _unnamed_10210(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length48 = v_uint32() self.Alignment48 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class PROCESSOR_NUMBER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Group = v_uint16() self.Number = v_uint8() self.Reserved = v_uint8() class MM_PAGE_ACCESS_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = MM_PAGE_ACCESS_INFO_FLAGS() class KPCR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.IdtBase = v_ptr64() self.Unused = v_bytes(size=16) # FIXME Unknown Array Type self.Irql = v_uint8() self.SecondLevelCacheAssociativity = v_uint8() self.ObsoleteNumber = v_uint8() self.Fill0 = v_uint8() self.Unused0 = v_bytes(size=12) # FIXME Unknown Array Type self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.StallScaleFactor = v_uint32() self.Unused1 = v_bytes(size=24) # FIXME Unknown Array Type self.KernelReserved = v_bytes(size=60) # FIXME Unknown Array Type self.SecondLevelCacheSize = v_uint32() self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.Unused2 = v_uint32() self._pad0108 = v_bytes(size=4) self.KdVersionBlock = v_ptr64() self.Unused3 = v_ptr64() self.PcrAlign1 = v_bytes(size=96) # FIXME Unknown Array Type self._pad0180 = v_bytes(size=8) self.Prcb = KPRCB() class IMAGE_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Machine = v_uint16() self.NumberOfSections = v_uint16() self.TimeDateStamp = v_uint32() self.PointerToSymbolTable = v_uint32() self.NumberOfSymbols = v_uint32() self.SizeOfOptionalHeader = v_uint16() self.Characteristics = v_uint16() class LFH_BLOCK_ZONE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.FreePointer = v_ptr64() self.Limit = v_ptr64() class TP_CALLBACK_INSTANCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class LFH_HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = RTL_CRITICAL_SECTION() self.SubSegmentZones = LIST_ENTRY() self.ZoneBlockSize = v_uint64() self.Heap = v_ptr64() self.SegmentChange = v_uint32() self.SegmentCreate = v_uint32() self.SegmentInsertInFree = v_uint32() self.SegmentDelete = v_uint32() self.CacheAllocs = v_uint32() self.CacheFrees = v_uint32() self.SizeInCache = v_uint64() self.RunInfo = HEAP_BUCKET_RUN_INFO() self.UserBlockCache = HEAP_BUCKET_RUN_INFO() self.Buckets = HEAP_BUCKET_RUN_INFO() self.LocalData = HEAP_BUCKET_RUN_INFO() class _unnamed_7983(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IoResourceRequirementList = v_ptr64() class HEAP_BUCKET_RUN_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Bucket = v_uint32() self.RunLength = v_uint32() class PEB_LDR_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Initialized = v_uint8() self._pad0008 = v_bytes(size=3) self.SsHandle = v_ptr64() self.InLoadOrderModuleList = LIST_ENTRY() self.InMemoryOrderModuleList = LIST_ENTRY() self.InInitializationOrderModuleList = LIST_ENTRY() self.EntryInProgress = v_ptr64() self.ShutdownInProgress = v_uint8() self._pad0050 = v_bytes(size=7) self.ShutdownThreadId = v_ptr64() class _unnamed_7986(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WhichSpace = v_uint32() self._pad0008 = v_bytes(size=4) self.Buffer = v_ptr64() self.Offset = v_uint32() self._pad0018 = v_bytes(size=4) self.Length = v_uint32() class KQUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.EntryListHead = LIST_ENTRY() self.CurrentCount = v_uint32() self.MaximumCount = v_uint32() self.ThreadListHead = LIST_ENTRY() class MM_PAGE_ACCESS_INFO_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.File = _unnamed_8834() class SECURITY_SUBJECT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientToken = v_ptr64() self.ImpersonationLevel = v_uint32() self._pad0010 = v_bytes(size=4) self.PrimaryToken = v_ptr64() self.ProcessAuditId = v_ptr64() class _unnamed_7876(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityInformation = v_uint32() self._pad0008 = v_bytes(size=4) self.Length = v_uint32() class _unnamed_7871(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OutputBufferLength = v_uint32() self._pad0008 = v_bytes(size=4) self.InputBufferLength = v_uint32() self._pad0010 = v_bytes(size=4) self.IoControlCode = v_uint32() self._pad0018 = v_bytes(size=4) self.Type3InputBuffer = v_ptr64() class INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self._pad0008 = v_bytes(size=4) self.Context = v_ptr64() self.InterfaceReference = v_ptr64() self.InterfaceDereference = v_ptr64() class SLIST_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Alignment = v_uint64() self.Region = v_uint64() class _unnamed_7879(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityInformation = v_uint32() self._pad0008 = v_bytes(size=4) self.SecurityDescriptor = v_ptr64() class IMAGE_DATA_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.Size = v_uint32() class FILE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self._pad0008 = v_bytes(size=4) self.DeviceObject = v_ptr64() self.Vpb = v_ptr64() self.FsContext = v_ptr64() self.FsContext2 = v_ptr64() self.SectionObjectPointer = v_ptr64() self.PrivateCacheMap = v_ptr64() self.FinalStatus = v_uint32() self._pad0040 = v_bytes(size=4) self.RelatedFileObject = v_ptr64() self.LockOperation = v_uint8() self.DeletePending = v_uint8() self.ReadAccess = v_uint8() self.WriteAccess = v_uint8() self.DeleteAccess = v_uint8() self.SharedRead = v_uint8() self.SharedWrite = v_uint8() self.SharedDelete = v_uint8() self.Flags = v_uint32() self._pad0058 = v_bytes(size=4) self.FileName = UNICODE_STRING() self.CurrentByteOffset = LARGE_INTEGER() self.Waiters = v_uint32() self.Busy = v_uint32() self.LastLock = v_ptr64() self.Lock = KEVENT() self.Event = KEVENT() self.CompletionContext = v_ptr64() self.IrpListLock = v_uint64() self.IrpList = LIST_ENTRY() self.FileObjectExtension = v_ptr64() class PPM_IDLE_STATES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Flags = _unnamed_9235() self.TargetState = v_uint32() self.ActualState = v_uint32() self.OldState = v_uint32() self.NewlyUnparked = v_uint8() self._pad0018 = v_bytes(size=3) self.TargetProcessors = KAFFINITY_EX() self.State = KAFFINITY_EX() class HEAP_SUBSEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LocalInfo = v_ptr64() self.UserBlocks = v_ptr64() self.AggregateExchg = INTERLOCK_SEQ() self.BlockSize = v_uint16() self.Flags = v_uint16() self.BlockCount = v_uint16() self.SizeIndex = v_uint8() self.AffinityIndex = v_uint8() self.SFreeListEntry = SINGLE_LIST_ENTRY() self.Lock = v_uint32() class ERESOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemResourcesList = LIST_ENTRY() self.OwnerTable = v_ptr64() self.ActiveCount = v_uint16() self.Flag = v_uint16() self._pad0020 = v_bytes(size=4) self.SharedWaiters = v_ptr64() self.ExclusiveWaiters = v_ptr64() self.OwnerEntry = OWNER_ENTRY() self.ActiveEntries = v_uint32() self.ContentionCount = v_uint32() self.NumberOfSharedWaiters = v_uint32() self.NumberOfExclusiveWaiters = v_uint32() self.Reserved2 = v_ptr64() self.Address = v_ptr64() self.SpinLock = v_uint64() class KGUARDED_MUTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self._pad0008 = v_bytes(size=4) self.Owner = v_ptr64() self.Contention = v_uint32() self._pad0018 = v_bytes(size=4) self.Gate = KGATE() self.KernelApcDisable = v_uint16() self.SpecialApcDisable = v_uint16() class ACCESS_REASONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data = v_bytes(size=128) # FIXME Unknown Array Type class TP_TASK_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExecuteCallback = v_ptr64() self.Unposted = v_ptr64() class _unnamed_9727(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NotificationType = v_uint32() self._pad0008 = v_bytes(size=4) self.SafeToRecurse = v_uint8() class _unnamed_9726(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SyncType = v_uint32() self.PageProtection = v_uint32() class _unnamed_9725(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ResourceToRelease = v_ptr64() class _unnamed_9724(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EndingOffset = v_ptr64() self.ResourceToRelease = v_ptr64() class _unnamed_9649(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Channel = v_uint32() self.Port = v_uint32() self.Reserved1 = v_uint32() class _unnamed_9646(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Raw = _unnamed_9641() class _unnamed_9641(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Group = v_uint16() self.MessageCount = v_uint16() self.Vector = v_uint32() self.Affinity = v_uint64() class _unnamed_9728(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Argument1 = v_ptr64() self.Argument2 = v_ptr64() self.Argument3 = v_ptr64() self.Argument4 = v_ptr64() self.Argument5 = v_ptr64() class EX_PUSH_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locked = v_uint64() class XSTATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mask = v_uint64() self.Length = v_uint32() self.Reserved1 = v_uint32() self.Area = v_ptr64() self.Buffer = v_ptr64() class HEAP_FREE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PreviousBlockPrivateData = v_ptr64() self.Size = v_uint16() self.Flags = v_uint8() self.SmallTagIndex = v_uint8() self.PreviousSize = v_uint16() self.SegmentOffset = v_uint8() self.UnusedBytes = v_uint8() self.FreeList = LIST_ENTRY() class KSTACK_COUNT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Value = v_uint32() class _unnamed_8031(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PowerSequence = v_ptr64() class HEAP_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.SegmentSignature = v_uint32() self.SegmentFlags = v_uint32() self.SegmentListEntry = LIST_ENTRY() self.Heap = v_ptr64() self.BaseAddress = v_ptr64() self.NumberOfPages = v_uint32() self._pad0040 = v_bytes(size=4) self.FirstEntry = v_ptr64() self.LastValidEntry = v_ptr64() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.SegmentAllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self._pad0060 = v_bytes(size=4) self.UCRSegmentList = LIST_ENTRY() class WHEA_ERROR_RECORD_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.Revision = WHEA_REVISION() self.SignatureEnd = v_uint32() self.SectionCount = v_uint16() self.Severity = v_uint32() self.ValidBits = WHEA_ERROR_RECORD_HEADER_VALIDBITS() self.Length = v_uint32() self.Timestamp = WHEA_TIMESTAMP() self.PlatformId = GUID() self.PartitionId = GUID() self.CreatorId = GUID() self.NotifyType = GUID() self.RecordId = v_uint64() self.Flags = WHEA_ERROR_RECORD_HEADER_FLAGS() self.PersistenceInfo = WHEA_PERSISTENCE_INFO() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type class EVENT_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Id = v_uint16() self.Version = v_uint8() self.Channel = v_uint8() self.Level = v_uint8() self.Opcode = v_uint8() self.Task = v_uint16() self.Keyword = v_uint64() class _unnamed_9587(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = _unnamed_10176() class MMSUPPORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WorkingSetMutex = EX_PUSH_LOCK() self.ExitGate = v_ptr64() self.AccessLog = v_ptr64() self.WorkingSetExpansionLinks = LIST_ENTRY() self.AgeDistribution = v_bytes(size=28) # FIXME Unknown Array Type self.MinimumWorkingSetSize = v_uint32() self.WorkingSetSize = v_uint32() self.WorkingSetPrivateSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.ChargedWslePages = v_uint32() self.ActualWslePages = v_uint32() self.WorkingSetSizeOverhead = v_uint32() self.PeakWorkingSetSize = v_uint32() self.HardFaultCount = v_uint32() self.VmWorkingSetList = v_ptr64() self.NextPageColor = v_uint16() self.LastTrimStamp = v_uint16() self.PageFaultCount = v_uint32() self.RepurposeCount = v_uint32() self.Spare = v_bytes(size=8) # FIXME Unknown Array Type self.Flags = MMSUPPORT_FLAGS() class PSP_CPU_SHARE_CAPTURED_WEIGHT_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CapturedCpuShareWeight = v_uint32() self.CapturedTotalWeight = v_uint32() class FLS_CALLBACK_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class ACL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AclRevision = v_uint8() self.Sbz1 = v_uint8() self.AclSize = v_uint16() self.AceCount = v_uint16() self.Sbz2 = v_uint16() class _unnamed_7739(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityContext = v_ptr64() self.Options = v_uint32() self._pad0010 = v_bytes(size=4) self.Reserved = v_uint16() self.ShareAccess = v_uint16() self._pad0018 = v_bytes(size=4) self.Parameters = v_ptr64() class LIST_ENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint64() self.Blink = v_uint64() class WAIT_CONTEXT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitQueueEntry = KDEVICE_QUEUE_ENTRY() self.DeviceRoutine = v_ptr64() self.DeviceContext = v_ptr64() self.NumberOfMapRegisters = v_uint32() self._pad0030 = v_bytes(size=4) self.DeviceObject = v_ptr64() self.CurrentIrp = v_ptr64() self.BufferChainingDpc = v_ptr64() class SE_AUDIT_PROCESS_CREATION_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ImageFileName = v_ptr64() class ACTIVATION_CONTEXT_STACK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ActiveFrame = v_ptr64() self.FrameListCache = LIST_ENTRY() self.Flags = v_uint32() self.NextCookieSequenceNumber = v_uint32() self.StackId = v_uint32() class LDR_DATA_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InLoadOrderLinks = LIST_ENTRY() self.InMemoryOrderLinks = LIST_ENTRY() self.InInitializationOrderLinks = LIST_ENTRY() self.DllBase = v_ptr64() self.EntryPoint = v_ptr64() self.SizeOfImage = v_uint32() self._pad0048 = v_bytes(size=4) self.FullDllName = UNICODE_STRING() self.BaseDllName = UNICODE_STRING() self.Flags = v_uint32() self.LoadCount = v_uint16() self.TlsIndex = v_uint16() self.HashLinks = LIST_ENTRY() self.TimeDateStamp = v_uint32() self._pad0088 = v_bytes(size=4) self.EntryPointActivationContext = v_ptr64() self.PatchInformation = v_ptr64() self.ForwarderLinks = LIST_ENTRY() self.ServiceTagLinks = LIST_ENTRY() self.StaticLinks = LIST_ENTRY() self.ContextInformation = v_ptr64() self.OriginalBase = v_uint64() self.LoadTime = LARGE_INTEGER() class LOOKASIDE_LIST_EX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE_POOL() class TEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.EnvironmentPointer = v_ptr64() self.ClientId = CLIENT_ID() self.ActiveRpcHandle = v_ptr64() self.ThreadLocalStoragePointer = v_ptr64() self.ProcessEnvironmentBlock = v_ptr64() self.LastErrorValue = v_uint32() self.CountOfOwnedCriticalSections = v_uint32() self.CsrClientThread = v_ptr64() self.Win32ThreadInfo = v_ptr64() self.User32Reserved = v_bytes(size=104) # FIXME Unknown Array Type self.UserReserved = v_bytes(size=20) # FIXME Unknown Array Type self._pad0100 = v_bytes(size=4) self.WOW32Reserved = v_ptr64() self.CurrentLocale = v_uint32() self.FpSoftwareStatusRegister = v_uint32() self.SystemReserved1 = v_bytes(size=432) # FIXME Unknown Array Type self.ExceptionCode = v_uint32() self._pad02c8 = v_bytes(size=4) self.ActivationContextStackPointer = v_ptr64() self.SpareBytes = v_bytes(size=24) # FIXME Unknown Array Type self.TxFsContext = v_uint32() self._pad02f0 = v_bytes(size=4) self.GdiTebBatch = GDI_TEB_BATCH() self.RealClientId = CLIENT_ID() self.GdiCachedProcessHandle = v_ptr64() self.GdiClientPID = v_uint32() self.GdiClientTID = v_uint32() self.GdiThreadLocalInfo = v_ptr64() self.Win32ClientInfo = v_bytes(size=496) # FIXME Unknown Array Type self.glDispatchTable = v_bytes(size=1864) # FIXME Unknown Array Type self.glReserved1 = v_bytes(size=232) # FIXME Unknown Array Type self.glReserved2 = v_ptr64() self.glSectionInfo = v_ptr64() self.glSection = v_ptr64() self.glTable = v_ptr64() self.glCurrentRC = v_ptr64() self.glContext = v_ptr64() self.LastStatusValue = v_uint32() self._pad1258 = v_bytes(size=4) self.StaticUnicodeString = UNICODE_STRING() self.StaticUnicodeBuffer = v_bytes(size=522) # FIXME Unknown Array Type self._pad1478 = v_bytes(size=6) self.DeallocationStack = v_ptr64() self.TlsSlots = v_bytes(size=512) # FIXME Unknown Array Type self.TlsLinks = LIST_ENTRY() self.Vdm = v_ptr64() self.ReservedForNtRpc = v_ptr64() self.DbgSsReserved = v_bytes(size=16) # FIXME Unknown Array Type self.HardErrorMode = v_uint32() self._pad16b8 = v_bytes(size=4) self.Instrumentation = v_bytes(size=88) # FIXME Unknown Array Type self.ActivityId = GUID() self.SubProcessTag = v_ptr64() self.EtwLocalData = v_ptr64() self.EtwTraceData = v_ptr64() self.WinSockData = v_ptr64() self.GdiBatchCount = v_uint32() self.CurrentIdealProcessor = PROCESSOR_NUMBER() self.GuaranteedStackBytes = v_uint32() self._pad1750 = v_bytes(size=4) self.ReservedForPerf = v_ptr64() self.ReservedForOle = v_ptr64() self.WaitingOnLoaderLock = v_uint32() self._pad1768 = v_bytes(size=4) self.SavedPriorityState = v_ptr64() self.SoftPatchPtr1 = v_uint64() self.ThreadPoolData = v_ptr64() self.TlsExpansionSlots = v_ptr64() self.DeallocationBStore = v_ptr64() self.BStoreLimit = v_ptr64() self.MuiGeneration = v_uint32() self.IsImpersonating = v_uint32() self.NlsCache = v_ptr64() self.pShimData = v_ptr64() self.HeapVirtualAffinity = v_uint32() self._pad17b8 = v_bytes(size=4) self.CurrentTransactionHandle = v_ptr64() self.ActiveFrame = v_ptr64() self.FlsData = v_ptr64() self.PreferredLanguages = v_ptr64() self.UserPrefLanguages = v_ptr64() self.MergedPrefLanguages = v_ptr64() self.MuiImpersonation = v_uint32() self.CrossTebFlags = v_uint16() self.SameTebFlags = v_uint16() self.TxnScopeEnterCallback = v_ptr64() self.TxnScopeExitCallback = v_ptr64() self.TxnScopeContext = v_ptr64() self.LockCount = v_uint32() self.SpareUlong0 = v_uint32() self.ResourceRetValue = v_ptr64() class EX_RUNDOWN_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint64() class XSAVE_FORMAT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint16() self.StatusWord = v_uint16() self.TagWord = v_uint8() self.Reserved1 = v_uint8() self.ErrorOpcode = v_uint16() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint16() self.Reserved2 = v_uint16() self.DataOffset = v_uint32() self.DataSelector = v_uint16() self.Reserved3 = v_uint16() self.MxCsr = v_uint32() self.MxCsr_Mask = v_uint32() self.FloatRegisters = v_uint32() self.XmmRegisters = v_uint32() self.Reserved4 = v_bytes(size=96) # FIXME Unknown Array Type class PO_DIAG_STACK_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StackDepth = v_uint32() self._pad0008 = v_bytes(size=4) self.Stack = v_bytes(size=8) # FIXME Unknown Array Type class IMAGE_DOS_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.e_magic = v_uint16() self.e_cblp = v_uint16() self.e_cp = v_uint16() self.e_crlc = v_uint16() self.e_cparhdr = v_uint16() self.e_minalloc = v_uint16() self.e_maxalloc = v_uint16() self.e_ss = v_uint16() self.e_sp = v_uint16() self.e_csum = v_uint16() self.e_ip = v_uint16() self.e_cs = v_uint16() self.e_lfarlc = v_uint16() self.e_ovno = v_uint16() self.e_res = v_bytes(size=8) # FIXME Unknown Array Type self.e_oemid = v_uint16() self.e_oeminfo = v_uint16() self.e_res2 = v_bytes(size=20) # FIXME Unknown Array Type self.e_lfanew = v_uint32() class RTL_DYNAMIC_HASH_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Linkage = LIST_ENTRY() self.Signature = v_uint64() class MMADDRESS_NODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u1 = _unnamed_9413() self.LeftChild = v_ptr64() self.RightChild = v_ptr64() self.StartingVpn = v_uint64() self.EndingVpn = v_uint64() class TXN_PARAMETER_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.TxFsContext = v_uint16() self._pad0008 = v_bytes(size=4) self.TransactionObject = v_ptr64() class _unnamed_6010(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseMiddle = v_uint8() self.Flags1 = v_uint8() self.Flags2 = v_uint8() self.BaseHigh = v_uint8() class _unnamed_6011(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseMiddle = v_uint32() class QUAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UseThisFieldToCopy = v_uint64() class HEAP_TUNING_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CommittThresholdShift = v_uint32() self._pad0008 = v_bytes(size=4) self.MaxPreCommittThreshold = v_uint64() class _unnamed_7839(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self._pad0008 = v_bytes(size=4) self.EaList = v_ptr64() self.EaListLength = v_uint32() self._pad0018 = v_bytes(size=4) self.EaIndex = v_uint32() class KPRCB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MxCsr = v_uint32() self.LegacyNumber = v_uint8() self.ReservedMustBeZero = v_uint8() self.InterruptRequest = v_uint8() self.IdleHalt = v_uint8() self.CurrentThread = v_ptr64() self.NextThread = v_ptr64() self.IdleThread = v_ptr64() self.NestingLevel = v_uint8() self.PrcbPad00 = v_bytes(size=3) # FIXME Unknown Array Type self.Number = v_uint32() self.RspBase = v_uint64() self.PrcbLock = v_uint64() self.PrcbPad01 = v_uint64() self.ProcessorState = KPROCESSOR_STATE() self.CpuType = v_uint8() self.CpuID = v_uint8() self.CpuStep = v_uint16() self.MHz = v_uint32() self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.MinorVersion = v_uint16() self.MajorVersion = v_uint16() self.BuildType = v_uint8() self.CpuVendor = v_uint8() self.CoresPerPhysicalProcessor = v_uint8() self.LogicalProcessorsPerCore = v_uint8() self.ApicMask = v_uint32() self.CFlushSize = v_uint32() self.AcpiReserved = v_ptr64() self.InitialApicId = v_uint32() self.Stride = v_uint32() self.Group = v_uint16() self._pad0660 = v_bytes(size=6) self.GroupSetMember = v_uint64() self.GroupIndex = v_uint8() self._pad0670 = v_bytes(size=7) self.LockQueue = v_uint8() self.PPLookasideList = v_uint8() self.PPNPagedLookasideList = v_uint8() self.PPPagedLookasideList = v_uint8() self.PacketBarrier = v_uint32() self._pad2088 = v_bytes(size=4) self.DeferredReadyListHead = SINGLE_LIST_ENTRY() self.MmPageFaultCount = v_uint32() self.MmCopyOnWriteCount = v_uint32() self.MmTransitionCount = v_uint32() self.MmDemandZeroCount = v_uint32() self.MmPageReadCount = v_uint32() self.MmPageReadIoCount = v_uint32() self.MmDirtyPagesWriteCount = v_uint32() self.MmDirtyWriteIoCount = v_uint32() self.MmMappedPagesWriteCount = v_uint32() self.MmMappedWriteIoCount = v_uint32() self.KeSystemCalls = v_uint32() self.KeContextSwitches = v_uint32() self.CcFastReadNoWait = v_uint32() self.CcFastReadWait = v_uint32() self.CcFastReadNotPossible = v_uint32() self.CcCopyReadNoWait = v_uint32() self.CcCopyReadWait = v_uint32() self.CcCopyReadNoWaitMiss = v_uint32() self.LookasideIrpFloat = v_uint32() self.IoReadOperationCount = v_uint32() self.IoWriteOperationCount = v_uint32() self.IoOtherOperationCount = v_uint32() self.IoReadTransferCount = LARGE_INTEGER() self.IoWriteTransferCount = LARGE_INTEGER() self.IoOtherTransferCount = LARGE_INTEGER() self.TargetCount = v_uint32() self.IpiFrozen = v_uint32() self._pad2180 = v_bytes(size=120) self.DpcData = v_uint32() self.DpcStack = v_ptr64() self.MaximumDpcQueueDepth = v_uint32() self.DpcRequestRate = v_uint32() self.MinimumDpcRate = v_uint32() self.DpcLastCount = v_uint32() self.ThreadDpcEnable = v_uint8() self.QuantumEnd = v_uint8() self.DpcRoutineActive = v_uint8() self.IdleSchedule = v_uint8() self.DpcRequestSummary = v_uint32() self.TimerHand = v_uint32() self.MasterOffset = v_uint32() self.LastTick = v_uint32() self.UnusedPad = v_uint32() self.PrcbPad50 = v_bytes(size=16) # FIXME Unknown Array Type self.TimerTable = KTIMER_TABLE() self.DpcGate = KGATE() self.PrcbPad52 = v_ptr64() self.CallDpc = KDPC() self.ClockKeepAlive = v_uint32() self.ClockCheckSlot = v_uint8() self.ClockPollCycle = v_uint8() self.NmiActive = v_uint16() self.DpcWatchdogPeriod = v_uint32() self.DpcWatchdogCount = v_uint32() self.TickOffset = v_uint64() self.KeSpinLockOrdering = v_uint32() self.PrcbPad70 = v_uint32() self.WaitListHead = LIST_ENTRY() self.WaitLock = v_uint64() self.ReadySummary = v_uint32() self.QueueIndex = v_uint32() self.TimerExpirationDpc = KDPC() self.PrcbPad72 = v_bytes(size=32) # FIXME Unknown Array Type self.DispatcherReadyListHead = v_bytes(size=32) # FIXME Unknown Array Type self.InterruptCount = v_uint32() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.DpcTime = v_uint32() self.InterruptTime = v_uint32() self.AdjustDpcThreshold = v_uint32() self.DebuggerSavedIRQL = v_uint8() self.PrcbPad80 = v_bytes(size=7) # FIXME Unknown Array Type self.DpcTimeCount = v_uint32() self.DpcTimeLimit = v_uint32() self.PeriodicCount = v_uint32() self.PeriodicBias = v_uint32() self.AvailableTime = v_uint32() self.KeExceptionDispatchCount = v_uint32() self.ParentNode = v_ptr64() self.StartCycles = v_uint64() self.PrcbPad82 = v_bytes(size=24) # FIXME Unknown Array Type self.MmSpinLockOrdering = v_uint32() self.PageColor = v_uint32() self.NodeColor = v_uint32() self.NodeShiftedColor = v_uint32() self.SecondaryColorMask = v_uint32() self.PrcbPad83 = v_uint32() self.CycleTime = v_uint64() self.CcFastMdlReadNoWait = v_uint32() self.CcFastMdlReadWait = v_uint32() self.CcFastMdlReadNotPossible = v_uint32() self.CcMapDataNoWait = v_uint32() self.CcMapDataWait = v_uint32() self.CcPinMappedDataCount = v_uint32() self.CcPinReadNoWait = v_uint32() self.CcPinReadWait = v_uint32() self.CcMdlReadNoWait = v_uint32() self.CcMdlReadWait = v_uint32() self.CcLazyWriteHotSpots = v_uint32() self.CcLazyWriteIos = v_uint32() self.CcLazyWritePages = v_uint32() self.CcDataFlushes = v_uint32() self.CcDataPages = v_uint32() self.CcLostDelayedWrites = v_uint32() self.CcFastReadResourceMiss = v_uint32() self.CcCopyReadWaitMiss = v_uint32() self.CcFastMdlReadResourceMiss = v_uint32() self.CcMapDataNoWaitMiss = v_uint32() self.CcMapDataWaitMiss = v_uint32() self.CcPinReadNoWaitMiss = v_uint32() self.CcPinReadWaitMiss = v_uint32() self.CcMdlReadNoWaitMiss = v_uint32() self.CcMdlReadWaitMiss = v_uint32() self.CcReadAheadIos = v_uint32() self.MmCacheTransitionCount = v_uint32() self.MmCacheReadCount = v_uint32() self.MmCacheIoCount = v_uint32() self.PrcbPad91 = v_bytes(size=4) # FIXME Unknown Array Type self.RuntimeAccumulation = v_uint64() self.PowerState = PROCESSOR_POWER_STATE() self.PrcbPad92 = v_bytes(size=16) # FIXME Unknown Array Type self.KeAlignmentFixupCount = v_uint32() self._pad4918 = v_bytes(size=4) self.DpcWatchdogDpc = KDPC() self.DpcWatchdogTimer = KTIMER() self.Cache = KTIMER() self.CacheCount = v_uint32() self.CachedCommit = v_uint32() self.CachedResidentAvailable = v_uint32() self.HyperPte = v_ptr64() self.WheaInfo = v_ptr64() self.EtwSupport = v_ptr64() self._pad4a00 = v_bytes(size=8) self.InterruptObjectPool = SLIST_HEADER() self.HypercallPageList = SLIST_HEADER() self.HypercallPageVirtual = v_ptr64() self.VirtualApicAssist = v_ptr64() self.StatisticsPage = v_ptr64() self.RateControl = v_ptr64() self.CacheProcessorMask = v_bytes(size=40) # FIXME Unknown Array Type self.PackageProcessorSet = KAFFINITY_EX() self.CoreProcessorSet = v_uint64() self.PebsIndexAddress = v_ptr64() self.PrcbPad93 = v_bytes(size=96) # FIXME Unknown Array Type self.SpinLockAcquireCount = v_uint32() self.SpinLockContentionCount = v_uint32() self.SpinLockSpinCount = v_uint32() self.IpiSendRequestBroadcastCount = v_uint32() self.IpiSendRequestRoutineCount = v_uint32() self.IpiSendSoftwareInterruptCount = v_uint32() self.ExInitializeResourceCount = v_uint32() self.ExReInitializeResourceCount = v_uint32() self.ExDeleteResourceCount = v_uint32() self.ExecutiveResourceAcquiresCount = v_uint32() self.ExecutiveResourceContentionsCount = v_uint32() self.ExecutiveResourceReleaseExclusiveCount = v_uint32() self.ExecutiveResourceReleaseSharedCount = v_uint32() self.ExecutiveResourceConvertsCount = v_uint32() self.ExAcqResExclusiveAttempts = v_uint32() self.ExAcqResExclusiveAcquiresExclusive = v_uint32() self.ExAcqResExclusiveAcquiresExclusiveRecursive = v_uint32() self.ExAcqResExclusiveWaits = v_uint32() self.ExAcqResExclusiveNotAcquires = v_uint32() self.ExAcqResSharedAttempts = v_uint32() self.ExAcqResSharedAcquiresExclusive = v_uint32() self.ExAcqResSharedAcquiresShared = v_uint32() self.ExAcqResSharedAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedWaits = v_uint32() self.ExAcqResSharedNotAcquires = v_uint32() self.ExAcqResSharedStarveExclusiveAttempts = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresExclusive = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresShared = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedStarveExclusiveWaits = v_uint32() self.ExAcqResSharedStarveExclusiveNotAcquires = v_uint32() self.ExAcqResSharedWaitForExclusiveAttempts = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresExclusive = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresShared = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedWaitForExclusiveWaits = v_uint32() self.ExAcqResSharedWaitForExclusiveNotAcquires = v_uint32() self.ExSetResOwnerPointerExclusive = v_uint32() self.ExSetResOwnerPointerSharedNew = v_uint32() self.ExSetResOwnerPointerSharedOld = v_uint32() self.ExTryToAcqExclusiveAttempts = v_uint32() self.ExTryToAcqExclusiveAcquires = v_uint32() self.ExBoostExclusiveOwner = v_uint32() self.ExBoostSharedOwners = v_uint32() self.ExEtwSynchTrackingNotificationsCount = v_uint32() self.ExEtwSynchTrackingNotificationsAccountedCount = v_uint32() self.VendorString = v_bytes(size=13) # FIXME Unknown Array Type self.PrcbPad10 = v_bytes(size=3) # FIXME Unknown Array Type self.FeatureBits = v_uint32() self._pad4bd0 = v_bytes(size=4) self.UpdateSignature = LARGE_INTEGER() self.Context = v_ptr64() self.ContextFlags = v_uint32() self._pad4be8 = v_bytes(size=4) self.ExtendedState = v_ptr64() self._pad4c00 = v_bytes(size=16) self.Mailbox = v_ptr64() self._pad4c80 = v_bytes(size=120) self.RequestMailbox = v_ptr64() class RTL_DYNAMIC_HASH_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.Shift = v_uint32() self.TableSize = v_uint32() self.Pivot = v_uint32() self.DivisorMask = v_uint32() self.NumEntries = v_uint32() self.NonEmptyBuckets = v_uint32() self.NumEnumerators = v_uint32() self.Directory = v_ptr64() class _unnamed_5519(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LongFunction = v_uint32() class KAFFINITY_EX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint16() self.Size = v_uint16() self.Reserved = v_uint32() self.Bitmap = v_bytes(size=32) # FIXME Unknown Array Type class DEVICE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.ReferenceCount = v_uint32() self.DriverObject = v_ptr64() self.NextDevice = v_ptr64() self.AttachedDevice = v_ptr64() self.CurrentIrp = v_ptr64() self.Timer = v_ptr64() self.Flags = v_uint32() self.Characteristics = v_uint32() self.Vpb = v_ptr64() self.DeviceExtension = v_ptr64() self.DeviceType = v_uint32() self.StackSize = v_uint8() self._pad0050 = v_bytes(size=3) self.Queue = _unnamed_7211() self.AlignmentRequirement = v_uint32() self._pad00a0 = v_bytes(size=4) self.DeviceQueue = KDEVICE_QUEUE() self.Dpc = KDPC() self.ActiveThreadCount = v_uint32() self._pad0110 = v_bytes(size=4) self.SecurityDescriptor = v_ptr64() self.DeviceLock = KEVENT() self.SectorSize = v_uint16() self.Spare1 = v_uint16() self._pad0138 = v_bytes(size=4) self.DeviceObjectExtension = v_ptr64() self.Reserved = v_ptr64() class USER_MEMORY_CACHE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UserBlocks = SLIST_HEADER() self.AvailableBlocks = v_uint32() class _unnamed_5516(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() class KTSS64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved0 = v_uint32() self.Rsp0 = v_uint64() self.Rsp1 = v_uint64() self.Rsp2 = v_uint64() self.Ist = v_bytes(size=64) # FIXME Unknown Array Type self.Reserved1 = v_uint64() self.Reserved2 = v_uint16() self.IoMapBase = v_uint16() class EX_PUSH_LOCK_WAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WakeEvent = KEVENT() self.Next = v_ptr64() self.Last = v_ptr64() self.Previous = v_ptr64() self.ShareCount = v_uint32() self.Flags = v_uint32() class KERNEL_STACK_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StackBase = v_uint64() self.StackLimit = v_uint64() self.KernelStack = v_uint64() self.InitialStack = v_uint64() self.ActualLimit = v_uint64() class _unnamed_10176(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Alignment = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class IO_STACK_LOCATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorFunction = v_uint8() self.MinorFunction = v_uint8() self.Flags = v_uint8() self.Control = v_uint8() self._pad0008 = v_bytes(size=4) self.Parameters = _unnamed_7661() self.DeviceObject = v_ptr64() self.FileObject = v_ptr64() self.CompletionRoutine = v_ptr64() self.Context = v_ptr64() class KNODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PagedPoolSListHead = SLIST_HEADER() self.NonPagedPoolSListHead = SLIST_HEADER() self.Affinity = GROUP_AFFINITY() self.ProximityId = v_uint32() self.NodeNumber = v_uint16() self.PrimaryNodeNumber = v_uint16() self.MaximumProcessors = v_uint8() self.Color = v_uint8() self.Flags = flags() self.NodePad0 = v_uint8() self.Seed = v_uint32() self.MmShiftedColor = v_uint32() self._pad0068 = v_bytes(size=4) self.FreeCount = v_bytes(size=16) # FIXME Unknown Array Type self.Right = v_uint32() self.Left = v_uint32() self.CachedKernelStacks = CACHED_KSTACK_LIST() self.ParkLock = v_uint32() self.NodePad1 = v_uint32() class _unnamed_8078(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Argument1 = v_ptr64() self.Argument2 = v_ptr64() self.Argument3 = v_ptr64() self.Argument4 = v_ptr64() class XSAVE_AREA_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mask = v_uint64() self.Reserved = v_bytes(size=56) # FIXME Unknown Array Type class MM_DRIVER_VERIFIER_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint32() self.RaiseIrqls = v_uint32() self.AcquireSpinLocks = v_uint32() self.SynchronizeExecutions = v_uint32() self.AllocationsAttempted = v_uint32() self.AllocationsSucceeded = v_uint32() self.AllocationsSucceededSpecialPool = v_uint32() self.AllocationsWithNoTag = v_uint32() self.TrimRequests = v_uint32() self.Trims = v_uint32() self.AllocationsFailed = v_uint32() self.AllocationsFailedDeliberately = v_uint32() self.Loads = v_uint32() self.Unloads = v_uint32() self.UnTrackedPool = v_uint32() self.UserTrims = v_uint32() self.CurrentPagedPoolAllocations = v_uint32() self.CurrentNonPagedPoolAllocations = v_uint32() self.PeakPagedPoolAllocations = v_uint32() self.PeakNonPagedPoolAllocations = v_uint32() self.PagedBytes = v_uint64() self.NonPagedBytes = v_uint64() self.PeakPagedBytes = v_uint64() self.PeakNonPagedBytes = v_uint64() self.BurstAllocationsFailedDeliberately = v_uint32() self.SessionTrims = v_uint32() self.OptionChanges = v_uint32() self.VerifyMode = v_uint32() self.PreviousBucketName = UNICODE_STRING() self.ActivityCounter = v_uint32() self.PreviousActivityCounter = v_uint32() self.WorkerTrimRequests = v_uint32() class _unnamed_8073(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ProviderId = v_uint64() self.DataPath = v_ptr64() self.BufferSize = v_uint32() self._pad0018 = v_bytes(size=4) self.Buffer = v_ptr64() class RTL_USER_PROCESS_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MaximumLength = v_uint32() self.Length = v_uint32() self.Flags = v_uint32() self.DebugFlags = v_uint32() self.ConsoleHandle = v_ptr64() self.ConsoleFlags = v_uint32() self._pad0020 = v_bytes(size=4) self.StandardInput = v_ptr64() self.StandardOutput = v_ptr64() self.StandardError = v_ptr64() self.CurrentDirectory = CURDIR() self.DllPath = UNICODE_STRING() self.ImagePathName = UNICODE_STRING() self.CommandLine = UNICODE_STRING() self.Environment = v_ptr64() self.StartingX = v_uint32() self.StartingY = v_uint32() self.CountX = v_uint32() self.CountY = v_uint32() self.CountCharsX = v_uint32() self.CountCharsY = v_uint32() self.FillAttribute = v_uint32() self.WindowFlags = v_uint32() self.ShowWindowFlags = v_uint32() self._pad00b0 = v_bytes(size=4) self.WindowTitle = UNICODE_STRING() self.DesktopInfo = UNICODE_STRING() self.ShellInfo = UNICODE_STRING() self.RuntimeData = UNICODE_STRING() self.CurrentDirectores = UNICODE_STRING() self.EnvironmentSize = v_uint64() self.EnvironmentVersion = v_uint64() class IO_RESOURCE_REQUIREMENTS_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.SlotNumber = v_uint32() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type self.AlternativeLists = v_uint32() self.List = v_uint32() class HEAP_BUCKET_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalBlocks = v_uint32() self.SubSegmentCounts = v_uint32()
Python
# Version: 5.1 # Architecture: i386 import vstruct from vstruct.primitives import * DEVICE_RELATION_TYPE = v_enum() DEVICE_RELATION_TYPE.BusRelations = 0 DEVICE_RELATION_TYPE.EjectionRelations = 1 DEVICE_RELATION_TYPE.PowerRelations = 2 DEVICE_RELATION_TYPE.RemovalRelations = 3 DEVICE_RELATION_TYPE.TargetDeviceRelation = 4 DEVICE_RELATION_TYPE.SingleBusRelations = 5 IO_ALLOCATION_ACTION = v_enum() IO_ALLOCATION_ACTION.KeepObject = 0 IO_ALLOCATION_ACTION.DeallocateObject = 1 IO_ALLOCATION_ACTION.DeallocateObjectKeepRegisters = 2 BUS_QUERY_ID_TYPE = v_enum() BUS_QUERY_ID_TYPE.BusQueryDeviceID = 0 BUS_QUERY_ID_TYPE.BusQueryHardwareIDs = 1 BUS_QUERY_ID_TYPE.BusQueryCompatibleIDs = 2 BUS_QUERY_ID_TYPE.BusQueryInstanceID = 3 BUS_QUERY_ID_TYPE.BusQueryDeviceSerialNumber = 4 NT_PRODUCT_TYPE = v_enum() NT_PRODUCT_TYPE.NtProductWinNt = 0 NT_PRODUCT_TYPE.NtProductLanManNt = 1 NT_PRODUCT_TYPE.NtProductServer = 2 DEVICE_POWER_STATE = v_enum() DEVICE_POWER_STATE.PowerDeviceUnspecified = 0 DEVICE_POWER_STATE.PowerDeviceD0 = 1 DEVICE_POWER_STATE.PowerDeviceD1 = 2 DEVICE_POWER_STATE.PowerDeviceD2 = 3 DEVICE_POWER_STATE.PowerDeviceD3 = 4 DEVICE_POWER_STATE.PowerDeviceMaximum = 5 KSPIN_LOCK_QUEUE_NUMBER = v_enum() KSPIN_LOCK_QUEUE_NUMBER.LockQueueDispatcherLock = 0 KSPIN_LOCK_QUEUE_NUMBER.LockQueueContextSwapLock = 1 KSPIN_LOCK_QUEUE_NUMBER.LockQueuePfnLock = 2 KSPIN_LOCK_QUEUE_NUMBER.LockQueueSystemSpaceLock = 3 KSPIN_LOCK_QUEUE_NUMBER.LockQueueVacbLock = 4 KSPIN_LOCK_QUEUE_NUMBER.LockQueueMasterLock = 5 KSPIN_LOCK_QUEUE_NUMBER.LockQueueNonPagedPoolLock = 6 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoCancelLock = 7 KSPIN_LOCK_QUEUE_NUMBER.LockQueueWorkQueueLock = 8 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoVpbLock = 9 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoDatabaseLock = 10 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoCompletionLock = 11 KSPIN_LOCK_QUEUE_NUMBER.LockQueueNtfsStructLock = 12 KSPIN_LOCK_QUEUE_NUMBER.LockQueueAfdWorkQueueLock = 13 KSPIN_LOCK_QUEUE_NUMBER.LockQueueBcbLock = 14 KSPIN_LOCK_QUEUE_NUMBER.LockQueueMaximumLock = 15 FSINFOCLASS = v_enum() FSINFOCLASS.FileFsVolumeInformation = 0 FSINFOCLASS.FileFsLabelInformation = 1 FSINFOCLASS.FileFsSizeInformation = 2 FSINFOCLASS.FileFsDeviceInformation = 3 FSINFOCLASS.FileFsAttributeInformation = 4 FSINFOCLASS.FileFsControlInformation = 5 FSINFOCLASS.FileFsFullSizeInformation = 6 FSINFOCLASS.FileFsObjectIdInformation = 7 FSINFOCLASS.FileFsDriverPathInformation = 8 FSINFOCLASS.FileFsMaximumInformation = 9 POOL_TYPE = v_enum() POOL_TYPE.NonPagedPool = 0 POOL_TYPE.PagedPool = 1 POOL_TYPE.NonPagedPoolMustSucceed = 2 POOL_TYPE.DontUseThisType = 3 POOL_TYPE.NonPagedPoolCacheAligned = 4 POOL_TYPE.PagedPoolCacheAligned = 5 POOL_TYPE.NonPagedPoolCacheAlignedMustS = 6 POOL_TYPE.MaxPoolType = 7 POOL_TYPE.NonPagedPoolSession = 8 POOL_TYPE.PagedPoolSession = 9 POOL_TYPE.NonPagedPoolMustSucceedSession = 10 POOL_TYPE.DontUseThisTypeSession = 11 POOL_TYPE.NonPagedPoolCacheAlignedSession = 12 POOL_TYPE.PagedPoolCacheAlignedSession = 13 POOL_TYPE.NonPagedPoolCacheAlignedMustSSession = 14 MODE = v_enum() MODE.KernelMode = 0 MODE.UserMode = 1 MODE.MaximumMode = 2 FS_FILTER_SECTION_SYNC_TYPE = v_enum() FS_FILTER_SECTION_SYNC_TYPE.SyncTypeOther = 0 FS_FILTER_SECTION_SYNC_TYPE.SyncTypeCreateSection = 1 OB_OPEN_REASON = v_enum() OB_OPEN_REASON.ObCreateHandle = 0 OB_OPEN_REASON.ObOpenHandle = 1 OB_OPEN_REASON.ObDuplicateHandle = 2 OB_OPEN_REASON.ObInheritHandle = 3 OB_OPEN_REASON.ObMaxOpenReason = 4 DEVICE_TEXT_TYPE = v_enum() DEVICE_TEXT_TYPE.DeviceTextDescription = 0 DEVICE_TEXT_TYPE.DeviceTextLocationInformation = 1 POWER_STATE_TYPE = v_enum() POWER_STATE_TYPE.SystemPowerState = 0 POWER_STATE_TYPE.DevicePowerState = 1 FILE_INFORMATION_CLASS = v_enum() FILE_INFORMATION_CLASS.FileDirectoryInformation = 0 FILE_INFORMATION_CLASS.FileFullDirectoryInformation = 1 FILE_INFORMATION_CLASS.FileBothDirectoryInformation = 2 FILE_INFORMATION_CLASS.FileBasicInformation = 3 FILE_INFORMATION_CLASS.FileStandardInformation = 4 FILE_INFORMATION_CLASS.FileInternalInformation = 5 FILE_INFORMATION_CLASS.FileEaInformation = 6 FILE_INFORMATION_CLASS.FileAccessInformation = 7 FILE_INFORMATION_CLASS.FileNameInformation = 8 FILE_INFORMATION_CLASS.FileRenameInformation = 9 FILE_INFORMATION_CLASS.FileLinkInformation = 10 FILE_INFORMATION_CLASS.FileNamesInformation = 11 FILE_INFORMATION_CLASS.FileDispositionInformation = 12 FILE_INFORMATION_CLASS.FilePositionInformation = 13 FILE_INFORMATION_CLASS.FileFullEaInformation = 14 FILE_INFORMATION_CLASS.FileModeInformation = 15 FILE_INFORMATION_CLASS.FileAlignmentInformation = 16 FILE_INFORMATION_CLASS.FileAllInformation = 17 FILE_INFORMATION_CLASS.FileAllocationInformation = 18 FILE_INFORMATION_CLASS.FileEndOfFileInformation = 19 FILE_INFORMATION_CLASS.FileAlternateNameInformation = 20 FILE_INFORMATION_CLASS.FileStreamInformation = 21 FILE_INFORMATION_CLASS.FilePipeInformation = 22 FILE_INFORMATION_CLASS.FilePipeLocalInformation = 23 FILE_INFORMATION_CLASS.FilePipeRemoteInformation = 24 FILE_INFORMATION_CLASS.FileMailslotQueryInformation = 25 FILE_INFORMATION_CLASS.FileMailslotSetInformation = 26 FILE_INFORMATION_CLASS.FileCompressionInformation = 27 FILE_INFORMATION_CLASS.FileObjectIdInformation = 28 FILE_INFORMATION_CLASS.FileCompletionInformation = 29 FILE_INFORMATION_CLASS.FileMoveClusterInformation = 30 FILE_INFORMATION_CLASS.FileQuotaInformation = 31 FILE_INFORMATION_CLASS.FileReparsePointInformation = 32 FILE_INFORMATION_CLASS.FileNetworkOpenInformation = 33 FILE_INFORMATION_CLASS.FileAttributeTagInformation = 34 FILE_INFORMATION_CLASS.FileTrackingInformation = 35 FILE_INFORMATION_CLASS.FileIdBothDirectoryInformation = 36 FILE_INFORMATION_CLASS.FileIdFullDirectoryInformation = 37 FILE_INFORMATION_CLASS.FileValidDataLengthInformation = 38 FILE_INFORMATION_CLASS.FileShortNameInformation = 39 FILE_INFORMATION_CLASS.FileMaximumInformation = 40 EXCEPTION_DISPOSITION = v_enum() EXCEPTION_DISPOSITION.ExceptionContinueExecution = 0 EXCEPTION_DISPOSITION.ExceptionContinueSearch = 1 EXCEPTION_DISPOSITION.ExceptionNestedException = 2 EXCEPTION_DISPOSITION.ExceptionCollidedUnwind = 3 PF_SCENARIO_TYPE = v_enum() PF_SCENARIO_TYPE.PfApplicationLaunchScenarioType = 0 PF_SCENARIO_TYPE.PfSystemBootScenarioType = 1 PF_SCENARIO_TYPE.PfMaxScenarioType = 2 SECURITY_OPERATION_CODE = v_enum() SECURITY_OPERATION_CODE.SetSecurityDescriptor = 0 SECURITY_OPERATION_CODE.QuerySecurityDescriptor = 1 SECURITY_OPERATION_CODE.DeleteSecurityDescriptor = 2 SECURITY_OPERATION_CODE.AssignSecurityDescriptor = 3 PP_NPAGED_LOOKASIDE_NUMBER = v_enum() PP_NPAGED_LOOKASIDE_NUMBER.LookasideSmallIrpList = 0 PP_NPAGED_LOOKASIDE_NUMBER.LookasideLargeIrpList = 1 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMdlList = 2 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCreateInfoList = 3 PP_NPAGED_LOOKASIDE_NUMBER.LookasideNameBufferList = 4 PP_NPAGED_LOOKASIDE_NUMBER.LookasideTwilightList = 5 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCompletionList = 6 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMaximumList = 7 SECURITY_IMPERSONATION_LEVEL = v_enum() SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous = 0 SECURITY_IMPERSONATION_LEVEL.SecurityIdentification = 1 SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation = 2 SECURITY_IMPERSONATION_LEVEL.SecurityDelegation = 3 DEVICE_USAGE_NOTIFICATION_TYPE = v_enum() DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeUndefined = 0 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypePaging = 1 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeHibernation = 2 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeDumpFile = 3 INTERFACE_TYPE = v_enum() INTERFACE_TYPE.InterfaceTypeUndefined = 0 INTERFACE_TYPE.Internal = 1 INTERFACE_TYPE.Isa = 2 INTERFACE_TYPE.Eisa = 3 INTERFACE_TYPE.MicroChannel = 4 INTERFACE_TYPE.TurboChannel = 5 INTERFACE_TYPE.PCIBus = 6 INTERFACE_TYPE.VMEBus = 7 INTERFACE_TYPE.NuBus = 8 INTERFACE_TYPE.PCMCIABus = 9 INTERFACE_TYPE.CBus = 10 INTERFACE_TYPE.MPIBus = 11 INTERFACE_TYPE.MPSABus = 12 INTERFACE_TYPE.ProcessorInternal = 13 INTERFACE_TYPE.InternalPowerBus = 14 INTERFACE_TYPE.PNPISABus = 15 INTERFACE_TYPE.PNPBus = 16 INTERFACE_TYPE.MaximumInterfaceType = 17 KWAIT_REASON = v_enum() KWAIT_REASON.Executive = 0 KWAIT_REASON.FreePage = 1 KWAIT_REASON.PageIn = 2 KWAIT_REASON.PoolAllocation = 3 KWAIT_REASON.DelayExecution = 4 KWAIT_REASON.Suspended = 5 KWAIT_REASON.UserRequest = 6 KWAIT_REASON.WrExecutive = 7 KWAIT_REASON.WrFreePage = 8 KWAIT_REASON.WrPageIn = 9 KWAIT_REASON.WrPoolAllocation = 10 KWAIT_REASON.WrDelayExecution = 11 KWAIT_REASON.WrSuspended = 12 KWAIT_REASON.WrUserRequest = 13 KWAIT_REASON.WrEventPair = 14 KWAIT_REASON.WrQueue = 15 KWAIT_REASON.WrLpcReceive = 16 KWAIT_REASON.WrLpcReply = 17 KWAIT_REASON.WrVirtualMemory = 18 KWAIT_REASON.WrPageOut = 19 KWAIT_REASON.WrRendezvous = 20 KWAIT_REASON.Spare2 = 21 KWAIT_REASON.Spare3 = 22 KWAIT_REASON.Spare4 = 23 KWAIT_REASON.Spare5 = 24 KWAIT_REASON.Spare6 = 25 KWAIT_REASON.WrKernel = 26 KWAIT_REASON.MaximumWaitReason = 27 ALTERNATIVE_ARCHITECTURE_TYPE = v_enum() ALTERNATIVE_ARCHITECTURE_TYPE.StandardDesign = 0 ALTERNATIVE_ARCHITECTURE_TYPE.NEC98x86 = 1 ALTERNATIVE_ARCHITECTURE_TYPE.EndAlternatives = 2 MEMORY_TYPE = v_enum() MEMORY_TYPE.MemoryExceptionBlock = 0 MEMORY_TYPE.MemorySystemBlock = 1 MEMORY_TYPE.MemoryFree = 2 MEMORY_TYPE.MemoryBad = 3 MEMORY_TYPE.MemoryLoadedProgram = 4 MEMORY_TYPE.MemoryFirmwareTemporary = 5 MEMORY_TYPE.MemoryFirmwarePermanent = 6 MEMORY_TYPE.MemoryFreeContiguous = 7 MEMORY_TYPE.MemorySpecialMemory = 8 MEMORY_TYPE.MemoryMaximum = 9 PS_QUOTA_TYPE = v_enum() PS_QUOTA_TYPE.PsNonPagedPool = 0 PS_QUOTA_TYPE.PsPagedPool = 1 PS_QUOTA_TYPE.PsPageFile = 2 PS_QUOTA_TYPE.PsQuotaTypes = 3 ReplacesCorHdrNumericDefines = v_enum() ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY = 0 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED = 1 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY = 2 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED = 3 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA = 4 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR_V2 = 5 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR = 6 ReplacesCorHdrNumericDefines.COR_VERSION_MINOR = 7 ReplacesCorHdrNumericDefines.COR_DELETED_NAME_LENGTH = 8 ReplacesCorHdrNumericDefines.COR_VTABLEGAP_NAME_LENGTH = 9 ReplacesCorHdrNumericDefines.NATIVE_TYPE_MAX_CB = 10 ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 11 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_METHODRVA = 12 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_EHRVA = 13 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_BASICBLOCK = 14 ReplacesCorHdrNumericDefines.COR_VTABLE_32BIT = 15 ReplacesCorHdrNumericDefines.COR_VTABLE_64BIT = 16 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED = 17 ReplacesCorHdrNumericDefines.COR_VTABLE_CALL_MOST_DERIVED = 18 ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE = 19 ReplacesCorHdrNumericDefines.MAX_CLASS_NAME = 20 ReplacesCorHdrNumericDefines.MAX_PACKAGE_NAME = 21 SYSTEM_POWER_STATE = v_enum() SYSTEM_POWER_STATE.PowerSystemUnspecified = 0 SYSTEM_POWER_STATE.PowerSystemWorking = 1 SYSTEM_POWER_STATE.PowerSystemSleeping1 = 2 SYSTEM_POWER_STATE.PowerSystemSleeping2 = 3 SYSTEM_POWER_STATE.PowerSystemSleeping3 = 4 SYSTEM_POWER_STATE.PowerSystemHibernate = 5 SYSTEM_POWER_STATE.PowerSystemShutdown = 6 SYSTEM_POWER_STATE.PowerSystemMaximum = 7 MEMORY_CACHING_TYPE_ORIG = v_enum() MEMORY_CACHING_TYPE_ORIG.MmFrameBufferCached = 0 POWER_ACTION = v_enum() POWER_ACTION.PowerActionNone = 0 POWER_ACTION.PowerActionReserved = 1 POWER_ACTION.PowerActionSleep = 2 POWER_ACTION.PowerActionHibernate = 3 POWER_ACTION.PowerActionShutdown = 4 POWER_ACTION.PowerActionShutdownReset = 5 POWER_ACTION.PowerActionShutdownOff = 6 POWER_ACTION.PowerActionWarmEject = 7 class KEXECUTE_OPTIONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExecuteDisable = v_uint8() class KPRCB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinorVersion = v_uint16() self.MajorVersion = v_uint16() self.CurrentThread = v_ptr32() self.NextThread = v_ptr32() self.IdleThread = v_ptr32() self.Number = v_uint8() self.Reserved = v_uint8() self.BuildType = v_uint16() self.SetMember = v_uint32() self.CpuType = v_uint8() self.CpuID = v_uint8() self.CpuStep = v_uint16() self.ProcessorState = KPROCESSOR_STATE() self.KernelReserved = v_bytes(size=64) # FIXME Unknown Array Type self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.PrcbPad0 = v_bytes(size=92) # FIXME Unknown Array Type self.LockQueue = v_bytes(size=92) # FIXME Unknown Array Type self.PrcbPad1 = v_bytes(size=8) # FIXME Unknown Array Type self.NpxThread = v_ptr32() self.InterruptCount = v_uint32() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.DpcTime = v_uint32() self.DebugDpcTime = v_uint32() self.InterruptTime = v_uint32() self.AdjustDpcThreshold = v_uint32() self.PageColor = v_uint32() self.SkipTick = v_uint32() self.MultiThreadSetBusy = v_uint8() self.Spare2 = v_bytes(size=3) # FIXME Unknown Array Type self.ParentNode = v_ptr32() self.MultiThreadProcessorSet = v_uint32() self.MultiThreadSetMaster = v_ptr32() self.ThreadStartCount = v_bytes(size=8) # FIXME Unknown Array Type self.CcFastReadNoWait = v_uint32() self.CcFastReadWait = v_uint32() self.CcFastReadNotPossible = v_uint32() self.CcCopyReadNoWait = v_uint32() self.CcCopyReadWait = v_uint32() self.CcCopyReadNoWaitMiss = v_uint32() self.KeAlignmentFixupCount = v_uint32() self.KeContextSwitches = v_uint32() self.KeDcacheFlushCount = v_uint32() self.KeExceptionDispatchCount = v_uint32() self.KeFirstLevelTbFills = v_uint32() self.KeFloatingEmulationCount = v_uint32() self.KeIcacheFlushCount = v_uint32() self.KeSecondLevelTbFills = v_uint32() self.KeSystemCalls = v_uint32() self.SpareCounter0 = v_bytes(size=4) # FIXME Unknown Array Type self.PPLookasideList = v_bytes(size=4) # FIXME Unknown Array Type self.PPNPagedLookasideList = v_bytes(size=4) # FIXME Unknown Array Type self.PPPagedLookasideList = v_bytes(size=4) # FIXME Unknown Array Type self.PacketBarrier = v_uint32() self.ReverseStall = v_uint32() self.IpiFrame = v_ptr32() self.PrcbPad2 = v_bytes(size=52) # FIXME Unknown Array Type self.CurrentPacket = v_bytes(size=12) # FIXME Unknown Array Type self.TargetSet = v_uint32() self.WorkerRoutine = v_ptr32() self.IpiFrozen = v_uint32() self.PrcbPad3 = v_bytes(size=40) # FIXME Unknown Array Type self.RequestSummary = v_uint32() self.SignalDone = v_ptr32() self.PrcbPad4 = v_bytes(size=56) # FIXME Unknown Array Type self.DpcListHead = LIST_ENTRY() self.DpcStack = v_ptr32() self.DpcCount = v_uint32() self.DpcQueueDepth = v_uint32() self.DpcRoutineActive = v_uint32() self.DpcInterruptRequested = v_uint32() self.DpcLastCount = v_uint32() self.DpcRequestRate = v_uint32() self.MaximumDpcQueueDepth = v_uint32() self.MinimumDpcRate = v_uint32() self.QuantumEnd = v_uint32() self.PrcbPad5 = v_bytes(size=16) # FIXME Unknown Array Type self.DpcLock = v_uint32() self.PrcbPad6 = v_bytes(size=28) # FIXME Unknown Array Type self.CallDpc = KDPC() self.ChainedInterruptList = v_ptr32() self.LookasideIrpFloat = v_uint32() self.SpareFields0 = v_bytes(size=24) # FIXME Unknown Array Type self.VendorString = v_bytes(size=13) # FIXME Unknown Array Type self.InitialApicId = v_uint8() self.LogicalProcessorsPerPhysicalProcessor = v_uint8() self._pad0910 = v_bytes(size=1) self.MHz = v_uint32() self.FeatureBits = v_uint32() self.UpdateSignature = LARGE_INTEGER() self.NpxSaveArea = FX_SAVE_AREA() self.PowerState = PROCESSOR_POWER_STATE() class OBJECT_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.RootDirectory = v_ptr32() self.ObjectName = v_ptr32() self.Attributes = v_uint32() self.SecurityDescriptor = v_ptr32() self.SecurityQualityOfService = v_ptr32() class IO_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() class KSYSTEM_TIME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.High1Time = v_uint32() self.High2Time = v_uint32() class CM_FULL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.PartialResourceList = CM_PARTIAL_RESOURCE_LIST() class EXCEPTION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionCode = v_uint32() self.ExceptionFlags = v_uint32() self.ExceptionRecord = v_ptr32() self.ExceptionAddress = v_ptr32() self.NumberParameters = v_uint32() self.ExceptionInformation = v_bytes(size=60) # FIXME Unknown Array Type class SID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.SubAuthorityCount = v_uint8() self.IdentifierAuthority = SID_IDENTIFIER_AUTHORITY() self.SubAuthority = v_bytes(size=4) # FIXME Unknown Array Type class PS_JOB_TOKEN_FILTER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CapturedSidCount = v_uint32() self.CapturedSids = v_ptr32() self.CapturedSidsLength = v_uint32() self.CapturedGroupCount = v_uint32() self.CapturedGroups = v_ptr32() self.CapturedGroupsLength = v_uint32() self.CapturedPrivilegeCount = v_uint32() self.CapturedPrivileges = v_ptr32() self.CapturedPrivilegesLength = v_uint32() class KSPIN_LOCK_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Lock = v_ptr32() class FAST_IO_DISPATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFastIoDispatch = v_uint32() self.FastIoCheckIfPossible = v_ptr32() self.FastIoRead = v_ptr32() self.FastIoWrite = v_ptr32() self.FastIoQueryBasicInfo = v_ptr32() self.FastIoQueryStandardInfo = v_ptr32() self.FastIoLock = v_ptr32() self.FastIoUnlockSingle = v_ptr32() self.FastIoUnlockAll = v_ptr32() self.FastIoUnlockAllByKey = v_ptr32() self.FastIoDeviceControl = v_ptr32() self.AcquireFileForNtCreateSection = v_ptr32() self.ReleaseFileForNtCreateSection = v_ptr32() self.FastIoDetachDevice = v_ptr32() self.FastIoQueryNetworkOpenInfo = v_ptr32() self.AcquireForModWrite = v_ptr32() self.MdlRead = v_ptr32() self.MdlReadComplete = v_ptr32() self.PrepareMdlWrite = v_ptr32() self.MdlWriteComplete = v_ptr32() self.FastIoReadCompressed = v_ptr32() self.FastIoWriteCompressed = v_ptr32() self.MdlReadCompleteCompressed = v_ptr32() self.MdlWriteCompleteCompressed = v_ptr32() self.FastIoQueryOpen = v_ptr32() self.ReleaseForModWrite = v_ptr32() self.AcquireForCcFlush = v_ptr32() self.ReleaseForCcFlush = v_ptr32() class FS_FILTER_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbacks = v_uint32() self.Reserved = v_uint32() self.PreAcquireForSectionSynchronization = v_ptr32() self.PostAcquireForSectionSynchronization = v_ptr32() self.PreReleaseForSectionSynchronization = v_ptr32() self.PostReleaseForSectionSynchronization = v_ptr32() self.PreAcquireForCcFlush = v_ptr32() self.PostAcquireForCcFlush = v_ptr32() self.PreReleaseForCcFlush = v_ptr32() self.PostReleaseForCcFlush = v_ptr32() self.PreAcquireForModifiedPageWriter = v_ptr32() self.PostAcquireForModifiedPageWriter = v_ptr32() self.PreReleaseForModifiedPageWriter = v_ptr32() self.PostReleaseForModifiedPageWriter = v_ptr32() class IMAGE_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Machine = v_uint16() self.NumberOfSections = v_uint16() self.TimeDateStamp = v_uint32() self.PointerToSymbolTable = v_uint32() self.NumberOfSymbols = v_uint32() self.SizeOfOptionalHeader = v_uint16() self.Characteristics = v_uint16() class IO_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Option = v_uint8() self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Spare1 = v_uint8() self.Flags = v_uint16() self.Spare2 = v_uint16() self.u = unnamed() class EX_PUSH_LOCK_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locks = v_bytes(size=128) # FIXME Unknown Array Type class MMWSL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DosPath = UNICODE_STRING() self.Handle = v_ptr32() class RTL_TRACE_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Count = v_uint32() self.Size = v_uint32() self.UserCount = v_uint32() self.UserSize = v_uint32() self.UserContext = v_ptr32() self.Next = v_ptr32() self.Trace = v_ptr32() class IMAGE_OPTIONAL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint16() self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.BaseOfData = v_uint32() self.ImageBase = v_uint32() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint32() self.SizeOfStackCommit = v_uint32() self.SizeOfHeapReserve = v_uint32() self.SizeOfHeapCommit = v_uint32() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = v_uint32() class SCSI_REQUEST_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class IMAGE_NT_HEADERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER() class ETHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Tcb = KTHREAD() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.ExitStatus = v_uint32() self.PostBlockList = LIST_ENTRY() self.TerminationPort = v_ptr32() self.ActiveTimerListLock = v_uint32() self.ActiveTimerListHead = LIST_ENTRY() self.Cid = CLIENT_ID() self.LpcReplySemaphore = KSEMAPHORE() self.LpcReplyMessage = v_ptr32() self.ImpersonationInfo = v_ptr32() self.IrpList = LIST_ENTRY() self.TopLevelIrp = v_uint32() self.DeviceToVerify = v_ptr32() self.ThreadsProcess = v_ptr32() self.StartAddress = v_ptr32() self.Win32StartAddress = v_ptr32() self.ThreadListEntry = LIST_ENTRY() self.RundownProtect = EX_RUNDOWN_REF() self.ThreadLock = EX_PUSH_LOCK() self.LpcReplyMessageId = v_uint32() self.ReadClusterSize = v_uint32() self.GrantedAccess = v_uint32() self.CrossThreadFlags = v_uint32() self.SameThreadPassiveFlags = v_uint32() self.SameThreadApcFlags = v_uint32() self.ForwardClusterOnly = v_uint8() self.DisablePageFaultClustering = v_uint8() class PEB_LDR_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Initialized = v_uint8() self._pad0008 = v_bytes(size=3) self.SsHandle = v_ptr32() self.InLoadOrderModuleList = LIST_ENTRY() self.InMemoryOrderModuleList = LIST_ENTRY() self.InInitializationOrderModuleList = LIST_ENTRY() self.EntryInProgress = v_ptr32() class EPROCESS_QUOTA_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Usage = v_uint32() self.Limit = v_uint32() self.Peak = v_uint32() self.Return = v_uint32() class HARDWARE_PTE_X86(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class HEAP_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.PreviousSize = v_uint16() self.SmallTagIndex = v_uint8() self.Flags = v_uint8() self.UnusedBytes = v_uint8() self.SegmentIndex = v_uint8() class RTL_CRITICAL_SECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DebugInfo = v_ptr32() self.LockCount = v_uint32() self.RecursionCount = v_uint32() self.OwningThread = v_ptr32() self.LockSemaphore = v_ptr32() self.SpinCount = v_uint32() class HANDLE_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TableCode = v_uint32() self.QuotaProcess = v_ptr32() self.UniqueProcessId = v_ptr32() self.HandleTableLock = v_ptr32() self.HandleTableList = LIST_ENTRY() self.HandleContentionEvent = EX_PUSH_LOCK() self.DebugInfo = v_ptr32() self.ExtraInfoPages = v_uint32() self.FirstFree = v_uint32() self.LastFree = v_uint32() self.NextHandleNeedingPool = v_uint32() self.HandleCount = v_uint32() self.Flags = v_uint32() class SECURITY_SUBJECT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientToken = v_ptr32() self.ImpersonationLevel = v_uint32() self.PrimaryToken = v_ptr32() self.ProcessAuditId = v_ptr32() class KDEVICE_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceListHead = LIST_ENTRY() self.Lock = v_uint32() self.Busy = v_uint8() class FLOATING_SAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint32() self.StatusWord = v_uint32() self.TagWord = v_uint32() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.RegisterArea = v_bytes(size=80) # FIXME Unknown Array Type self.Cr0NpxState = v_uint32() class DPH_HEAP_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.pNextAlloc = v_ptr32() self.pVirtualBlock = v_ptr32() self.nVirtualBlockSize = v_uint32() self.nVirtualAccessSize = v_uint32() self.pUserAllocation = v_ptr32() self.nUserRequestedSize = v_uint32() self.nUserActualSize = v_uint32() self.UserValue = v_ptr32() self.UserFlags = v_uint32() self.StackTrace = v_ptr32() class KQUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.EntryListHead = LIST_ENTRY() self.CurrentCount = v_uint32() self.MaximumCount = v_uint32() self.ThreadListHead = LIST_ENTRY() class RTL_TRACE_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Database = v_ptr32() self.NextSegment = v_ptr32() self.TotalSize = v_uint32() self.SegmentStart = v_ptr32() self.SegmentEnd = v_ptr32() self.SegmentFree = v_ptr32() class CM_PARTIAL_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.PartialDescriptors = v_uint32() class IO_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityQos = v_ptr32() self.AccessState = v_ptr32() self.DesiredAccess = v_uint32() self.FullCreateOptions = v_uint32() class LUID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Luid = LUID() self.Attributes = v_uint32() class TERMINATION_PORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Port = v_ptr32() class IO_CLIENT_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextExtension = v_ptr32() self.ClientIdentificationAddress = v_ptr32() class DEVICE_CAPABILITIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.DeviceD1 = v_uint32() self.Address = v_uint32() self.UINumber = v_uint32() self.DeviceState = v_uint32() self.SystemWake = v_uint32() self.DeviceWake = v_uint32() self.D1Latency = v_uint32() self.D2Latency = v_uint32() self.D3Latency = v_uint32() class INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.Context = v_ptr32() self.InterfaceReference = v_ptr32() self.InterfaceDereference = v_ptr32() class HEAP_FREE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.PreviousSize = v_uint16() self.SmallTagIndex = v_uint8() self.Flags = v_uint8() self.UnusedBytes = v_uint8() self.SegmentIndex = v_uint8() self.FreeList = LIST_ENTRY() class KTHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.MutantListHead = LIST_ENTRY() self.InitialStack = v_ptr32() self.StackLimit = v_ptr32() self.Teb = v_ptr32() self.TlsArray = v_ptr32() self.KernelStack = v_ptr32() self.DebugActive = v_uint8() self.State = v_uint8() self.Alerted = v_bytes(size=2) # FIXME Unknown Array Type self.Iopl = v_uint8() self.NpxState = v_uint8() self.Saturation = v_uint8() self.Priority = v_uint8() self.ApcState = KAPC_STATE() self.ContextSwitches = v_uint32() self.IdleSwapBlock = v_uint8() self.Spare0 = v_bytes(size=3) # FIXME Unknown Array Type self.WaitStatus = v_uint32() self.WaitIrql = v_uint8() self.WaitMode = v_uint8() self.WaitNext = v_uint8() self.WaitReason = v_uint8() self.WaitBlockList = v_ptr32() self.WaitListEntry = LIST_ENTRY() self.WaitTime = v_uint32() self.BasePriority = v_uint8() self.DecrementCount = v_uint8() self.PriorityDecrement = v_uint8() self.Quantum = v_uint8() self.WaitBlock = v_uint8() self.LegoData = v_ptr32() self.KernelApcDisable = v_uint32() self.UserAffinity = v_uint32() self.SystemAffinityActive = v_uint8() self.PowerState = v_uint8() self.NpxIrql = v_uint8() self.InitialNode = v_uint8() self.ServiceTable = v_ptr32() self.Queue = v_ptr32() self.ApcQueueLock = v_uint32() self._pad00f0 = v_bytes(size=4) self.Timer = KTIMER() self.QueueListEntry = LIST_ENTRY() self.SoftAffinity = v_uint32() self.Affinity = v_uint32() self.Preempted = v_uint8() self.ProcessReadyQueue = v_uint8() self.KernelStackResident = v_uint8() self.NextProcessor = v_uint8() self.CallbackStack = v_ptr32() self.Win32Thread = v_ptr32() self.TrapFrame = v_ptr32() self.ApcStatePointer = v_bytes(size=8) # FIXME Unknown Array Type self.PreviousMode = v_uint8() self.EnableStackSwap = v_uint8() self.LargeStack = v_uint8() self.ResourceIndex = v_uint8() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.SavedApcState = KAPC_STATE() self.Alertable = v_uint8() self.ApcStateIndex = v_uint8() self.ApcQueueable = v_uint8() self.AutoAlignment = v_uint8() self.StackBase = v_ptr32() self.SuspendApc = KAPC() self.SuspendSemaphore = KSEMAPHORE() self.ThreadListEntry = LIST_ENTRY() self.FreezeCount = v_uint8() self.SuspendCount = v_uint8() self.IdealProcessor = v_uint8() self.DisableBoost = v_uint8() class PP_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P = v_ptr32() self.L = v_ptr32() class IMAGE_DATA_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.Size = v_uint32() class KAPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Spare0 = v_uint32() self.Thread = v_ptr32() self.ApcListEntry = LIST_ENTRY() self.KernelRoutine = v_ptr32() self.RundownRoutine = v_ptr32() self.NormalRoutine = v_ptr32() self.NormalContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.ApcStateIndex = v_uint8() self.ApcMode = v_uint8() self.Inserted = v_uint8() class PROCESSOR_IDLE_TIMES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartTime = v_uint64() self.EndTime = v_uint64() self.IdleHandlerReserved = v_bytes(size=16) # FIXME Unknown Array Type class KWAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitListEntry = LIST_ENTRY() self.Thread = v_ptr32() self.Object = v_ptr32() self.NextWaitBlock = v_ptr32() self.WaitKey = v_uint16() self.WaitType = v_uint16() class KPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.ProfileListHead = LIST_ENTRY() self.DirectoryTableBase = v_bytes(size=8) # FIXME Unknown Array Type self.LdtDescriptor = KGDTENTRY() self.Int21Descriptor = KIDTENTRY() self.IopmOffset = v_uint16() self.Iopl = v_uint8() self.Unused = v_uint8() self.ActiveProcessors = v_uint32() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.ReadyListHead = LIST_ENTRY() self.SwapListEntry = SINGLE_LIST_ENTRY() self.VdmTrapcHandler = v_ptr32() self.ThreadListHead = LIST_ENTRY() self.ProcessLock = v_uint32() self.Affinity = v_uint32() self.StackCount = v_uint16() self.BasePriority = v_uint8() self.ThreadQuantum = v_uint8() self.AutoAlignment = v_uint8() self.State = v_uint8() self.ThreadSeed = v_uint8() self.DisableBoost = v_uint8() self.PowerState = v_uint8() self.DisableQuantum = v_uint8() self.IdealNode = v_uint8() self.Flags = KEXECUTE_OPTIONS() class DEVICE_OBJECT_POWER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFlags = v_uint32() self.Dr0 = v_uint32() self.Dr1 = v_uint32() self.Dr2 = v_uint32() self.Dr3 = v_uint32() self.Dr6 = v_uint32() self.Dr7 = v_uint32() self.FloatSave = FLOATING_SAVE_AREA() self.SegGs = v_uint32() self.SegFs = v_uint32() self.SegEs = v_uint32() self.SegDs = v_uint32() self.Edi = v_uint32() self.Esi = v_uint32() self.Ebx = v_uint32() self.Edx = v_uint32() self.Ecx = v_uint32() self.Eax = v_uint32() self.Ebp = v_uint32() self.Eip = v_uint32() self.SegCs = v_uint32() self.EFlags = v_uint32() self.Esp = v_uint32() self.SegSs = v_uint32() self.ExtendedRegisters = v_bytes(size=512) # FIXME Unknown Array Type class EX_FAST_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr32() class HEAP_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint32() self.TagIndex = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.TagName = v_bytes(size=48) # FIXME Unknown Array Type class PAGEFAULT_HISTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentIndex = v_uint32() self.MaxIndex = v_uint32() self.SpinLock = v_uint32() self.Reserved = v_ptr32() self.WatchInfo = v_ptr32() class FILE_NETWORK_OPEN_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.FileAttributes = v_uint32() class DPH_HEAP_ROOT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.HeapFlags = v_uint32() self.HeapCritSect = v_ptr32() self.nRemoteLockAcquired = v_uint32() self.pVirtualStorageListHead = v_ptr32() self.pVirtualStorageListTail = v_ptr32() self.nVirtualStorageRanges = v_uint32() self.nVirtualStorageBytes = v_uint32() self.pBusyAllocationListHead = v_ptr32() self.pBusyAllocationListTail = v_ptr32() self.nBusyAllocations = v_uint32() self.nBusyAllocationBytesCommitted = v_uint32() self.pFreeAllocationListHead = v_ptr32() self.pFreeAllocationListTail = v_ptr32() self.nFreeAllocations = v_uint32() self.nFreeAllocationBytesCommitted = v_uint32() self.pAvailableAllocationListHead = v_ptr32() self.pAvailableAllocationListTail = v_ptr32() self.nAvailableAllocations = v_uint32() self.nAvailableAllocationBytesCommitted = v_uint32() self.pUnusedNodeListHead = v_ptr32() self.pUnusedNodeListTail = v_ptr32() self.nUnusedNodes = v_uint32() self.nBusyAllocationBytesAccessible = v_uint32() self.pNodePoolListHead = v_ptr32() self.pNodePoolListTail = v_ptr32() self.nNodePools = v_uint32() self.nNodePoolBytes = v_uint32() self.pNextHeapRoot = v_ptr32() self.pPrevHeapRoot = v_ptr32() self.nUnProtectionReferenceCount = v_uint32() self.InsideAllocateNode = v_uint32() self.ExtraFlags = v_uint32() self.Seed = v_uint32() self.NormalHeap = v_ptr32() self.CreateStackTrace = v_ptr32() self.FirstThread = v_ptr32() class OBJECT_HANDLE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HandleAttributes = v_uint32() self.GrantedAccess = v_uint32() class RTL_DRIVE_LETTER_CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint16() self.Length = v_uint16() self.TimeStamp = v_uint32() self.DosPath = STRING() class INITIAL_PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class ULARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class TEB_ACTIVE_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.Previous = v_ptr32() self.Context = v_ptr32() class RTL_TRACE_DATABASE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Flags = v_uint32() self.Tag = v_uint32() self.SegmentList = v_ptr32() self.MaximumSize = v_uint32() self.CurrentSize = v_uint32() self.Owner = v_ptr32() self.Lock = RTL_CRITICAL_SECTION() self.NoOfBuckets = v_uint32() self.Buckets = v_ptr32() self.HashFunction = v_ptr32() self.NoOfTraces = v_uint32() self.NoOfHits = v_uint32() self.HashCounter = v_bytes(size=64) # FIXME Unknown Array Type class GENERAL_LOOKASIDE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.Allocate = v_ptr32() self.Free = v_ptr32() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class EX_PUSH_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Waiting = v_uint32() class LDR_DATA_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InLoadOrderLinks = LIST_ENTRY() self.InMemoryOrderLinks = LIST_ENTRY() self.InInitializationOrderLinks = LIST_ENTRY() self.DllBase = v_ptr32() self.EntryPoint = v_ptr32() self.SizeOfImage = v_uint32() self.FullDllName = UNICODE_STRING() self.BaseDllName = UNICODE_STRING() self.Flags = v_uint32() self.LoadCount = v_uint16() self.TlsIndex = v_uint16() self.HashLinks = LIST_ENTRY() self.TimeDateStamp = v_uint32() self.EntryPointActivationContext = v_ptr32() self.PatchInformation = v_ptr32() class SLIST_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Alignment = v_uint64() class FXSAVE_FORMAT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint16() self.StatusWord = v_uint16() self.TagWord = v_uint16() self.ErrorOpcode = v_uint16() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.MXCsr = v_uint32() self.MXCsrMask = v_uint32() self.RegisterArea = v_bytes(size=128) # FIXME Unknown Array Type self.Reserved3 = v_bytes(size=128) # FIXME Unknown Array Type self.Reserved4 = v_bytes(size=224) # FIXME Unknown Array Type self.Align16Byte = v_bytes(size=8) # FIXME Unknown Array Type class unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Generic = unnamed() class OWNER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwnerThread = v_uint32() self.OwnerCount = v_uint32() class DPH_BLOCK_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartStamp = v_uint32() self.Heap = v_ptr32() self.RequestedSize = v_uint32() self.ActualSize = v_uint32() self.FreeQueue = LIST_ENTRY() self.StackTrace = v_ptr32() self.EndStamp = v_uint32() class DEVOBJ_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.PowerFlags = v_uint32() self.Dope = v_ptr32() self.ExtensionFlags = v_uint32() self.DeviceNode = v_ptr32() self.AttachedTo = v_ptr32() self.StartIoCount = v_uint32() self.StartIoKey = v_uint32() self.StartIoFlags = v_uint32() self.Vpb = v_ptr32() class PROCESSOR_PERF_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PercentFrequency = v_uint8() self.MinCapacity = v_uint8() self.Power = v_uint16() self.IncreaseLevel = v_uint8() self.DecreaseLevel = v_uint8() self.Flags = v_uint16() self.IncreaseTime = v_uint32() self.DecreaseTime = v_uint32() self.IncreaseCount = v_uint32() self.DecreaseCount = v_uint32() self.PerformanceTime = v_uint64() class MDL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Size = v_uint16() self.MdlFlags = v_uint16() self.Process = v_ptr32() self.MappedSystemVa = v_ptr32() self.StartVa = v_ptr32() self.ByteCount = v_uint32() self.ByteOffset = v_uint32() class KGDTENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LimitLow = v_uint16() self.BaseLow = v_uint16() self.HighWord = unnamed() class NAMED_PIPE_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NamedPipeType = v_uint32() self.ReadMode = v_uint32() self.CompletionMode = v_uint32() self.MaximumInstances = v_uint32() self.InboundQuota = v_uint32() self.OutboundQuota = v_uint32() self.DefaultTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class NT_TIB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionList = v_ptr32() self.StackBase = v_ptr32() self.StackLimit = v_ptr32() self.SubSystemTib = v_ptr32() self.FiberData = v_ptr32() self.ArbitraryUserPointer = v_ptr32() self.Self = v_ptr32() class HEAP_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.Signature = v_uint32() self.Flags = v_uint32() self.Heap = v_ptr32() self.LargestUnCommittedRange = v_uint32() self.BaseAddress = v_ptr32() self.NumberOfPages = v_uint32() self.FirstEntry = v_ptr32() self.LastValidEntry = v_ptr32() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.UnCommittedRanges = v_ptr32() self.AllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self.LastEntryInSegment = v_ptr32() class POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemState = v_uint32() class UNICODE_STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class TEB_ACTIVE_FRAME_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.FrameName = v_ptr32() class DRIVER_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Flags = v_uint32() self.DriverStart = v_ptr32() self.DriverSize = v_uint32() self.DriverSection = v_ptr32() self.DriverExtension = v_ptr32() self.DriverName = UNICODE_STRING() self.HardwareDatabase = v_ptr32() self.FastIoDispatch = v_ptr32() self.DriverInit = v_ptr32() self.DriverStartIo = v_ptr32() self.DriverUnload = v_ptr32() self.MajorFunction = v_bytes(size=112) # FIXME Unknown Array Type class ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OperationID = LUID() self.SecurityEvaluated = v_uint8() self.GenerateAudit = v_uint8() self.GenerateOnClose = v_uint8() self.PrivilegesAllocated = v_uint8() self.Flags = v_uint32() self.RemainingDesiredAccess = v_uint32() self.PreviouslyGrantedAccess = v_uint32() self.OriginalDesiredAccess = v_uint32() self.SubjectSecurityContext = SECURITY_SUBJECT_CONTEXT() self.SecurityDescriptor = v_ptr32() self.AuxData = v_ptr32() self.Privileges = unnamed() self.AuditPrivileges = v_uint8() self._pad0064 = v_bytes(size=3) self.ObjectName = UNICODE_STRING() self.ObjectTypeName = UNICODE_STRING() class EJOB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Event = KEVENT() self.JobLinks = LIST_ENTRY() self.ProcessListHead = LIST_ENTRY() self.JobLock = ERESOURCE() self.TotalUserTime = LARGE_INTEGER() self.TotalKernelTime = LARGE_INTEGER() self.ThisPeriodTotalUserTime = LARGE_INTEGER() self.ThisPeriodTotalKernelTime = LARGE_INTEGER() self.TotalPageFaultCount = v_uint32() self.TotalProcesses = v_uint32() self.ActiveProcesses = v_uint32() self.TotalTerminatedProcesses = v_uint32() self.PerProcessUserTimeLimit = LARGE_INTEGER() self.PerJobUserTimeLimit = LARGE_INTEGER() self.LimitFlags = v_uint32() self.MinimumWorkingSetSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.ActiveProcessLimit = v_uint32() self.Affinity = v_uint32() self.PriorityClass = v_uint8() self._pad00b0 = v_bytes(size=3) self.UIRestrictionsClass = v_uint32() self.SecurityLimitFlags = v_uint32() self.Token = v_ptr32() self.Filter = v_ptr32() self.EndOfJobTimeAction = v_uint32() self.CompletionPort = v_ptr32() self.CompletionKey = v_ptr32() self.SessionId = v_uint32() self.SchedulingClass = v_uint32() self._pad00d8 = v_bytes(size=4) self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() self.IoInfo = IO_COUNTERS() self.ProcessMemoryLimit = v_uint32() self.JobMemoryLimit = v_uint32() self.PeakProcessMemoryUsed = v_uint32() self.PeakJobMemoryUsed = v_uint32() self.CurrentJobMemoryUsed = v_uint32() self.MemoryLimitsLock = FAST_MUTEX() self.JobSetLinks = LIST_ENTRY() self.MemberLevel = v_uint32() self.JobFlags = v_uint32() class FILE_STANDARD_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.NumberOfLinks = v_uint32() self.DeletePending = v_uint8() self.Directory = v_uint8() class IMAGE_SECTION_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = v_bytes(size=8) # FIXME Unknown Array Type self.Misc = unnamed() self.VirtualAddress = v_uint32() self.SizeOfRawData = v_uint32() self.PointerToRawData = v_uint32() self.PointerToRelocations = v_uint32() self.PointerToLinenumbers = v_uint32() self.NumberOfRelocations = v_uint16() self.NumberOfLinenumbers = v_uint16() self.Characteristics = v_uint32() class EPROCESS_QUOTA_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.QuotaEntry = v_uint32() self.QuotaList = LIST_ENTRY() self.ReferenceCount = v_uint32() self.ProcessCount = v_uint32() class HANDLE_TRACE_DEBUG_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentStackIndex = v_uint32() self.TraceDb = v_uint32() class GDI_TEB_BATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint32() self.HDC = v_uint32() self.Buffer = v_bytes(size=1240) # FIXME Unknown Array Type class KPROCESSOR_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFrame = CONTEXT() self.SpecialRegisters = KSPECIAL_REGISTERS() class LIST_ENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint64() self.Blink = v_uint64() class WAIT_CONTEXT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitQueueEntry = KDEVICE_QUEUE_ENTRY() self.DeviceRoutine = v_ptr32() self.DeviceContext = v_ptr32() self.NumberOfMapRegisters = v_uint32() self.DeviceObject = v_ptr32() self.CurrentIrp = v_ptr32() self.BufferChainingDpc = v_ptr32() class PEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InheritedAddressSpace = v_uint8() self.ReadImageFileExecOptions = v_uint8() self.BeingDebugged = v_uint8() self.SpareBool = v_uint8() self.Mutant = v_ptr32() self.ImageBaseAddress = v_ptr32() self.Ldr = v_ptr32() self.ProcessParameters = v_ptr32() self.SubSystemData = v_ptr32() self.ProcessHeap = v_ptr32() self.FastPebLock = v_ptr32() self.FastPebLockRoutine = v_ptr32() self.FastPebUnlockRoutine = v_ptr32() self.EnvironmentUpdateCount = v_uint32() self.KernelCallbackTable = v_ptr32() self.SystemReserved = v_bytes(size=4) # FIXME Unknown Array Type self.AtlThunkSListPtr32 = v_uint32() self.FreeList = v_ptr32() self.TlsExpansionCounter = v_uint32() self.TlsBitmap = v_ptr32() self.TlsBitmapBits = v_bytes(size=8) # FIXME Unknown Array Type self.ReadOnlySharedMemoryBase = v_ptr32() self.ReadOnlySharedMemoryHeap = v_ptr32() self.ReadOnlyStaticServerData = v_ptr32() self.AnsiCodePageData = v_ptr32() self.OemCodePageData = v_ptr32() self.UnicodeCaseTableData = v_ptr32() self.NumberOfProcessors = v_uint32() self.NtGlobalFlag = v_uint32() self._pad0070 = v_bytes(size=4) self.CriticalSectionTimeout = LARGE_INTEGER() self.HeapSegmentReserve = v_uint32() self.HeapSegmentCommit = v_uint32() self.HeapDeCommitTotalFreeThreshold = v_uint32() self.HeapDeCommitFreeBlockThreshold = v_uint32() self.NumberOfHeaps = v_uint32() self.MaximumNumberOfHeaps = v_uint32() self.ProcessHeaps = v_ptr32() self.GdiSharedHandleTable = v_ptr32() self.ProcessStarterHelper = v_ptr32() self.GdiDCAttributeList = v_uint32() self.LoaderLock = v_ptr32() self.OSMajorVersion = v_uint32() self.OSMinorVersion = v_uint32() self.OSBuildNumber = v_uint16() self.OSCSDVersion = v_uint16() self.OSPlatformId = v_uint32() self.ImageSubsystem = v_uint32() self.ImageSubsystemMajorVersion = v_uint32() self.ImageSubsystemMinorVersion = v_uint32() self.ImageProcessAffinityMask = v_uint32() self.GdiHandleBuffer = v_bytes(size=136) # FIXME Unknown Array Type self.PostProcessInitRoutine = v_ptr32() self.TlsExpansionBitmap = v_ptr32() self.TlsExpansionBitmapBits = v_bytes(size=128) # FIXME Unknown Array Type self.SessionId = v_uint32() self.AppCompatFlags = ULARGE_INTEGER() self.AppCompatFlagsUser = ULARGE_INTEGER() self.pShimData = v_ptr32() self.AppCompatInfo = v_ptr32() self.CSDVersion = UNICODE_STRING() self.ActivationContextData = v_ptr32() self.ProcessAssemblyStorageMap = v_ptr32() self.SystemDefaultActivationContextData = v_ptr32() self.SystemAssemblyStorageMap = v_ptr32() self.MinimumStackCommit = v_uint32() class SE_AUDIT_PROCESS_CREATION_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ImageFileName = v_ptr32() class ACTIVATION_CONTEXT_STACK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.NextCookieSequenceNumber = v_uint32() self.ActiveFrame = v_ptr32() self.FrameListCache = LIST_ENTRY() class PROCESS_WS_WATCH_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FaultingPc = v_ptr32() self.FaultingVa = v_ptr32() class SID_IDENTIFIER_AUTHORITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Value = v_bytes(size=6) # FIXME Unknown Array Type class SECTION_OBJECT_POINTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSectionObject = v_ptr32() self.SharedCacheMap = v_ptr32() self.ImageSectionObject = v_ptr32() class STACK_TRACE_DATABASE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = unnamed() self.AcquireLockRoutine = v_ptr32() self.ReleaseLockRoutine = v_ptr32() self.OkayToLockRoutine = v_ptr32() self.PreCommitted = v_uint8() self.DumpInProgress = v_uint8() self._pad0048 = v_bytes(size=2) self.CommitBase = v_ptr32() self.CurrentLowerCommitLimit = v_ptr32() self.CurrentUpperCommitLimit = v_ptr32() self.NextFreeLowerMemory = v_ptr32() self.NextFreeUpperMemory = v_ptr32() self.NumberOfEntriesLookedUp = v_uint32() self.NumberOfEntriesAdded = v_uint32() self.EntryIndexArray = v_ptr32() self.NumberOfBuckets = v_uint32() self.Buckets = v_bytes(size=4) # FIXME Unknown Array Type class HEAP_UCR_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.ReservedSize = v_uint32() self.CommittedSize = v_uint32() self.filler = v_uint32() class TEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.EnvironmentPointer = v_ptr32() self.ClientId = CLIENT_ID() self.ActiveRpcHandle = v_ptr32() self.ThreadLocalStoragePointer = v_ptr32() self.ProcessEnvironmentBlock = v_ptr32() self.LastErrorValue = v_uint32() self.CountOfOwnedCriticalSections = v_uint32() self.CsrClientThread = v_ptr32() self.Win32ThreadInfo = v_ptr32() self.User32Reserved = v_bytes(size=104) # FIXME Unknown Array Type self.UserReserved = v_bytes(size=20) # FIXME Unknown Array Type self.WOW32Reserved = v_ptr32() self.CurrentLocale = v_uint32() self.FpSoftwareStatusRegister = v_uint32() self.SystemReserved1 = v_bytes(size=216) # FIXME Unknown Array Type self.ExceptionCode = v_uint32() self.ActivationContextStack = ACTIVATION_CONTEXT_STACK() self.SpareBytes1 = v_bytes(size=24) # FIXME Unknown Array Type self.GdiTebBatch = GDI_TEB_BATCH() self.RealClientId = CLIENT_ID() self.GdiCachedProcessHandle = v_ptr32() self.GdiClientPID = v_uint32() self.GdiClientTID = v_uint32() self.GdiThreadLocalInfo = v_ptr32() self.Win32ClientInfo = v_bytes(size=248) # FIXME Unknown Array Type self.glDispatchTable = v_bytes(size=932) # FIXME Unknown Array Type self.glReserved1 = v_bytes(size=116) # FIXME Unknown Array Type self.glReserved2 = v_ptr32() self.glSectionInfo = v_ptr32() self.glSection = v_ptr32() self.glTable = v_ptr32() self.glCurrentRC = v_ptr32() self.glContext = v_ptr32() self.LastStatusValue = v_uint32() self.StaticUnicodeString = UNICODE_STRING() self.StaticUnicodeBuffer = v_bytes(size=522) # FIXME Unknown Array Type self._pad0e0c = v_bytes(size=2) self.DeallocationStack = v_ptr32() self.TlsSlots = v_bytes(size=256) # FIXME Unknown Array Type self.TlsLinks = LIST_ENTRY() self.Vdm = v_ptr32() self.ReservedForNtRpc = v_ptr32() self.DbgSsReserved = v_bytes(size=8) # FIXME Unknown Array Type self.HardErrorsAreDisabled = v_uint32() self.Instrumentation = v_bytes(size=64) # FIXME Unknown Array Type self.WinSockData = v_ptr32() self.GdiBatchCount = v_uint32() self.InDbgPrint = v_uint8() self.FreeStackOnTermination = v_uint8() self.HasFiberData = v_uint8() self.IdealProcessor = v_uint8() self.Spare3 = v_uint32() self.ReservedForPerf = v_ptr32() self.ReservedForOle = v_ptr32() self.WaitingOnLoaderLock = v_uint32() self.Wx86Thread = Wx86ThreadState() self.TlsExpansionSlots = v_ptr32() self.ImpersonationLocale = v_uint32() self.IsImpersonating = v_uint32() self.NlsCache = v_ptr32() self.pShimData = v_ptr32() self.HeapVirtualAffinity = v_uint32() self.CurrentTransactionHandle = v_ptr32() self.ActiveFrame = v_ptr32() self.SafeThunkCall = v_uint8() self.BooleanSpare = v_bytes(size=3) # FIXME Unknown Array Type class KTRAP_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DbgEbp = v_uint32() self.DbgEip = v_uint32() self.DbgArgMark = v_uint32() self.DbgArgPointer = v_uint32() self.TempSegCs = v_uint32() self.TempEsp = v_uint32() self.Dr0 = v_uint32() self.Dr1 = v_uint32() self.Dr2 = v_uint32() self.Dr3 = v_uint32() self.Dr6 = v_uint32() self.Dr7 = v_uint32() self.SegGs = v_uint32() self.SegEs = v_uint32() self.SegDs = v_uint32() self.Edx = v_uint32() self.Ecx = v_uint32() self.Eax = v_uint32() self.PreviousPreviousMode = v_uint32() self.ExceptionList = v_ptr32() self.SegFs = v_uint32() self.Edi = v_uint32() self.Esi = v_uint32() self.Ebx = v_uint32() self.Ebp = v_uint32() self.ErrCode = v_uint32() self.Eip = v_uint32() self.SegCs = v_uint32() self.EFlags = v_uint32() self.HardwareEsp = v_uint32() self.HardwareSegSs = v_uint32() self.V86Es = v_uint32() self.V86Ds = v_uint32() self.V86Fs = v_uint32() self.V86Gs = v_uint32() class EX_RUNDOWN_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() class RTL_USER_PROCESS_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MaximumLength = v_uint32() self.Length = v_uint32() self.Flags = v_uint32() self.DebugFlags = v_uint32() self.ConsoleHandle = v_ptr32() self.ConsoleFlags = v_uint32() self.StandardInput = v_ptr32() self.StandardOutput = v_ptr32() self.StandardError = v_ptr32() self.CurrentDirectory = CURDIR() self.DllPath = UNICODE_STRING() self.ImagePathName = UNICODE_STRING() self.CommandLine = UNICODE_STRING() self.Environment = v_ptr32() self.StartingX = v_uint32() self.StartingY = v_uint32() self.CountX = v_uint32() self.CountY = v_uint32() self.CountCharsX = v_uint32() self.CountCharsY = v_uint32() self.FillAttribute = v_uint32() self.WindowFlags = v_uint32() self.ShowWindowFlags = v_uint32() self.WindowTitle = UNICODE_STRING() self.DesktopInfo = UNICODE_STRING() self.ShellInfo = UNICODE_STRING() self.RuntimeData = UNICODE_STRING() self.CurrentDirectores = UNICODE_STRING() class KDPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Number = v_uint8() self.Importance = v_uint8() self.DpcListEntry = LIST_ENTRY() self.DeferredRoutine = v_ptr32() self.DeferredContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.Lock = v_ptr32() class Wx86ThreadState(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CallBx86Eip = v_ptr32() self.DeallocationCpu = v_ptr32() self.UseKnownWx86Dll = v_uint8() self.OleStubInvoked = v_uint8() class KEVENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class KSEMAPHORE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.Limit = v_uint32() class FILE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Vpb = v_ptr32() self.FsContext = v_ptr32() self.FsContext2 = v_ptr32() self.SectionObjectPointer = v_ptr32() self.PrivateCacheMap = v_ptr32() self.FinalStatus = v_uint32() self.RelatedFileObject = v_ptr32() self.LockOperation = v_uint8() self.DeletePending = v_uint8() self.ReadAccess = v_uint8() self.WriteAccess = v_uint8() self.DeleteAccess = v_uint8() self.SharedRead = v_uint8() self.SharedWrite = v_uint8() self.SharedDelete = v_uint8() self.Flags = v_uint32() self.FileName = UNICODE_STRING() self.CurrentByteOffset = LARGE_INTEGER() self.Waiters = v_uint32() self.Busy = v_uint32() self.LastLock = v_ptr32() self.Lock = KEVENT() self.Event = KEVENT() self.CompletionContext = v_ptr32() class RTL_CRITICAL_SECTION_DEBUG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.CriticalSection = v_ptr32() self.ProcessLocksList = LIST_ENTRY() self.EntryCount = v_uint32() self.ContentionCount = v_uint32() self.Spare = v_bytes(size=8) # FIXME Unknown Array Type class OBJECT_TYPE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mutex = ERESOURCE() self.TypeList = LIST_ENTRY() self.Name = UNICODE_STRING() self.DefaultObject = v_ptr32() self.Index = v_uint32() self.TotalNumberOfObjects = v_uint32() self.TotalNumberOfHandles = v_uint32() self.HighWaterNumberOfObjects = v_uint32() self.HighWaterNumberOfHandles = v_uint32() self.TypeInfo = OBJECT_TYPE_INITIALIZER() self.Key = v_uint32() self.ObjectLocks = v_uint32() class SID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Sid = v_ptr32() self.Attributes = v_uint32() class DISPATCHER_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.Absolute = v_uint8() self.Size = v_uint8() self.Inserted = v_uint8() self.SignalState = v_uint32() self.WaitListHead = LIST_ENTRY() class IO_TIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.TimerFlag = v_uint16() self.TimerList = LIST_ENTRY() self.TimerRoutine = v_ptr32() self.Context = v_ptr32() self.DeviceObject = v_ptr32() class MMSUPPORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LastTrimTime = LARGE_INTEGER() self.Flags = MMSUPPORT_FLAGS() self.PageFaultCount = v_uint32() self.PeakWorkingSetSize = v_uint32() self.WorkingSetSize = v_uint32() self.MinimumWorkingSetSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.VmWorkingSetList = v_ptr32() self.WorkingSetExpansionLinks = LIST_ENTRY() self.Claim = v_uint32() self.NextEstimationSlot = v_uint32() self.NextAgingSlot = v_uint32() self.EstimatedAvailable = v_uint32() self.GrowthSinceLastEstimate = v_uint32() class PROCESSOR_POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdleFunction = v_ptr32() self.Idle0KernelTimeLimit = v_uint32() self.Idle0LastTime = v_uint32() self.IdleHandlers = v_ptr32() self.IdleState = v_ptr32() self.IdleHandlersCount = v_uint32() self.LastCheck = v_uint64() self.IdleTimes = PROCESSOR_IDLE_TIMES() self.IdleTime1 = v_uint32() self.PromotionCheck = v_uint32() self.IdleTime2 = v_uint32() self.CurrentThrottle = v_uint8() self.ThermalThrottleLimit = v_uint8() self.CurrentThrottleIndex = v_uint8() self.ThermalThrottleIndex = v_uint8() self.LastKernelUserTime = v_uint32() self.LastIdleThreadKernelTime = v_uint32() self.PackageIdleStartTime = v_uint32() self.PackageIdleTime = v_uint32() self.DebugCount = v_uint32() self.LastSysTime = v_uint32() self.TotalIdleStateTime = v_bytes(size=24) # FIXME Unknown Array Type self.TotalIdleTransitions = v_bytes(size=12) # FIXME Unknown Array Type self._pad0090 = v_bytes(size=4) self.PreviousC3StateTime = v_uint64() self.KneeThrottleIndex = v_uint8() self.ThrottleLimitIndex = v_uint8() self.PerfStatesCount = v_uint8() self.ProcessorMinThrottle = v_uint8() self.ProcessorMaxThrottle = v_uint8() self.EnableIdleAccounting = v_uint8() self.LastC3Percentage = v_uint8() self.LastAdjustedBusyPercentage = v_uint8() self.PromotionCount = v_uint32() self.DemotionCount = v_uint32() self.ErrorCount = v_uint32() self.RetryCount = v_uint32() self.Flags = v_uint32() self._pad00b8 = v_bytes(size=4) self.PerfCounterFrequency = LARGE_INTEGER() self.PerfTickCount = v_uint32() self._pad00c8 = v_bytes(size=4) self.PerfTimer = KTIMER() self.PerfDpc = KDPC() self.PerfStates = v_ptr32() self.PerfSetThrottle = v_ptr32() self.LastC3KernelUserTime = v_uint32() self.LastPackageIdleTime = v_uint32() class OBJECT_TYPE_INITIALIZER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.UseDefaultObject = v_uint8() self.CaseInsensitive = v_uint8() self.InvalidAttributes = v_uint32() self.GenericMapping = GENERIC_MAPPING() self.ValidAccessMask = v_uint32() self.SecurityRequired = v_uint8() self.MaintainHandleCount = v_uint8() self.MaintainTypeList = v_uint8() self._pad0020 = v_bytes(size=1) self.PoolType = v_uint32() self.DefaultPagedPoolCharge = v_uint32() self.DefaultNonPagedPoolCharge = v_uint32() self.DumpProcedure = v_ptr32() self.OpenProcedure = v_ptr32() self.CloseProcedure = v_ptr32() self.DeleteProcedure = v_ptr32() self.ParseProcedure = v_ptr32() self.SecurityProcedure = v_ptr32() self.QueryNameProcedure = v_ptr32() self.OkayToCloseProcedure = v_ptr32() class HEAP_UNCOMMMTTED_RANGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Address = v_uint32() self.Size = v_uint32() self.filler = v_uint32() class DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pad = v_uint16() self.Limit = v_uint16() self.Base = v_uint32() class HEAP_PSEUDO_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint32() class MMSUPPORT_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SessionSpace = v_uint32() class HEAP_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = unnamed() class EXCEPTION_REGISTRATION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Handler = v_ptr32() class FILE_BASIC_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.FileAttributes = v_uint32() class DEVICE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.ReferenceCount = v_uint32() self.DriverObject = v_ptr32() self.NextDevice = v_ptr32() self.AttachedDevice = v_ptr32() self.CurrentIrp = v_ptr32() self.Timer = v_ptr32() self.Flags = v_uint32() self.Characteristics = v_uint32() self.Vpb = v_ptr32() self.DeviceExtension = v_ptr32() self.DeviceType = v_uint32() self.StackSize = v_uint8() self._pad0034 = v_bytes(size=3) self.Queue = unnamed() self.AlignmentRequirement = v_uint32() self.DeviceQueue = KDEVICE_QUEUE() self.Dpc = KDPC() self.ActiveThreadCount = v_uint32() self.SecurityDescriptor = v_ptr32() self.DeviceLock = KEVENT() self.SectorSize = v_uint16() self.Spare1 = v_uint16() self.DeviceObjectExtension = v_ptr32() self.Reserved = v_ptr32() class LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_ptr32() self.Blink = v_ptr32() class SECURITY_QUALITY_OF_SERVICE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.ImpersonationLevel = v_uint32() self.ContextTrackingMode = v_uint8() self.EffectiveOnly = v_uint8() class COMPRESSED_DATA_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CompressionFormatAndEngine = v_uint16() self.CompressionUnitShift = v_uint8() self.ChunkShift = v_uint8() self.ClusterShift = v_uint8() self.Reserved = v_uint8() self.NumberOfChunks = v_uint16() self.CompressedChunkSizes = v_bytes(size=4) # FIXME Unknown Array Type class PEB_FREE_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Size = v_uint32() class KTIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.DueTime = ULARGE_INTEGER() self.TimerListEntry = LIST_ENTRY() self.Dpc = v_ptr32() self.Period = v_uint32() class PAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = FAST_MUTEX() class EX_PUSH_LOCK_WAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WakeEvent = KEVENT() self.Next = v_ptr32() self.ShareCount = v_uint32() self.Exclusive = v_uint8() class LUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class LARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class CLIENT_ID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UniqueProcess = v_ptr32() self.UniqueThread = v_ptr32() class NPAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = v_uint32() class RTL_STACK_TRACE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashChain = v_ptr32() self.TraceCount = v_uint32() self.Index = v_uint16() self.Depth = v_uint16() self.BackTrace = v_bytes(size=128) # FIXME Unknown Array Type class OBJECT_DUMP_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Stream = v_ptr32() self.Detail = v_uint32() class GUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data1 = v_uint32() self.Data2 = v_uint16() self.Data3 = v_uint16() self.Data4 = v_bytes(size=8) # FIXME Unknown Array Type class HANDLE_TRACE_DB_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientId = CLIENT_ID() self.Handle = v_ptr32() self.Type = v_uint32() self.StackTrace = v_bytes(size=64) # FIXME Unknown Array Type class KAPC_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ApcListHead = v_bytes(size=64) # FIXME Unknown Array Type self.Process = v_ptr32() self.KernelApcInProgress = v_uint8() self.KernelApcPending = v_uint8() self.UserApcPending = v_uint8() class PS_IMPERSONATION_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Token = v_ptr32() self.CopyOnOpen = v_uint8() self.EffectiveOnly = v_uint8() self._pad0008 = v_bytes(size=2) self.ImpersonationLevel = v_uint32() class FAST_MUTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Owner = v_ptr32() self.Contention = v_uint32() self.Event = KEVENT() self.OldIrql = v_uint32() class KIDTENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint16() self.Selector = v_uint16() self.Access = v_uint16() self.ExtendedOffset = v_uint16() class VPB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Flags = v_uint16() self.VolumeLabelLength = v_uint16() self.DeviceObject = v_ptr32() self.RealDevice = v_ptr32() self.SerialNumber = v_uint32() self.ReferenceCount = v_uint32() self.VolumeLabel = v_bytes(size=64) # FIXME Unknown Array Type class IO_STACK_LOCATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorFunction = v_uint8() self.MinorFunction = v_uint8() self.Flags = v_uint8() self.Control = v_uint8() self.Parameters = unnamed() self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.CompletionRoutine = v_ptr32() self.Context = v_ptr32() class ERESOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemResourcesList = LIST_ENTRY() self.OwnerTable = v_ptr32() self.ActiveCount = v_uint16() self.Flag = v_uint16() self.SharedWaiters = v_ptr32() self.ExclusiveWaiters = v_ptr32() self.OwnerThreads = v_ptr32() self.ContentionCount = v_uint32() self.NumberOfSharedWaiters = v_uint16() self.NumberOfExclusiveWaiters = v_uint16() self.Address = v_ptr32() self.SpinLock = v_uint32() class STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class KNODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ProcessorMask = v_uint32() self.Color = v_uint32() self.MmShiftedColor = v_uint32() self.FreeCount = v_bytes(size=8) # FIXME Unknown Array Type self._pad0018 = v_bytes(size=4) self.DeadStackList = SLIST_HEADER() self.PfnDereferenceSListHead = SLIST_HEADER() self.PfnDeferredList = v_ptr32() self.Seed = v_uint8() self.Flags = flags() class GENERIC_MAPPING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GenericRead = v_uint32() self.GenericWrite = v_uint32() self.GenericExecute = v_uint32() self.GenericAll = v_uint32() class IRP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.MdlAddress = v_ptr32() self.Flags = v_uint32() self.AssociatedIrp = unnamed() self.ThreadListEntry = LIST_ENTRY() self.IoStatus = IO_STATUS_BLOCK() self.RequestorMode = v_uint8() self.PendingReturned = v_uint8() self.StackCount = v_uint8() self.CurrentLocation = v_uint8() self.Cancel = v_uint8() self.CancelIrql = v_uint8() self.ApcEnvironment = v_uint8() self.AllocationFlags = v_uint8() self.UserIosb = v_ptr32() self.UserEvent = v_ptr32() self.Overlay = unnamed() self.CancelRoutine = v_ptr32() self.UserBuffer = v_ptr32() self.Tail = unnamed() class OBJECT_NAME_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = UNICODE_STRING() class IO_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.Descriptors = v_uint32() class KUSER_SHARED_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TickCountLow = v_uint32() self.TickCountMultiplier = v_uint32() self.InterruptTime = KSYSTEM_TIME() self.SystemTime = KSYSTEM_TIME() self.TimeZoneBias = KSYSTEM_TIME() self.ImageNumberLow = v_uint16() self.ImageNumberHigh = v_uint16() self.NtSystemRoot = v_bytes(size=520) # FIXME Unknown Array Type self.MaxStackTraceDepth = v_uint32() self.CryptoExponent = v_uint32() self.TimeZoneId = v_uint32() self.Reserved2 = v_bytes(size=32) # FIXME Unknown Array Type self.NtProductType = v_uint32() self.ProductTypeIsValid = v_uint8() self._pad026c = v_bytes(size=3) self.NtMajorVersion = v_uint32() self.NtMinorVersion = v_uint32() self.ProcessorFeatures = v_bytes(size=64) # FIXME Unknown Array Type self.Reserved1 = v_uint32() self.Reserved3 = v_uint32() self.TimeSlip = v_uint32() self.AlternativeArchitecture = v_uint32() self._pad02c8 = v_bytes(size=4) self.SystemExpirationDate = LARGE_INTEGER() self.SuiteMask = v_uint32() self.KdDebuggerEnabled = v_uint8() self.NXSupportPolicy = v_uint8() self._pad02d8 = v_bytes(size=2) self.ActiveConsoleId = v_uint32() self.DismountCount = v_uint32() self.ComPlusPackage = v_uint32() self.LastSystemRITEventTickCount = v_uint32() self.NumberOfPhysicalPages = v_uint32() self.SafeBootMode = v_uint8() self._pad02f0 = v_bytes(size=3) self.TraceLogging = v_uint32() self._pad02f8 = v_bytes(size=4) self.TestRetInstruction = v_uint64() self.SystemCall = v_uint32() self.SystemCallReturn = v_uint32() self.SystemCallPad = v_bytes(size=24) # FIXME Unknown Array Type self.TickCount = KSYSTEM_TIME() self._pad0330 = v_bytes(size=4) self.Cookie = v_uint32() class FNSAVE_FORMAT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint32() self.StatusWord = v_uint32() self.TagWord = v_uint32() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.RegisterArea = v_bytes(size=80) # FIXME Unknown Array Type class KSPECIAL_REGISTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Cr0 = v_uint32() self.Cr2 = v_uint32() self.Cr3 = v_uint32() self.Cr4 = v_uint32() self.KernelDr0 = v_uint32() self.KernelDr1 = v_uint32() self.KernelDr2 = v_uint32() self.KernelDr3 = v_uint32() self.KernelDr6 = v_uint32() self.KernelDr7 = v_uint32() self.Gdtr = DESCRIPTOR() self.Idtr = DESCRIPTOR() self.Tr = v_uint16() self.Ldtr = v_uint16() self.Reserved = v_bytes(size=24) # FIXME Unknown Array Type class FS_FILTER_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AcquireForModifiedPageWriter = unnamed() class HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.Signature = v_uint32() self.Flags = v_uint32() self.ForceFlags = v_uint32() self.VirtualMemoryThreshold = v_uint32() self.SegmentReserve = v_uint32() self.SegmentCommit = v_uint32() self.DeCommitFreeBlockThreshold = v_uint32() self.DeCommitTotalFreeThreshold = v_uint32() self.TotalFreeSize = v_uint32() self.MaximumAllocationSize = v_uint32() self.ProcessHeapsListIndex = v_uint16() self.HeaderValidateLength = v_uint16() self.HeaderValidateCopy = v_ptr32() self.NextAvailableTagIndex = v_uint16() self.MaximumTagIndex = v_uint16() self.TagEntries = v_ptr32() self.UCRSegments = v_ptr32() self.UnusedUnCommittedRanges = v_ptr32() self.AlignRound = v_uint32() self.AlignMask = v_uint32() self.VirtualAllocdBlocks = LIST_ENTRY() self.Segments = v_bytes(size=256) # FIXME Unknown Array Type self.u = unnamed() self.u2 = unnamed() self.AllocatorBackTraceIndex = v_uint16() self.NonDedicatedListLength = v_uint32() self.LargeBlocksIndex = v_ptr32() self.PseudoTagEntries = v_ptr32() self.FreeLists = v_ptr32() self.LockVariable = v_ptr32() self.CommitRoutine = v_ptr32() self.FrontEndHeap = v_ptr32() self.FrontHeapLockCount = v_uint16() self.FrontEndHeapType = v_uint8() self.LastSegmentIndex = v_uint8() class MAILSLOT_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MailslotQuota = v_uint32() self.MaximumMessageSize = v_uint32() self.ReadTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class IO_STATUS_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self.Information = v_uint32() class PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class CM_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = v_uint32() class EPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pcb = KPROCESS() self.ProcessLock = EX_PUSH_LOCK() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.RundownProtect = EX_RUNDOWN_REF() self.UniqueProcessId = v_ptr32() self.ActiveProcessLinks = LIST_ENTRY() self.QuotaUsage = v_bytes(size=12) # FIXME Unknown Array Type self.QuotaPeak = v_bytes(size=12) # FIXME Unknown Array Type self.CommitCharge = v_uint32() self.PeakVirtualSize = v_uint32() self.VirtualSize = v_uint32() self.SessionProcessLinks = LIST_ENTRY() self.DebugPort = v_ptr32() self.ExceptionPort = v_ptr32() self.ObjectTable = v_ptr32() self.Token = EX_FAST_REF() self.WorkingSetLock = FAST_MUTEX() self.WorkingSetPage = v_uint32() self.AddressCreationLock = FAST_MUTEX() self.HyperSpaceLock = v_uint32() self.ForkInProgress = v_ptr32() self.HardwareTrigger = v_uint32() self.VadRoot = v_ptr32() self.VadHint = v_ptr32() self.CloneRoot = v_ptr32() self.NumberOfPrivatePages = v_uint32() self.NumberOfLockedPages = v_uint32() self.Win32Process = v_ptr32() self.Job = v_ptr32() self.SectionObject = v_ptr32() self.SectionBaseAddress = v_ptr32() self.QuotaBlock = v_ptr32() self.WorkingSetWatch = v_ptr32() self.Win32WindowStation = v_ptr32() self.InheritedFromUniqueProcessId = v_ptr32() self.LdtInformation = v_ptr32() self.VadFreeHint = v_ptr32() self.VdmObjects = v_ptr32() self.DeviceMap = v_ptr32() self.PhysicalVadList = LIST_ENTRY() self.PageDirectoryPte = HARDWARE_PTE_X86() self._pad0170 = v_bytes(size=4) self.Session = v_ptr32() self.ImageFileName = v_bytes(size=16) # FIXME Unknown Array Type self.JobLinks = LIST_ENTRY() self.LockedPagesList = v_ptr32() self.ThreadListHead = LIST_ENTRY() self.SecurityPort = v_ptr32() self.PaeTop = v_ptr32() self.ActiveThreads = v_uint32() self.GrantedAccess = v_uint32() self.DefaultHardErrorProcessing = v_uint32() self.LastThreadExitStatus = v_uint32() self.Peb = v_ptr32() self.PrefetchTrace = EX_FAST_REF() self.ReadOperationCount = LARGE_INTEGER() self.WriteOperationCount = LARGE_INTEGER() self.OtherOperationCount = LARGE_INTEGER() self.ReadTransferCount = LARGE_INTEGER() self.WriteTransferCount = LARGE_INTEGER() self.OtherTransferCount = LARGE_INTEGER() self.CommitChargeLimit = v_uint32() self.CommitChargePeak = v_uint32() self.AweInfo = v_ptr32() self.SeAuditProcessCreationInfo = SE_AUDIT_PROCESS_CREATION_INFO() self.Vm = MMSUPPORT() self.LastFaultCount = v_uint32() self.ModifiedPageCount = v_uint32() self.NumberOfVads = v_uint32() self.JobStatus = v_uint32() self.Flags = v_uint32() self.ExitStatus = v_uint32() self.NextPageColor = v_uint16() self.SubSystemMinorVersion = v_uint8() self.SubSystemMajorVersion = v_uint8() self.PriorityClass = v_uint8() self.WorkingSetAcquiredUnsafe = v_uint8() self._pad0258 = v_bytes(size=2) self.Cookie = v_uint32() class LIST_ENTRY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint32() self.Blink = v_uint32() class FILE_GET_QUOTA_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextEntryOffset = v_uint32() self.SidLength = v_uint32() self.Sid = SID() class SINGLE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() class FX_SAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.U = unnamed() self.NpxSavedCpu = v_uint32() self.Cr0NpxState = v_uint32() class POWER_SEQUENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SequenceD1 = v_uint32() self.SequenceD2 = v_uint32() self.SequenceD3 = v_uint32() class IO_COMPLETION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = v_ptr32() self.Key = v_ptr32() class FS_FILTER_CALLBACK_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbackData = v_uint32() self.Operation = v_uint8() self.Reserved = v_uint8() self._pad0008 = v_bytes(size=2) self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.Parameters = FS_FILTER_PARAMETERS() class DRIVER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DriverObject = v_ptr32() self.AddDevice = v_ptr32() self.Count = v_uint32() self.ServiceKeyName = UNICODE_STRING() self.ClientDriverExtension = v_ptr32() self.FsFilterCallbacks = v_ptr32() class KDEVICE_QUEUE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceListEntry = LIST_ENTRY() self.SortKey = v_uint32() self.Inserted = v_uint8() class flags(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Removable = v_uint8() class IO_RESOURCE_REQUIREMENTS_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.SlotNumber = v_uint32() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type self.AlternativeLists = v_uint32() self.List = v_uint32() class CM_PARTIAL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Flags = v_uint16() self.u = unnamed()
Python
# Version: 5.1 # Architecture: i386 import vstruct from vstruct.primitives import * POLICY_AUDIT_EVENT_TYPE = v_enum() POLICY_AUDIT_EVENT_TYPE.AuditCategorySystem = 0 POLICY_AUDIT_EVENT_TYPE.AuditCategoryLogon = 1 POLICY_AUDIT_EVENT_TYPE.AuditCategoryObjectAccess = 2 POLICY_AUDIT_EVENT_TYPE.AuditCategoryPrivilegeUse = 3 POLICY_AUDIT_EVENT_TYPE.AuditCategoryDetailedTracking = 4 POLICY_AUDIT_EVENT_TYPE.AuditCategoryPolicyChange = 5 POLICY_AUDIT_EVENT_TYPE.AuditCategoryAccountManagement = 6 POLICY_AUDIT_EVENT_TYPE.AuditCategoryDirectoryServiceAccess = 7 POLICY_AUDIT_EVENT_TYPE.AuditCategoryAccountLogon = 8 KINTERRUPT_MODE = v_enum() KINTERRUPT_MODE.LevelSensitive = 0 KINTERRUPT_MODE.Latched = 1 ARBITER_REQUEST_SOURCE = v_enum() ARBITER_REQUEST_SOURCE.ArbiterRequestUndefined = 0 ARBITER_REQUEST_SOURCE.ArbiterRequestLegacyReported = 1 ARBITER_REQUEST_SOURCE.ArbiterRequestHalReported = 2 ARBITER_REQUEST_SOURCE.ArbiterRequestLegacyAssigned = 3 ARBITER_REQUEST_SOURCE.ArbiterRequestPnpDetected = 4 ARBITER_REQUEST_SOURCE.ArbiterRequestPnpEnumerated = 5 DEVICE_RELATION_TYPE = v_enum() DEVICE_RELATION_TYPE.BusRelations = 0 DEVICE_RELATION_TYPE.EjectionRelations = 1 DEVICE_RELATION_TYPE.PowerRelations = 2 DEVICE_RELATION_TYPE.RemovalRelations = 3 DEVICE_RELATION_TYPE.TargetDeviceRelation = 4 DEVICE_RELATION_TYPE.SingleBusRelations = 5 IO_ALLOCATION_ACTION = v_enum() IO_ALLOCATION_ACTION.KeepObject = 0 IO_ALLOCATION_ACTION.DeallocateObject = 1 IO_ALLOCATION_ACTION.DeallocateObjectKeepRegisters = 2 BUS_QUERY_ID_TYPE = v_enum() BUS_QUERY_ID_TYPE.BusQueryDeviceID = 0 BUS_QUERY_ID_TYPE.BusQueryHardwareIDs = 1 BUS_QUERY_ID_TYPE.BusQueryCompatibleIDs = 2 BUS_QUERY_ID_TYPE.BusQueryInstanceID = 3 BUS_QUERY_ID_TYPE.BusQueryDeviceSerialNumber = 4 MMSYSTEM_PTE_POOL_TYPE = v_enum() MMSYSTEM_PTE_POOL_TYPE.SystemPteSpace = 0 MMSYSTEM_PTE_POOL_TYPE.NonPagedPoolExpansion = 1 MMSYSTEM_PTE_POOL_TYPE.MaximumPtePoolTypes = 2 POP_POLICY_DEVICE_TYPE = v_enum() POP_POLICY_DEVICE_TYPE.PolicyDeviceSystemButton = 0 POP_POLICY_DEVICE_TYPE.PolicyDeviceThermalZone = 1 POP_POLICY_DEVICE_TYPE.PolicyDeviceBattery = 2 POP_POLICY_DEVICE_TYPE.PolicyInitiatePowerActionAPI = 3 POP_POLICY_DEVICE_TYPE.PolicySetPowerStateAPI = 4 POP_POLICY_DEVICE_TYPE.PolicyImmediateDozeS4 = 5 POP_POLICY_DEVICE_TYPE.PolicySystemIdle = 6 MEMORY_CACHING_TYPE = v_enum() MEMORY_CACHING_TYPE.MmNonCached = 0 MEMORY_CACHING_TYPE.MmCached = 1 MEMORY_CACHING_TYPE.MmWriteCombined = 2 MEMORY_CACHING_TYPE.MmHardwareCoherentCached = 3 MEMORY_CACHING_TYPE.MmNonCachedUnordered = 4 MEMORY_CACHING_TYPE.MmUSWCCached = 5 MEMORY_CACHING_TYPE.MmMaximumCacheType = 6 NT_PRODUCT_TYPE = v_enum() NT_PRODUCT_TYPE.NtProductWinNt = 0 NT_PRODUCT_TYPE.NtProductLanManNt = 1 NT_PRODUCT_TYPE.NtProductServer = 2 DEVICE_POWER_STATE = v_enum() DEVICE_POWER_STATE.PowerDeviceUnspecified = 0 DEVICE_POWER_STATE.PowerDeviceD0 = 1 DEVICE_POWER_STATE.PowerDeviceD1 = 2 DEVICE_POWER_STATE.PowerDeviceD2 = 3 DEVICE_POWER_STATE.PowerDeviceD3 = 4 DEVICE_POWER_STATE.PowerDeviceMaximum = 5 PF_SCENARIO_TYPE = v_enum() PF_SCENARIO_TYPE.PfApplicationLaunchScenarioType = 0 PF_SCENARIO_TYPE.PfSystemBootScenarioType = 1 PF_SCENARIO_TYPE.PfMaxScenarioType = 2 TOKEN_TYPE = v_enum() TOKEN_TYPE.TokenPrimary = 0 TOKEN_TYPE.TokenImpersonation = 1 VI_DEADLOCK_RESOURCE_TYPE = v_enum() VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockUnknown = 0 VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockMutex = 1 VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockFastMutex = 2 VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockFastMutexUnsafe = 3 VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockSpinLock = 4 VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockQueuedSpinLock = 5 VI_DEADLOCK_RESOURCE_TYPE.VfDeadlockTypeMaximum = 6 FSINFOCLASS = v_enum() FSINFOCLASS.FileFsVolumeInformation = 0 FSINFOCLASS.FileFsLabelInformation = 1 FSINFOCLASS.FileFsSizeInformation = 2 FSINFOCLASS.FileFsDeviceInformation = 3 FSINFOCLASS.FileFsAttributeInformation = 4 FSINFOCLASS.FileFsControlInformation = 5 FSINFOCLASS.FileFsFullSizeInformation = 6 FSINFOCLASS.FileFsObjectIdInformation = 7 FSINFOCLASS.FileFsDriverPathInformation = 8 FSINFOCLASS.FileFsMaximumInformation = 9 ARBITER_ACTION = v_enum() ARBITER_ACTION.ArbiterActionTestAllocation = 0 ARBITER_ACTION.ArbiterActionRetestAllocation = 1 ARBITER_ACTION.ArbiterActionCommitAllocation = 2 ARBITER_ACTION.ArbiterActionRollbackAllocation = 3 ARBITER_ACTION.ArbiterActionQueryAllocatedResources = 4 ARBITER_ACTION.ArbiterActionWriteReservedResources = 5 ARBITER_ACTION.ArbiterActionQueryConflict = 6 ARBITER_ACTION.ArbiterActionQueryArbitrate = 7 ARBITER_ACTION.ArbiterActionAddReserved = 8 ARBITER_ACTION.ArbiterActionBootAllocation = 9 POOL_TYPE = v_enum() POOL_TYPE.NonPagedPool = 0 POOL_TYPE.PagedPool = 1 POOL_TYPE.NonPagedPoolMustSucceed = 2 POOL_TYPE.DontUseThisType = 3 POOL_TYPE.NonPagedPoolCacheAligned = 4 POOL_TYPE.PagedPoolCacheAligned = 5 POOL_TYPE.NonPagedPoolCacheAlignedMustS = 6 POOL_TYPE.MaxPoolType = 7 POOL_TYPE.NonPagedPoolSession = 8 POOL_TYPE.PagedPoolSession = 9 POOL_TYPE.NonPagedPoolMustSucceedSession = 10 POOL_TYPE.DontUseThisTypeSession = 11 POOL_TYPE.NonPagedPoolCacheAlignedSession = 12 POOL_TYPE.PagedPoolCacheAlignedSession = 13 POOL_TYPE.NonPagedPoolCacheAlignedMustSSession = 14 PCI_DISPATCH_STYLE = v_enum() PCI_DISPATCH_STYLE.IRP_COMPLETE = 0 PCI_DISPATCH_STYLE.IRP_DOWNWARD = 1 PCI_DISPATCH_STYLE.IRP_UPWARD = 2 PCI_DISPATCH_STYLE.IRP_DISPATCH = 3 MODE = v_enum() MODE.KernelMode = 0 MODE.UserMode = 1 MODE.MaximumMode = 2 FS_FILTER_SECTION_SYNC_TYPE = v_enum() FS_FILTER_SECTION_SYNC_TYPE.SyncTypeOther = 0 FS_FILTER_SECTION_SYNC_TYPE.SyncTypeCreateSection = 1 OB_OPEN_REASON = v_enum() OB_OPEN_REASON.ObCreateHandle = 0 OB_OPEN_REASON.ObOpenHandle = 1 OB_OPEN_REASON.ObDuplicateHandle = 2 OB_OPEN_REASON.ObInheritHandle = 3 OB_OPEN_REASON.ObMaxOpenReason = 4 CPU_VENDORS = v_enum() CPU_VENDORS.CPU_NONE = 0 CPU_VENDORS.CPU_INTEL = 1 CPU_VENDORS.CPU_AMD = 2 CPU_VENDORS.CPU_CYRIX = 3 CPU_VENDORS.CPU_TRANSMETA = 4 CPU_VENDORS.CPU_CENTAUR = 5 CPU_VENDORS.CPU_RISE = 6 CPU_VENDORS.CPU_UNKNOWN = 7 DEVICE_TEXT_TYPE = v_enum() DEVICE_TEXT_TYPE.DeviceTextDescription = 0 DEVICE_TEXT_TYPE.DeviceTextLocationInformation = 1 POWER_STATE_TYPE = v_enum() POWER_STATE_TYPE.SystemPowerState = 0 POWER_STATE_TYPE.DevicePowerState = 1 BUS_DATA_TYPE = v_enum() BUS_DATA_TYPE.ConfigurationSpaceUndefined = 0 BUS_DATA_TYPE.Cmos = 1 BUS_DATA_TYPE.EisaConfiguration = 2 BUS_DATA_TYPE.Pos = 3 BUS_DATA_TYPE.CbusConfiguration = 4 BUS_DATA_TYPE.PCIConfiguration = 5 BUS_DATA_TYPE.VMEConfiguration = 6 BUS_DATA_TYPE.NuBusConfiguration = 7 BUS_DATA_TYPE.PCMCIAConfiguration = 8 BUS_DATA_TYPE.MPIConfiguration = 9 BUS_DATA_TYPE.MPSAConfiguration = 10 BUS_DATA_TYPE.PNPISAConfiguration = 11 BUS_DATA_TYPE.SgiInternalConfiguration = 12 BUS_DATA_TYPE.MaximumBusDataType = 13 LSA_FOREST_TRUST_RECORD_TYPE = v_enum() LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName = 0 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx = 1 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo = 2 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustRecordTypeLast = 3 FILE_INFORMATION_CLASS = v_enum() FILE_INFORMATION_CLASS.FileDirectoryInformation = 0 FILE_INFORMATION_CLASS.FileFullDirectoryInformation = 1 FILE_INFORMATION_CLASS.FileBothDirectoryInformation = 2 FILE_INFORMATION_CLASS.FileBasicInformation = 3 FILE_INFORMATION_CLASS.FileStandardInformation = 4 FILE_INFORMATION_CLASS.FileInternalInformation = 5 FILE_INFORMATION_CLASS.FileEaInformation = 6 FILE_INFORMATION_CLASS.FileAccessInformation = 7 FILE_INFORMATION_CLASS.FileNameInformation = 8 FILE_INFORMATION_CLASS.FileRenameInformation = 9 FILE_INFORMATION_CLASS.FileLinkInformation = 10 FILE_INFORMATION_CLASS.FileNamesInformation = 11 FILE_INFORMATION_CLASS.FileDispositionInformation = 12 FILE_INFORMATION_CLASS.FilePositionInformation = 13 FILE_INFORMATION_CLASS.FileFullEaInformation = 14 FILE_INFORMATION_CLASS.FileModeInformation = 15 FILE_INFORMATION_CLASS.FileAlignmentInformation = 16 FILE_INFORMATION_CLASS.FileAllInformation = 17 FILE_INFORMATION_CLASS.FileAllocationInformation = 18 FILE_INFORMATION_CLASS.FileEndOfFileInformation = 19 FILE_INFORMATION_CLASS.FileAlternateNameInformation = 20 FILE_INFORMATION_CLASS.FileStreamInformation = 21 FILE_INFORMATION_CLASS.FilePipeInformation = 22 FILE_INFORMATION_CLASS.FilePipeLocalInformation = 23 FILE_INFORMATION_CLASS.FilePipeRemoteInformation = 24 FILE_INFORMATION_CLASS.FileMailslotQueryInformation = 25 FILE_INFORMATION_CLASS.FileMailslotSetInformation = 26 FILE_INFORMATION_CLASS.FileCompressionInformation = 27 FILE_INFORMATION_CLASS.FileObjectIdInformation = 28 FILE_INFORMATION_CLASS.FileCompletionInformation = 29 FILE_INFORMATION_CLASS.FileMoveClusterInformation = 30 FILE_INFORMATION_CLASS.FileQuotaInformation = 31 FILE_INFORMATION_CLASS.FileReparsePointInformation = 32 FILE_INFORMATION_CLASS.FileNetworkOpenInformation = 33 FILE_INFORMATION_CLASS.FileAttributeTagInformation = 34 FILE_INFORMATION_CLASS.FileTrackingInformation = 35 FILE_INFORMATION_CLASS.FileIdBothDirectoryInformation = 36 FILE_INFORMATION_CLASS.FileIdFullDirectoryInformation = 37 FILE_INFORMATION_CLASS.FileValidDataLengthInformation = 38 FILE_INFORMATION_CLASS.FileShortNameInformation = 39 FILE_INFORMATION_CLASS.FileMaximumInformation = 40 EXCEPTION_DISPOSITION = v_enum() EXCEPTION_DISPOSITION.ExceptionContinueExecution = 0 EXCEPTION_DISPOSITION.ExceptionContinueSearch = 1 EXCEPTION_DISPOSITION.ExceptionNestedException = 2 EXCEPTION_DISPOSITION.ExceptionCollidedUnwind = 3 PNP_VETO_TYPE = v_enum() PNP_VETO_TYPE.PNP_VetoTypeUnknown = 0 PNP_VETO_TYPE.PNP_VetoLegacyDevice = 1 PNP_VETO_TYPE.PNP_VetoPendingClose = 2 PNP_VETO_TYPE.PNP_VetoWindowsApp = 3 PNP_VETO_TYPE.PNP_VetoWindowsService = 4 PNP_VETO_TYPE.PNP_VetoOutstandingOpen = 5 PNP_VETO_TYPE.PNP_VetoDevice = 6 PNP_VETO_TYPE.PNP_VetoDriver = 7 PNP_VETO_TYPE.PNP_VetoIllegalDeviceRequest = 8 PNP_VETO_TYPE.PNP_VetoInsufficientPower = 9 PNP_VETO_TYPE.PNP_VetoNonDisableable = 10 PNP_VETO_TYPE.PNP_VetoLegacyDriver = 11 PNP_VETO_TYPE.PNP_VetoInsufficientRights = 12 PCI_SIGNATURE = v_enum() PCI_SIGNATURE.PciPdoExtensionType = 0 PCI_SIGNATURE.PciFdoExtensionType = 1 PCI_SIGNATURE.PciArb_Io = 2 PCI_SIGNATURE.PciArb_Memory = 3 PCI_SIGNATURE.PciArb_Interrupt = 4 PCI_SIGNATURE.PciArb_BusNumber = 5 PCI_SIGNATURE.PciTrans_Interrupt = 6 PCI_SIGNATURE.PciInterface_BusHandler = 7 PCI_SIGNATURE.PciInterface_IntRouteHandler = 8 PCI_SIGNATURE.PciInterface_PciCb = 9 PCI_SIGNATURE.PciInterface_LegacyDeviceDetection = 10 PCI_SIGNATURE.PciInterface_PmeHandler = 11 PCI_SIGNATURE.PciInterface_DevicePresent = 12 PCI_SIGNATURE.PciInterface_NativeIde = 13 PCI_SIGNATURE.PciInterface_AgpTarget = 14 SECURITY_OPERATION_CODE = v_enum() SECURITY_OPERATION_CODE.SetSecurityDescriptor = 0 SECURITY_OPERATION_CODE.QuerySecurityDescriptor = 1 SECURITY_OPERATION_CODE.DeleteSecurityDescriptor = 2 SECURITY_OPERATION_CODE.AssignSecurityDescriptor = 3 PP_NPAGED_LOOKASIDE_NUMBER = v_enum() PP_NPAGED_LOOKASIDE_NUMBER.LookasideSmallIrpList = 0 PP_NPAGED_LOOKASIDE_NUMBER.LookasideLargeIrpList = 1 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMdlList = 2 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCreateInfoList = 3 PP_NPAGED_LOOKASIDE_NUMBER.LookasideNameBufferList = 4 PP_NPAGED_LOOKASIDE_NUMBER.LookasideTwilightList = 5 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCompletionList = 6 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMaximumList = 7 SECURITY_IMPERSONATION_LEVEL = v_enum() SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous = 0 SECURITY_IMPERSONATION_LEVEL.SecurityIdentification = 1 SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation = 2 SECURITY_IMPERSONATION_LEVEL.SecurityDelegation = 3 DEVICE_USAGE_NOTIFICATION_TYPE = v_enum() DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeUndefined = 0 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypePaging = 1 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeHibernation = 2 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeDumpFile = 3 PROXY_CLASS = v_enum() PROXY_CLASS.ProxyFull = 0 PROXY_CLASS.ProxyService = 1 PROXY_CLASS.ProxyTree = 2 PROXY_CLASS.ProxyDirectory = 3 PLUGPLAY_EVENT_CATEGORY = v_enum() PLUGPLAY_EVENT_CATEGORY.HardwareProfileChangeEvent = 0 PLUGPLAY_EVENT_CATEGORY.TargetDeviceChangeEvent = 1 PLUGPLAY_EVENT_CATEGORY.DeviceClassChangeEvent = 2 PLUGPLAY_EVENT_CATEGORY.CustomDeviceEvent = 3 PLUGPLAY_EVENT_CATEGORY.DeviceInstallEvent = 4 PLUGPLAY_EVENT_CATEGORY.DeviceArrivalEvent = 5 PLUGPLAY_EVENT_CATEGORY.PowerEvent = 6 PLUGPLAY_EVENT_CATEGORY.VetoEvent = 7 PLUGPLAY_EVENT_CATEGORY.BlockedDriverEvent = 8 PLUGPLAY_EVENT_CATEGORY.MaxPlugEventCategory = 9 INTERFACE_TYPE = v_enum() INTERFACE_TYPE.InterfaceTypeUndefined = 0 INTERFACE_TYPE.Internal = 1 INTERFACE_TYPE.Isa = 2 INTERFACE_TYPE.Eisa = 3 INTERFACE_TYPE.MicroChannel = 4 INTERFACE_TYPE.TurboChannel = 5 INTERFACE_TYPE.PCIBus = 6 INTERFACE_TYPE.VMEBus = 7 INTERFACE_TYPE.NuBus = 8 INTERFACE_TYPE.PCMCIABus = 9 INTERFACE_TYPE.CBus = 10 INTERFACE_TYPE.MPIBus = 11 INTERFACE_TYPE.MPSABus = 12 INTERFACE_TYPE.ProcessorInternal = 13 INTERFACE_TYPE.InternalPowerBus = 14 INTERFACE_TYPE.PNPISABus = 15 INTERFACE_TYPE.PNPBus = 16 INTERFACE_TYPE.MaximumInterfaceType = 17 KWAIT_REASON = v_enum() KWAIT_REASON.Executive = 0 KWAIT_REASON.FreePage = 1 KWAIT_REASON.PageIn = 2 KWAIT_REASON.PoolAllocation = 3 KWAIT_REASON.DelayExecution = 4 KWAIT_REASON.Suspended = 5 KWAIT_REASON.UserRequest = 6 KWAIT_REASON.WrExecutive = 7 KWAIT_REASON.WrFreePage = 8 KWAIT_REASON.WrPageIn = 9 KWAIT_REASON.WrPoolAllocation = 10 KWAIT_REASON.WrDelayExecution = 11 KWAIT_REASON.WrSuspended = 12 KWAIT_REASON.WrUserRequest = 13 KWAIT_REASON.WrEventPair = 14 KWAIT_REASON.WrQueue = 15 KWAIT_REASON.WrLpcReceive = 16 KWAIT_REASON.WrLpcReply = 17 KWAIT_REASON.WrVirtualMemory = 18 KWAIT_REASON.WrPageOut = 19 KWAIT_REASON.WrRendezvous = 20 KWAIT_REASON.Spare2 = 21 KWAIT_REASON.Spare3 = 22 KWAIT_REASON.Spare4 = 23 KWAIT_REASON.Spare5 = 24 KWAIT_REASON.Spare6 = 25 KWAIT_REASON.WrKernel = 26 KWAIT_REASON.MaximumWaitReason = 27 ALTERNATIVE_ARCHITECTURE_TYPE = v_enum() ALTERNATIVE_ARCHITECTURE_TYPE.StandardDesign = 0 ALTERNATIVE_ARCHITECTURE_TYPE.NEC98x86 = 1 ALTERNATIVE_ARCHITECTURE_TYPE.EndAlternatives = 2 MMLISTS = v_enum() MMLISTS.ZeroedPageList = 0 MMLISTS.FreePageList = 1 MMLISTS.StandbyPageList = 2 MMLISTS.ModifiedPageList = 3 MMLISTS.ModifiedNoWritePageList = 4 MMLISTS.BadPageList = 5 MMLISTS.ActiveAndValid = 6 MMLISTS.TransitionPage = 7 MEMORY_TYPE = v_enum() MEMORY_TYPE.MemoryExceptionBlock = 0 MEMORY_TYPE.MemorySystemBlock = 1 MEMORY_TYPE.MemoryFree = 2 MEMORY_TYPE.MemoryBad = 3 MEMORY_TYPE.MemoryLoadedProgram = 4 MEMORY_TYPE.MemoryFirmwareTemporary = 5 MEMORY_TYPE.MemoryFirmwarePermanent = 6 MEMORY_TYPE.MemoryFreeContiguous = 7 MEMORY_TYPE.MemorySpecialMemory = 8 MEMORY_TYPE.MemoryMaximum = 9 PS_QUOTA_TYPE = v_enum() PS_QUOTA_TYPE.PsNonPagedPool = 0 PS_QUOTA_TYPE.PsPagedPool = 1 PS_QUOTA_TYPE.PsPageFile = 2 PS_QUOTA_TYPE.PsQuotaTypes = 3 ReplacesCorHdrNumericDefines = v_enum() ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY = 0 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED = 1 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY = 2 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED = 3 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA = 4 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR_V2 = 5 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR = 6 ReplacesCorHdrNumericDefines.COR_VERSION_MINOR = 7 ReplacesCorHdrNumericDefines.COR_DELETED_NAME_LENGTH = 8 ReplacesCorHdrNumericDefines.COR_VTABLEGAP_NAME_LENGTH = 9 ReplacesCorHdrNumericDefines.NATIVE_TYPE_MAX_CB = 10 ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 11 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_METHODRVA = 12 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_EHRVA = 13 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_BASICBLOCK = 14 ReplacesCorHdrNumericDefines.COR_VTABLE_32BIT = 15 ReplacesCorHdrNumericDefines.COR_VTABLE_64BIT = 16 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED = 17 ReplacesCorHdrNumericDefines.COR_VTABLE_CALL_MOST_DERIVED = 18 ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE = 19 ReplacesCorHdrNumericDefines.MAX_CLASS_NAME = 20 ReplacesCorHdrNumericDefines.MAX_PACKAGE_NAME = 21 ARBITER_RESULT = v_enum() ARBITER_RESULT.ArbiterResultUndefined = 0 ARBITER_RESULT.ArbiterResultSuccess = 1 ARBITER_RESULT.ArbiterResultExternalConflict = 2 ARBITER_RESULT.ArbiterResultNullRequest = 3 SYSTEM_POWER_STATE = v_enum() SYSTEM_POWER_STATE.PowerSystemUnspecified = 0 SYSTEM_POWER_STATE.PowerSystemWorking = 1 SYSTEM_POWER_STATE.PowerSystemSleeping1 = 2 SYSTEM_POWER_STATE.PowerSystemSleeping2 = 3 SYSTEM_POWER_STATE.PowerSystemSleeping3 = 4 SYSTEM_POWER_STATE.PowerSystemHibernate = 5 SYSTEM_POWER_STATE.PowerSystemShutdown = 6 SYSTEM_POWER_STATE.PowerSystemMaximum = 7 MEMORY_CACHING_TYPE_ORIG = v_enum() MEMORY_CACHING_TYPE_ORIG.MmFrameBufferCached = 0 POWER_ACTION = v_enum() POWER_ACTION.PowerActionNone = 0 POWER_ACTION.PowerActionReserved = 1 POWER_ACTION.PowerActionSleep = 2 POWER_ACTION.PowerActionHibernate = 3 POWER_ACTION.PowerActionShutdown = 4 POWER_ACTION.PowerActionShutdownReset = 5 POWER_ACTION.PowerActionShutdownOff = 6 POWER_ACTION.PowerActionWarmEject = 7 PNP_DEVNODE_STATE = v_enum() PNP_DEVNODE_STATE.DeviceNodeUnspecified = 0 PNP_DEVNODE_STATE.DeviceNodeUninitialized = 1 PNP_DEVNODE_STATE.DeviceNodeInitialized = 2 PNP_DEVNODE_STATE.DeviceNodeDriversAdded = 3 PNP_DEVNODE_STATE.DeviceNodeResourcesAssigned = 4 PNP_DEVNODE_STATE.DeviceNodeStartPending = 5 PNP_DEVNODE_STATE.DeviceNodeStartCompletion = 6 PNP_DEVNODE_STATE.DeviceNodeStartPostWork = 7 PNP_DEVNODE_STATE.DeviceNodeStarted = 8 PNP_DEVNODE_STATE.DeviceNodeQueryStopped = 9 PNP_DEVNODE_STATE.DeviceNodeStopped = 10 PNP_DEVNODE_STATE.DeviceNodeRestartCompletion = 11 PNP_DEVNODE_STATE.DeviceNodeEnumeratePending = 12 PNP_DEVNODE_STATE.DeviceNodeEnumerateCompletion = 13 PNP_DEVNODE_STATE.DeviceNodeAwaitingQueuedDeletion = 14 PNP_DEVNODE_STATE.DeviceNodeAwaitingQueuedRemoval = 15 PNP_DEVNODE_STATE.DeviceNodeQueryRemoved = 16 PNP_DEVNODE_STATE.DeviceNodeRemovePendingCloses = 17 PNP_DEVNODE_STATE.DeviceNodeRemoved = 18 PNP_DEVNODE_STATE.DeviceNodeDeletePendingCloses = 19 PNP_DEVNODE_STATE.DeviceNodeDeleted = 20 PROFILE_STATUS = v_enum() PROFILE_STATUS.DOCK_NOTDOCKDEVICE = 0 PROFILE_STATUS.DOCK_QUIESCENT = 1 PROFILE_STATUS.DOCK_ARRIVING = 2 PROFILE_STATUS.DOCK_DEPARTING = 3 PROFILE_STATUS.DOCK_EJECTIRP_COMPLETED = 4 MI_PFN_CACHE_ATTRIBUTE = v_enum() MI_PFN_CACHE_ATTRIBUTE.MiNonCached = 0 MI_PFN_CACHE_ATTRIBUTE.MiCached = 1 MI_PFN_CACHE_ATTRIBUTE.MiWriteCombined = 2 MI_PFN_CACHE_ATTRIBUTE.MiNotMapped = 3 class KEXECUTE_OPTIONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExecuteDisable = v_uint8() class PCI_PMC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint8() self.Support = PM_SUPPORT() class SEGMENT_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseAddress = v_ptr32() self.TotalNumberOfPtes = v_uint32() self.SizeOfSegment = LARGE_INTEGER() self.NonExtendedPtes = v_uint32() self.ImageCommitment = v_uint32() self.ControlArea = v_ptr32() self.Subsection = v_ptr32() self.LargeControlArea = v_ptr32() self.MmSectionFlags = v_ptr32() self.MmSubSectionFlags = v_ptr32() class DUAL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Map = v_ptr32() self.SmallDir = v_ptr32() self.Guard = v_uint32() self.FreeDisplay = v_uint32() self.FreeSummary = v_uint32() self.FreeBins = LIST_ENTRY() class SID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.SubAuthorityCount = v_uint8() self.IdentifierAuthority = SID_IDENTIFIER_AUTHORITY() self.SubAuthority = v_bytes(size=4) # FIXME Unknown Array Type class MMPTE_HARDWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class PCI_FUNCTION_RESOURCES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Limit = v_uint32() self.Current = v_uint32() class DBGKD_SET_SPECIAL_CALL64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SpecialCall = v_uint64() class KTSS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Backlink = v_uint16() self.Reserved0 = v_uint16() self.Esp0 = v_uint32() self.Ss0 = v_uint16() self.Reserved1 = v_uint16() self.NotUsed1 = v_bytes(size=16) # FIXME Unknown Array Type self.CR3 = v_uint32() self.Eip = v_uint32() self.EFlags = v_uint32() self.Eax = v_uint32() self.Ecx = v_uint32() self.Edx = v_uint32() self.Ebx = v_uint32() self.Esp = v_uint32() self.Ebp = v_uint32() self.Esi = v_uint32() self.Edi = v_uint32() self.Es = v_uint16() self.Reserved2 = v_uint16() self.Cs = v_uint16() self.Reserved3 = v_uint16() self.Ss = v_uint16() self.Reserved4 = v_uint16() self.Ds = v_uint16() self.Reserved5 = v_uint16() self.Fs = v_uint16() self.Reserved6 = v_uint16() self.Gs = v_uint16() self.Reserved7 = v_uint16() self.LDT = v_uint16() self.Reserved8 = v_uint16() self.Flags = v_uint16() self.IoMapBase = v_uint16() self.IoMaps = v_uint16() self.IntDirectionMap = v_bytes(size=32) # FIXME Unknown Array Type class CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DosPath = UNICODE_STRING() self.Handle = v_ptr32() class DBGKD_GET_INTERNAL_BREAKPOINT32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakpointAddress = v_uint32() self.Flags = v_uint32() self.Calls = v_uint32() self.MaxCallsPerPeriod = v_uint32() self.MinInstructions = v_uint32() self.MaxInstructions = v_uint32() self.TotalInstructions = v_uint32() class DBGKD_MANIPULATE_STATE32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ApiNumber = v_uint32() self.ProcessorLevel = v_uint16() self.Processor = v_uint16() self.ReturnStatus = v_uint32() self.u = unnamed() class PROCESSOR_POWER_POLICY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint32() self.DynamicThrottle = v_uint8() self.Spare = v_bytes(size=3) # FIXME Unknown Array Type self.DisableCStates = v_uint32() self.PolicyCount = v_uint32() self.Policy = v_uint32() class BITMAP_RANGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Links = LIST_ENTRY() self.BasePage = v_uint64() self.FirstDirtyPage = v_uint32() self.LastDirtyPage = v_uint32() self.DirtyPages = v_uint32() self.Bitmap = v_ptr32() class PI_BUS_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.NumberCSNs = v_uint32() self.ReadDataPort = v_ptr32() self.DataPortMapped = v_uint8() self._pad0010 = v_bytes(size=3) self.AddressPort = v_ptr32() self.AddrPortMapped = v_uint8() self._pad0018 = v_bytes(size=3) self.CommandPort = v_ptr32() self.CmdPortMapped = v_uint8() self._pad0020 = v_bytes(size=3) self.NextSlotNumber = v_uint32() self.DeviceList = SINGLE_LIST_ENTRY() self.CardList = SINGLE_LIST_ENTRY() self.PhysicalBusDevice = v_ptr32() self.FunctionalBusDevice = v_ptr32() self.AttachedDevice = v_ptr32() self.BusNumber = v_uint32() self.SystemPowerState = v_uint32() self.DevicePowerState = v_uint32() class HANDLE_TABLE_ENTRY_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AuditMask = v_uint32() class DBGKD_WRITE_MEMORY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TargetBaseAddress = v_uint32() self.TransferCount = v_uint32() self.ActualBytesWritten = v_uint32() class PCI_INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_ptr32() self.MinSize = v_uint16() self.MinVersion = v_uint16() self.MaxVersion = v_uint16() self.Flags = v_uint16() self.ReferenceCount = v_uint32() self.Signature = v_uint32() self.Constructor = v_ptr32() self.Initializer = v_ptr32() class MMWSLENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class CM_PARTIAL_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.PartialDescriptors = v_uint32() class DBGKD_RESTORE_BREAKPOINT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakPointHandle = v_uint32() class DEVICE_CAPABILITIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.DeviceD1 = v_uint32() self.Address = v_uint32() self.UINumber = v_uint32() self.DeviceState = v_uint32() self.SystemWake = v_uint32() self.DeviceWake = v_uint32() self.D1Latency = v_uint32() self.D2Latency = v_uint32() self.D3Latency = v_uint32() class HEAP_ENTRY_EXTRA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocatorBackTraceIndex = v_uint16() self.TagIndex = v_uint16() self.Settable = v_uint32() class EXCEPTION_RECORD64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionCode = v_uint32() self.ExceptionFlags = v_uint32() self.ExceptionRecord = v_uint64() self.ExceptionAddress = v_uint64() self.NumberParameters = v_uint32() self.unusedAlignment = v_uint32() self.ExceptionInformation = v_bytes(size=120) # FIXME Unknown Array Type class KPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.ProfileListHead = LIST_ENTRY() self.DirectoryTableBase = v_bytes(size=8) # FIXME Unknown Array Type self.LdtDescriptor = KGDTENTRY() self.Int21Descriptor = KIDTENTRY() self.IopmOffset = v_uint16() self.Iopl = v_uint8() self.Unused = v_uint8() self.ActiveProcessors = v_uint32() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.ReadyListHead = LIST_ENTRY() self.SwapListEntry = SINGLE_LIST_ENTRY() self.VdmTrapcHandler = v_ptr32() self.ThreadListHead = LIST_ENTRY() self.ProcessLock = v_uint32() self.Affinity = v_uint32() self.StackCount = v_uint16() self.BasePriority = v_uint8() self.ThreadQuantum = v_uint8() self.AutoAlignment = v_uint8() self.State = v_uint8() self.ThreadSeed = v_uint8() self.DisableBoost = v_uint8() self.PowerState = v_uint8() self.DisableQuantum = v_uint8() self.IdealNode = v_uint8() self.Flags = KEXECUTE_OPTIONS() class DEVICE_OBJECT_POWER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdleCount = v_uint32() self.ConservationIdleTime = v_uint32() self.PerformanceIdleTime = v_uint32() self.DeviceObject = v_ptr32() self.IdleList = LIST_ENTRY() self.DeviceType = v_uint8() self._pad001c = v_bytes(size=3) self.State = v_uint32() self.NotifySourceList = LIST_ENTRY() self.NotifyTargetList = LIST_ENTRY() self.PowerChannelSummary = POWER_CHANNEL_SUMMARY() self.Volume = LIST_ENTRY() class MMPTE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class BATTERY_REPORTING_SCALE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Granularity = v_uint32() self.Capacity = v_uint32() class VI_POOL_ENTRY_INUSE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_ptr32() self.CallingAddress = v_ptr32() self.NumberOfBytes = v_uint32() self.Tag = v_uint32() class HEAP_LOOKASIDE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Counters = v_bytes(size=8) # FIXME Unknown Array Type class MMPTE_TRANSITION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class OBJECT_HANDLE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HandleAttributes = v_uint32() self.GrantedAccess = v_uint32() class KINTERRUPT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.InterruptListEntry = LIST_ENTRY() self.ServiceRoutine = v_ptr32() self.ServiceContext = v_ptr32() self.SpinLock = v_uint32() self.TickCount = v_uint32() self.ActualLock = v_ptr32() self.DispatchAddress = v_ptr32() self.Vector = v_uint32() self.Irql = v_uint8() self.SynchronizeIrql = v_uint8() self.FloatingSave = v_uint8() self.Connected = v_uint8() self.Number = v_uint8() self.ShareVector = v_uint8() self._pad0030 = v_bytes(size=2) self.Mode = v_uint32() self.ServiceCount = v_uint32() self.DispatchCount = v_uint32() self.DispatchCode = v_bytes(size=424) # FIXME Unknown Array Type class OWNER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwnerThread = v_uint32() self.OwnerCount = v_uint32() class DEVOBJ_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.PowerFlags = v_uint32() self.Dope = v_ptr32() self.ExtensionFlags = v_uint32() self.DeviceNode = v_ptr32() self.AttachedTo = v_ptr32() self.StartIoCount = v_uint32() self.StartIoKey = v_uint32() self.StartIoFlags = v_uint32() self.Vpb = v_ptr32() class ARBITER_ALLOCATION_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = v_uint64() self.End = v_uint64() self.CurrentMinimum = v_uint64() self.CurrentMaximum = v_uint64() self.Entry = v_ptr32() self.CurrentAlternative = v_ptr32() self.AlternativeCount = v_uint32() self.Alternatives = v_ptr32() self.Flags = v_uint16() self.RangeAttributes = v_uint8() self.RangeAvailableAttributes = v_uint8() self.WorkSpace = v_uint32() class DBGKD_SET_INTERNAL_BREAKPOINT64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakpointAddress = v_uint64() self.Flags = v_uint32() class MM_DRIVER_VERIFIER_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint32() self.RaiseIrqls = v_uint32() self.AcquireSpinLocks = v_uint32() self.SynchronizeExecutions = v_uint32() self.AllocationsAttempted = v_uint32() self.AllocationsSucceeded = v_uint32() self.AllocationsSucceededSpecialPool = v_uint32() self.AllocationsWithNoTag = v_uint32() self.TrimRequests = v_uint32() self.Trims = v_uint32() self.AllocationsFailed = v_uint32() self.AllocationsFailedDeliberately = v_uint32() self.Loads = v_uint32() self.Unloads = v_uint32() self.UnTrackedPool = v_uint32() self.UserTrims = v_uint32() self.CurrentPagedPoolAllocations = v_uint32() self.CurrentNonPagedPoolAllocations = v_uint32() self.PeakPagedPoolAllocations = v_uint32() self.PeakNonPagedPoolAllocations = v_uint32() self.PagedBytes = v_uint32() self.NonPagedBytes = v_uint32() self.PeakPagedBytes = v_uint32() self.PeakNonPagedBytes = v_uint32() self.BurstAllocationsFailedDeliberately = v_uint32() self.SessionTrims = v_uint32() self.Reserved = v_bytes(size=8) # FIXME Unknown Array Type class MAILSLOT_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MailslotQuota = v_uint32() self.MaximumMessageSize = v_uint32() self.ReadTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class FS_FILTER_CALLBACK_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbackData = v_uint32() self.Operation = v_uint8() self.Reserved = v_uint8() self._pad0008 = v_bytes(size=2) self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.Parameters = FS_FILTER_PARAMETERS() class ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OperationID = LUID() self.SecurityEvaluated = v_uint8() self.GenerateAudit = v_uint8() self.GenerateOnClose = v_uint8() self.PrivilegesAllocated = v_uint8() self.Flags = v_uint32() self.RemainingDesiredAccess = v_uint32() self.PreviouslyGrantedAccess = v_uint32() self.OriginalDesiredAccess = v_uint32() self.SubjectSecurityContext = SECURITY_SUBJECT_CONTEXT() self.SecurityDescriptor = v_ptr32() self.AuxData = v_ptr32() self.Privileges = unnamed() self.AuditPrivileges = v_uint8() self._pad0064 = v_bytes(size=3) self.ObjectName = UNICODE_STRING() self.ObjectTypeName = UNICODE_STRING() class FILE_STANDARD_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.NumberOfLinks = v_uint32() self.DeletePending = v_uint8() self.Directory = v_uint8() class AMD64_DBGKD_CONTROL_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TraceFlag = v_uint32() self.Dr7 = v_uint64() self.CurrentSymbolStart = v_uint64() self.CurrentSymbolEnd = v_uint64() class POOL_BLOCK_HEAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = POOL_HEADER() self.List = LIST_ENTRY() class DBGKD_SET_SPECIAL_CALL32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SpecialCall = v_uint32() class SYSTEM_POWER_LEVEL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Enable = v_uint8() self.Spare = v_bytes(size=3) # FIXME Unknown Array Type self.BatteryLevel = v_uint32() self.PowerPolicy = POWER_ACTION_POLICY() self.MinSystemState = v_uint32() class DBGKD_LOAD_SYMBOLS32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PathNameLength = v_uint32() self.BaseOfDll = v_uint32() self.ProcessId = v_uint32() self.CheckSum = v_uint32() self.SizeOfImage = v_uint32() self.UnloadSymbols = v_uint8() class DBGKM_EXCEPTION32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionRecord = EXCEPTION_RECORD32() self.FirstChance = v_uint32() class PAGEFAULT_HISTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentIndex = v_uint32() self.MaxIndex = v_uint32() self.SpinLock = v_uint32() self.Reserved = v_ptr32() self.WatchInfo = v_ptr32() class WNODE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BufferSize = v_uint32() self.ProviderId = v_uint32() self.HistoricalContext = v_uint64() self.CountLost = v_uint32() self._pad0018 = v_bytes(size=4) self.Guid = GUID() self.ClientContext = v_uint32() self.Flags = v_uint32() class PROCESS_WS_WATCH_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FaultingPc = v_ptr32() self.FaultingVa = v_ptr32() class SECTION_OBJECT_POINTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSectionObject = v_ptr32() self.SharedCacheMap = v_ptr32() self.ImageSectionObject = v_ptr32() class MDL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Size = v_uint16() self.MdlFlags = v_uint16() self.Process = v_ptr32() self.MappedSystemVa = v_ptr32() self.StartVa = v_ptr32() self.ByteCount = v_uint32() self.ByteOffset = v_uint32() class KTRAP_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DbgEbp = v_uint32() self.DbgEip = v_uint32() self.DbgArgMark = v_uint32() self.DbgArgPointer = v_uint32() self.TempSegCs = v_uint32() self.TempEsp = v_uint32() self.Dr0 = v_uint32() self.Dr1 = v_uint32() self.Dr2 = v_uint32() self.Dr3 = v_uint32() self.Dr6 = v_uint32() self.Dr7 = v_uint32() self.SegGs = v_uint32() self.SegEs = v_uint32() self.SegDs = v_uint32() self.Edx = v_uint32() self.Ecx = v_uint32() self.Eax = v_uint32() self.PreviousPreviousMode = v_uint32() self.ExceptionList = v_ptr32() self.SegFs = v_uint32() self.Edi = v_uint32() self.Esi = v_uint32() self.Ebx = v_uint32() self.Ebp = v_uint32() self.ErrCode = v_uint32() self.Eip = v_uint32() self.SegCs = v_uint32() self.EFlags = v_uint32() self.HardwareEsp = v_uint32() self.HardwareSegSs = v_uint32() self.V86Es = v_uint32() self.V86Ds = v_uint32() self.V86Fs = v_uint32() self.V86Gs = v_uint32() class CM_INDEX_HINT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.HashKey = v_bytes(size=4) # FIXME Unknown Array Type class SEP_AUDIT_POLICY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PolicyElements = SEP_AUDIT_POLICY_CATEGORIES() class MMPTE_SOFTWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class IO_TIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.TimerFlag = v_uint16() self.TimerList = LIST_ENTRY() self.TimerRoutine = v_ptr32() self.Context = v_ptr32() self.DeviceObject = v_ptr32() class Wx86ThreadState(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CallBx86Eip = v_ptr32() self.DeallocationCpu = v_ptr32() self.UseKnownWx86Dll = v_uint8() self.OleStubInvoked = v_uint8() class MM_SESSION_SPACE_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Initialized = v_uint32() class EVENT_COUNTER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = SINGLE_LIST_ENTRY() self.RefCount = v_uint32() self.Event = KEVENT() class SECURITY_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.Sbz1 = v_uint8() self.Control = v_uint16() self.Owner = v_ptr32() self.Group = v_ptr32() self.Sacl = v_ptr32() self.Dacl = v_ptr32() class SECURITY_TOKEN_AUDIT_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.GrantMask = v_uint32() self.DenyMask = v_uint32() class EX_WORK_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WorkerQueue = KQUEUE() self.DynamicThreadCount = v_uint32() self.WorkItemsProcessed = v_uint32() self.WorkItemsProcessedLastPass = v_uint32() self.QueueDepthLastPass = v_uint32() self.Info = EX_QUEUE_WORKER_INFO() class OBJECT_TYPE_INITIALIZER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.UseDefaultObject = v_uint8() self.CaseInsensitive = v_uint8() self.InvalidAttributes = v_uint32() self.GenericMapping = GENERIC_MAPPING() self.ValidAccessMask = v_uint32() self.SecurityRequired = v_uint8() self.MaintainHandleCount = v_uint8() self.MaintainTypeList = v_uint8() self._pad0020 = v_bytes(size=1) self.PoolType = v_uint32() self.DefaultPagedPoolCharge = v_uint32() self.DefaultNonPagedPoolCharge = v_uint32() self.DumpProcedure = v_ptr32() self.OpenProcedure = v_ptr32() self.CloseProcedure = v_ptr32() self.DeleteProcedure = v_ptr32() self.ParseProcedure = v_ptr32() self.SecurityProcedure = v_ptr32() self.QueryNameProcedure = v_ptr32() self.OkayToCloseProcedure = v_ptr32() class VACB_LEVEL_REFERENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reference = v_uint32() self.SpecialReference = v_uint32() class HEAP_FREE_ENTRY_EXTRA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TagIndex = v_uint16() self.FreeBackTraceIndex = v_uint16() class POP_DEVICE_SYS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IrpMinor = v_uint8() self._pad0004 = v_bytes(size=3) self.SystemState = v_uint32() self.Event = KEVENT() self.SpinLock = v_uint32() self.Thread = v_ptr32() self.GetNewDeviceList = v_uint8() self._pad0024 = v_bytes(size=3) self.Order = PO_DEVICE_NOTIFY_ORDER() self.Status = v_uint32() self.FailedDevice = v_ptr32() self.Waking = v_uint8() self.Cancelled = v_uint8() self.IgnoreErrors = v_uint8() self.IgnoreNotImplemented = v_uint8() self.WaitAny = v_uint8() self.WaitAll = v_uint8() self._pad027c = v_bytes(size=2) self.PresentIrpQueue = LIST_ENTRY() self.Head = POP_DEVICE_POWER_IRP() self.PowerIrpState = POP_DEVICE_POWER_IRP() class VI_DEADLOCK_RESOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() self.NodeCount = v_uint32() self.ResourceAddress = v_ptr32() self.ThreadOwner = v_ptr32() self.ResourceList = LIST_ENTRY() self.HashChainList = LIST_ENTRY() self.StackTrace = v_bytes(size=32) # FIXME Unknown Array Type self.LastAcquireTrace = v_bytes(size=32) # FIXME Unknown Array Type self.LastReleaseTrace = v_bytes(size=32) # FIXME Unknown Array Type class HEAP_PSEUDO_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint32() class CM_KEY_REFERENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.KeyCell = v_uint32() self.KeyHive = v_ptr32() class MMSECTION_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BeingDeleted = v_uint32() class DBGKD_GET_INTERNAL_BREAKPOINT64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakpointAddress = v_uint64() self.Flags = v_uint32() self.Calls = v_uint32() self.MaxCallsPerPeriod = v_uint32() self.MinInstructions = v_uint32() self.MaxInstructions = v_uint32() self.TotalInstructions = v_uint32() class PROCESSOR_POWER_POLICY_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TimeCheck = v_uint32() self.DemoteLimit = v_uint32() self.PromoteLimit = v_uint32() self.DemotePercent = v_uint8() self.PromotePercent = v_uint8() self.Spare = v_bytes(size=2) # FIXME Unknown Array Type self.AllowDemotion = v_uint32() class POP_POWER_ACTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Updates = v_uint8() self.State = v_uint8() self.Shutdown = v_uint8() self._pad0004 = v_bytes(size=1) self.Action = v_uint32() self.LightestState = v_uint32() self.Flags = v_uint32() self.Status = v_uint32() self.IrpMinor = v_uint8() self._pad0018 = v_bytes(size=3) self.SystemState = v_uint32() self.NextSystemState = v_uint32() self.ShutdownBugCode = v_ptr32() self.DevState = v_ptr32() self.HiberContext = v_ptr32() self.LastWakeState = v_uint32() self.WakeTime = v_uint64() self.SleepTime = v_uint64() class OBJECT_CREATE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Attributes = v_uint32() self.RootDirectory = v_ptr32() self.ParseContext = v_ptr32() self.ProbeMode = v_uint8() self._pad0010 = v_bytes(size=3) self.PagedPoolCharge = v_uint32() self.NonPagedPoolCharge = v_uint32() self.SecurityDescriptorCharge = v_uint32() self.SecurityDescriptor = v_ptr32() self.SecurityQos = v_ptr32() self.SecurityQualityOfService = SECURITY_QUALITY_OF_SERVICE() class OBJECT_HEADER_CREATOR_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TypeList = LIST_ENTRY() self.CreatorUniqueProcess = v_ptr32() self.CreatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() class PAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = FAST_MUTEX() class HEAP_STOP_ON_TAG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HeapAndTagIndex = v_uint32() class PO_NOTIFY_ORDER_LEVEL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LevelReady = KEVENT() self.DeviceCount = v_uint32() self.ActiveCount = v_uint32() self.WaitSleep = LIST_ENTRY() self.ReadySleep = LIST_ENTRY() self.Pending = LIST_ENTRY() self.Complete = LIST_ENTRY() self.ReadyS0 = LIST_ENTRY() self.WaitS0 = LIST_ENTRY() class RTL_BITMAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfBitMap = v_uint32() self.Buffer = v_ptr32() class LARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class IA64_DBGKD_CONTROL_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Continue = v_uint32() self.CurrentSymbolStart = v_uint64() self.CurrentSymbolEnd = v_uint64() class NPAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = v_uint32() class HARDWARE_PTE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class VPB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Flags = v_uint16() self.VolumeLabelLength = v_uint16() self.DeviceObject = v_ptr32() self.RealDevice = v_ptr32() self.SerialNumber = v_uint32() self.ReferenceCount = v_uint32() self.VolumeLabel = v_bytes(size=64) # FIXME Unknown Array Type class SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlArea = v_ptr32() self.TotalNumberOfPtes = v_uint32() self.NonExtendedPtes = v_uint32() self.WritableUserReferences = v_uint32() self.SizeOfSegment = v_uint64() self.SegmentPteTemplate = MMPTE() self.NumberOfCommittedPages = v_uint32() self.ExtendInfo = v_ptr32() self.SystemImageBase = v_ptr32() self.BasedAddress = v_ptr32() self.u1 = unnamed() self.u2 = unnamed() self.PrototypePte = v_ptr32() self.ThePtes = v_ptr32() class PP_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P = v_ptr32() self.L = v_ptr32() class OBJECT_NAME_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = UNICODE_STRING() class IO_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.Descriptors = v_uint32() class KUSER_SHARED_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TickCountLow = v_uint32() self.TickCountMultiplier = v_uint32() self.InterruptTime = KSYSTEM_TIME() self.SystemTime = KSYSTEM_TIME() self.TimeZoneBias = KSYSTEM_TIME() self.ImageNumberLow = v_uint16() self.ImageNumberHigh = v_uint16() self.NtSystemRoot = v_bytes(size=520) # FIXME Unknown Array Type self.MaxStackTraceDepth = v_uint32() self.CryptoExponent = v_uint32() self.TimeZoneId = v_uint32() self.Reserved2 = v_bytes(size=32) # FIXME Unknown Array Type self.NtProductType = v_uint32() self.ProductTypeIsValid = v_uint8() self._pad026c = v_bytes(size=3) self.NtMajorVersion = v_uint32() self.NtMinorVersion = v_uint32() self.ProcessorFeatures = v_bytes(size=64) # FIXME Unknown Array Type self.Reserved1 = v_uint32() self.Reserved3 = v_uint32() self.TimeSlip = v_uint32() self.AlternativeArchitecture = v_uint32() self._pad02c8 = v_bytes(size=4) self.SystemExpirationDate = LARGE_INTEGER() self.SuiteMask = v_uint32() self.KdDebuggerEnabled = v_uint8() self.NXSupportPolicy = v_uint8() self._pad02d8 = v_bytes(size=2) self.ActiveConsoleId = v_uint32() self.DismountCount = v_uint32() self.ComPlusPackage = v_uint32() self.LastSystemRITEventTickCount = v_uint32() self.NumberOfPhysicalPages = v_uint32() self.SafeBootMode = v_uint8() self._pad02f0 = v_bytes(size=3) self.TraceLogging = v_uint32() self._pad02f8 = v_bytes(size=4) self.TestRetInstruction = v_uint64() self.SystemCall = v_uint32() self.SystemCallReturn = v_uint32() self.SystemCallPad = v_bytes(size=24) # FIXME Unknown Array Type self.TickCount = KSYSTEM_TIME() self._pad0330 = v_bytes(size=4) self.Cookie = v_uint32() class MMFREE_POOL_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.List = LIST_ENTRY() self.Size = v_uint32() self.Signature = v_uint32() self.Owner = v_ptr32() class PRIVATE_CACHE_MAP_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DontUse = v_uint32() class FS_FILTER_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AcquireForModifiedPageWriter = unnamed() class HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.Signature = v_uint32() self.Flags = v_uint32() self.ForceFlags = v_uint32() self.VirtualMemoryThreshold = v_uint32() self.SegmentReserve = v_uint32() self.SegmentCommit = v_uint32() self.DeCommitFreeBlockThreshold = v_uint32() self.DeCommitTotalFreeThreshold = v_uint32() self.TotalFreeSize = v_uint32() self.MaximumAllocationSize = v_uint32() self.ProcessHeapsListIndex = v_uint16() self.HeaderValidateLength = v_uint16() self.HeaderValidateCopy = v_ptr32() self.NextAvailableTagIndex = v_uint16() self.MaximumTagIndex = v_uint16() self.TagEntries = v_ptr32() self.UCRSegments = v_ptr32() self.UnusedUnCommittedRanges = v_ptr32() self.AlignRound = v_uint32() self.AlignMask = v_uint32() self.VirtualAllocdBlocks = LIST_ENTRY() self.Segments = v_bytes(size=256) # FIXME Unknown Array Type self.u = unnamed() self.u2 = unnamed() self.AllocatorBackTraceIndex = v_uint16() self.NonDedicatedListLength = v_uint32() self.LargeBlocksIndex = v_ptr32() self.PseudoTagEntries = v_ptr32() self.FreeLists = v_ptr32() self.LockVariable = v_ptr32() self.CommitRoutine = v_ptr32() self.FrontEndHeap = v_ptr32() self.FrontHeapLockCount = v_uint16() self.FrontEndHeapType = v_uint8() self.LastSegmentIndex = v_uint8() class IO_STATUS_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self.Information = v_uint32() class PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class CM_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = v_uint32() class EPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pcb = KPROCESS() self.ProcessLock = EX_PUSH_LOCK() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.RundownProtect = EX_RUNDOWN_REF() self.UniqueProcessId = v_ptr32() self.ActiveProcessLinks = LIST_ENTRY() self.QuotaUsage = v_bytes(size=12) # FIXME Unknown Array Type self.QuotaPeak = v_bytes(size=12) # FIXME Unknown Array Type self.CommitCharge = v_uint32() self.PeakVirtualSize = v_uint32() self.VirtualSize = v_uint32() self.SessionProcessLinks = LIST_ENTRY() self.DebugPort = v_ptr32() self.ExceptionPort = v_ptr32() self.ObjectTable = v_ptr32() self.Token = EX_FAST_REF() self.WorkingSetLock = FAST_MUTEX() self.WorkingSetPage = v_uint32() self.AddressCreationLock = FAST_MUTEX() self.HyperSpaceLock = v_uint32() self.ForkInProgress = v_ptr32() self.HardwareTrigger = v_uint32() self.VadRoot = v_ptr32() self.VadHint = v_ptr32() self.CloneRoot = v_ptr32() self.NumberOfPrivatePages = v_uint32() self.NumberOfLockedPages = v_uint32() self.Win32Process = v_ptr32() self.Job = v_ptr32() self.SectionObject = v_ptr32() self.SectionBaseAddress = v_ptr32() self.QuotaBlock = v_ptr32() self.WorkingSetWatch = v_ptr32() self.Win32WindowStation = v_ptr32() self.InheritedFromUniqueProcessId = v_ptr32() self.LdtInformation = v_ptr32() self.VadFreeHint = v_ptr32() self.VdmObjects = v_ptr32() self.DeviceMap = v_ptr32() self.PhysicalVadList = LIST_ENTRY() self.PageDirectoryPte = HARDWARE_PTE() self._pad0170 = v_bytes(size=4) self.Session = v_ptr32() self.ImageFileName = v_bytes(size=16) # FIXME Unknown Array Type self.JobLinks = LIST_ENTRY() self.LockedPagesList = v_ptr32() self.ThreadListHead = LIST_ENTRY() self.SecurityPort = v_ptr32() self.PaeTop = v_ptr32() self.ActiveThreads = v_uint32() self.GrantedAccess = v_uint32() self.DefaultHardErrorProcessing = v_uint32() self.LastThreadExitStatus = v_uint32() self.Peb = v_ptr32() self.PrefetchTrace = EX_FAST_REF() self.ReadOperationCount = LARGE_INTEGER() self.WriteOperationCount = LARGE_INTEGER() self.OtherOperationCount = LARGE_INTEGER() self.ReadTransferCount = LARGE_INTEGER() self.WriteTransferCount = LARGE_INTEGER() self.OtherTransferCount = LARGE_INTEGER() self.CommitChargeLimit = v_uint32() self.CommitChargePeak = v_uint32() self.AweInfo = v_ptr32() self.SeAuditProcessCreationInfo = SE_AUDIT_PROCESS_CREATION_INFO() self.Vm = MMSUPPORT() self.LastFaultCount = v_uint32() self.ModifiedPageCount = v_uint32() self.NumberOfVads = v_uint32() self.JobStatus = v_uint32() self.Flags = v_uint32() self.ExitStatus = v_uint32() self.NextPageColor = v_uint16() self.SubSystemMinorVersion = v_uint8() self.SubSystemMajorVersion = v_uint8() self.PriorityClass = v_uint8() self.WorkingSetAcquiredUnsafe = v_uint8() self._pad0258 = v_bytes(size=2) self.Cookie = v_uint32() class PHYSICAL_MEMORY_RUN(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BasePage = v_uint32() self.PageCount = v_uint32() class CM_KEY_BODY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() self.KeyControlBlock = v_ptr32() self.NotifyBlock = v_ptr32() self.ProcessID = v_ptr32() self.Callers = v_uint32() self.CallerAddress = v_bytes(size=40) # FIXME Unknown Array Type self.KeyBodyList = LIST_ENTRY() class KMUTANT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.MutantListEntry = LIST_ENTRY() self.OwnerThread = v_ptr32() self.Abandoned = v_uint8() self.ApcDisable = v_uint8() class FX_SAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.U = unnamed() self.NpxSavedCpu = v_uint32() self.Cr0NpxState = v_uint32() class POWER_SEQUENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SequenceD1 = v_uint32() self.SequenceD2 = v_uint32() self.SequenceD3 = v_uint32() class KTIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.DueTime = ULARGE_INTEGER() self.TimerListEntry = LIST_ENTRY() self.Dpc = v_ptr32() self.Period = v_uint32() class MM_PAGED_POOL_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PagedPoolAllocationMap = v_ptr32() self.EndOfPagedPoolBitmap = v_ptr32() self.PagedPoolLargeSessionAllocationMap = v_ptr32() self.FirstPteForPagedPool = v_ptr32() self.LastPteForPagedPool = v_ptr32() self.NextPdeForPagedPoolExpansion = v_ptr32() self.PagedPoolHint = v_uint32() self.PagedPoolCommit = v_uint32() self.AllocatedPagedPool = v_uint32() class HIVE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = v_ptr32() self.BaseName = v_ptr32() self.CmHive = v_ptr32() self.Flags = v_uint32() self.CmHive2 = v_ptr32() self.ThreadFinished = v_uint8() self.ThreadStarted = v_uint8() self.Allocate = v_uint8() class CM_PARTIAL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Flags = v_uint16() self.u = unnamed() class RTLP_RANGE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = v_uint64() self.End = v_uint64() self.Allocated = unnamed() self.Attributes = v_uint8() self.PublicFlags = v_uint8() self.PrivateFlags = v_uint16() self.ListEntry = LIST_ENTRY() class MMVAD_LONG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartingVpn = v_uint32() self.EndingVpn = v_uint32() self.Parent = v_ptr32() self.LeftChild = v_ptr32() self.RightChild = v_ptr32() self.u = unnamed() self.ControlArea = v_ptr32() self.FirstPrototypePte = v_ptr32() self.LastContiguousPte = v_ptr32() self.u2 = unnamed() self.u3 = unnamed() self.u4 = unnamed() class CM_VIEW_OF_FILE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LRUViewList = LIST_ENTRY() self.PinViewList = LIST_ENTRY() self.FileOffset = v_uint32() self.Size = v_uint32() self.ViewAddress = v_ptr32() self.Bcb = v_ptr32() self.UseCount = v_uint32() class CM_FULL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.PartialResourceList = CM_PARTIAL_RESOURCE_LIST() class DBGKD_GET_VERSION64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.ProtocolVersion = v_uint16() self.Flags = v_uint16() self.MachineType = v_uint16() self.MaxPacketType = v_uint8() self.MaxStateChange = v_uint8() self.MaxManipulate = v_uint8() self.Simulation = v_uint8() self.Unused = v_bytes(size=2) # FIXME Unknown Array Type self.KernBase = v_uint64() self.PsLoadedModuleList = v_uint64() self.DebuggerDataList = v_uint64() class FAST_IO_DISPATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFastIoDispatch = v_uint32() self.FastIoCheckIfPossible = v_ptr32() self.FastIoRead = v_ptr32() self.FastIoWrite = v_ptr32() self.FastIoQueryBasicInfo = v_ptr32() self.FastIoQueryStandardInfo = v_ptr32() self.FastIoLock = v_ptr32() self.FastIoUnlockSingle = v_ptr32() self.FastIoUnlockAll = v_ptr32() self.FastIoUnlockAllByKey = v_ptr32() self.FastIoDeviceControl = v_ptr32() self.AcquireFileForNtCreateSection = v_ptr32() self.ReleaseFileForNtCreateSection = v_ptr32() self.FastIoDetachDevice = v_ptr32() self.FastIoQueryNetworkOpenInfo = v_ptr32() self.AcquireForModWrite = v_ptr32() self.MdlRead = v_ptr32() self.MdlReadComplete = v_ptr32() self.PrepareMdlWrite = v_ptr32() self.MdlWriteComplete = v_ptr32() self.FastIoReadCompressed = v_ptr32() self.FastIoWriteCompressed = v_ptr32() self.MdlReadCompleteCompressed = v_ptr32() self.MdlWriteCompleteCompressed = v_ptr32() self.FastIoQueryOpen = v_ptr32() self.ReleaseForModWrite = v_ptr32() self.AcquireForCcFlush = v_ptr32() self.ReleaseForCcFlush = v_ptr32() class KLOCK_QUEUE_HANDLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LockQueue = KSPIN_LOCK_QUEUE() self.OldIrql = v_uint8() class CM_KEY_CONTROL_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.RefCount = v_uint32() self.ExtFlags = v_uint32() self.KeyHash = CM_KEY_HASH() self.ParentKcb = v_ptr32() self.NameBlock = v_ptr32() self.CachedSecurity = v_ptr32() self.ValueCache = CACHED_CHILD_LIST() self.IndexHint = v_ptr32() self.KeyBodyListHead = LIST_ENTRY() self.KcbLastWriteTime = LARGE_INTEGER() self.KcbMaxNameLen = v_uint16() self.KcbMaxValueNameLen = v_uint16() self.KcbMaxValueDataLen = v_uint32() self.KcbUserFlags = v_uint32() class MMVAD_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CommitCharge = v_uint32() class MMWSL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Quota = v_uint32() self.FirstFree = v_uint32() self.FirstDynamic = v_uint32() self.LastEntry = v_uint32() self.NextSlot = v_uint32() self.Wsle = v_ptr32() self.LastInitializedWsle = v_uint32() self.NonDirectCount = v_uint32() self.HashTable = v_ptr32() self.HashTableSize = v_uint32() self.NumberOfCommittedPageTables = v_uint32() self.HashTableStart = v_ptr32() self.HighestPermittedHashAddress = v_ptr32() self.NumberOfImageWaiters = v_uint32() self.VadBitMapHint = v_uint32() self.UsedPageTableEntries = v_bytes(size=1536) # FIXME Unknown Array Type self.CommittedPageTables = v_bytes(size=96) # FIXME Unknown Array Type class POP_THERMAL_ZONE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Link = LIST_ENTRY() self.State = v_uint8() self.Flags = v_uint8() self.Mode = v_uint8() self.PendingMode = v_uint8() self.ActivePoint = v_uint8() self.PendingActivePoint = v_uint8() self._pad0010 = v_bytes(size=2) self.Throttle = v_uint32() self._pad0018 = v_bytes(size=4) self.LastTime = v_uint64() self.SampleRate = v_uint32() self.LastTemp = v_uint32() self.PassiveTimer = KTIMER() self.PassiveDpc = KDPC() self.OverThrottled = POP_ACTION_TRIGGER() self.Irp = v_ptr32() self.Info = THERMAL_INFORMATION() class CALL_HASH_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.CallersAddress = v_ptr32() self.CallersCaller = v_ptr32() self.CallCount = v_uint32() class SUPPORTED_RANGES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Sorted = v_uint8() self.Reserved = v_uint8() self.NoIO = v_uint32() self.IO = SUPPORTED_RANGE() self.NoMemory = v_uint32() self._pad0030 = v_bytes(size=4) self.Memory = SUPPORTED_RANGE() self.NoPrefetchMemory = v_uint32() self._pad0058 = v_bytes(size=4) self.PrefetchMemory = SUPPORTED_RANGE() self.NoDma = v_uint32() self._pad0080 = v_bytes(size=4) self.Dma = SUPPORTED_RANGE() class WORK_QUEUE_ITEM(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.List = LIST_ENTRY() self.WorkerRoutine = v_ptr32() self.Parameter = v_ptr32() class EPROCESS_QUOTA_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Usage = v_uint32() self.Limit = v_uint32() self.Peak = v_uint32() self.Return = v_uint32() class KSPECIAL_REGISTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Cr0 = v_uint32() self.Cr2 = v_uint32() self.Cr3 = v_uint32() self.Cr4 = v_uint32() self.KernelDr0 = v_uint32() self.KernelDr1 = v_uint32() self.KernelDr2 = v_uint32() self.KernelDr3 = v_uint32() self.KernelDr6 = v_uint32() self.KernelDr7 = v_uint32() self.Gdtr = DESCRIPTOR() self.Idtr = DESCRIPTOR() self.Tr = v_uint16() self.Ldtr = v_uint16() self.Reserved = v_bytes(size=24) # FIXME Unknown Array Type class POWER_ACTION_POLICY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Action = v_uint32() self.Flags = v_uint32() self.EventCode = v_uint32() class RTL_CRITICAL_SECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DebugInfo = v_ptr32() self.LockCount = v_uint32() self.RecursionCount = v_uint32() self.OwningThread = v_ptr32() self.LockSemaphore = v_ptr32() self.SpinCount = v_uint32() class DBGKM_EXCEPTION64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionRecord = EXCEPTION_RECORD64() self.FirstChance = v_uint32() class KSYSTEM_TIME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.High1Time = v_uint32() self.High2Time = v_uint32() class ACL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AclRevision = v_uint8() self.Sbz1 = v_uint8() self.AclSize = v_uint16() self.AceCount = v_uint16() self.Sbz2 = v_uint16() class FLOATING_SAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint32() self.StatusWord = v_uint32() self.TagWord = v_uint32() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.RegisterArea = v_bytes(size=80) # FIXME Unknown Array Type self.Cr0NpxState = v_uint32() class WMI_LOGGER_MODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SequentialFile = v_uint32() class KQUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.EntryListHead = LIST_ENTRY() self.CurrentCount = v_uint32() self.MaximumCount = v_uint32() self.ThreadListHead = LIST_ENTRY() class POOL_TRACKER_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Key = v_uint32() self.NonPagedAllocs = v_uint32() self.NonPagedFrees = v_uint32() self.NonPagedBytes = v_uint32() self.PagedAllocs = v_uint32() self.PagedFrees = v_uint32() self.PagedBytes = v_uint32() class WMI_BUFFER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Free = v_uint32() class LUID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Luid = LUID() self.Attributes = v_uint32() class MMMOD_WRITER_MDL_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Links = LIST_ENTRY() self.WriteOffset = LARGE_INTEGER() self.u = unnamed() self.Irp = v_ptr32() self.LastPageToWrite = v_uint32() self.PagingListHead = v_ptr32() self.CurrentList = v_ptr32() self.PagingFile = v_ptr32() self.File = v_ptr32() self.ControlArea = v_ptr32() self.FileResource = v_ptr32() self.Mdl = MDL() self.Page = v_bytes(size=4) # FIXME Unknown Array Type class CACHED_CHILD_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.ValueList = v_uint32() class KTHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.MutantListHead = LIST_ENTRY() self.InitialStack = v_ptr32() self.StackLimit = v_ptr32() self.Teb = v_ptr32() self.TlsArray = v_ptr32() self.KernelStack = v_ptr32() self.DebugActive = v_uint8() self.State = v_uint8() self.Alerted = v_bytes(size=2) # FIXME Unknown Array Type self.Iopl = v_uint8() self.NpxState = v_uint8() self.Saturation = v_uint8() self.Priority = v_uint8() self.ApcState = KAPC_STATE() self.ContextSwitches = v_uint32() self.IdleSwapBlock = v_uint8() self.Spare0 = v_bytes(size=3) # FIXME Unknown Array Type self.WaitStatus = v_uint32() self.WaitIrql = v_uint8() self.WaitMode = v_uint8() self.WaitNext = v_uint8() self.WaitReason = v_uint8() self.WaitBlockList = v_ptr32() self.WaitListEntry = LIST_ENTRY() self.WaitTime = v_uint32() self.BasePriority = v_uint8() self.DecrementCount = v_uint8() self.PriorityDecrement = v_uint8() self.Quantum = v_uint8() self.WaitBlock = v_uint8() self.LegoData = v_ptr32() self.KernelApcDisable = v_uint32() self.UserAffinity = v_uint32() self.SystemAffinityActive = v_uint8() self.PowerState = v_uint8() self.NpxIrql = v_uint8() self.InitialNode = v_uint8() self.ServiceTable = v_ptr32() self.Queue = v_ptr32() self.ApcQueueLock = v_uint32() self._pad00f0 = v_bytes(size=4) self.Timer = KTIMER() self.QueueListEntry = LIST_ENTRY() self.SoftAffinity = v_uint32() self.Affinity = v_uint32() self.Preempted = v_uint8() self.ProcessReadyQueue = v_uint8() self.KernelStackResident = v_uint8() self.NextProcessor = v_uint8() self.CallbackStack = v_ptr32() self.Win32Thread = v_ptr32() self.TrapFrame = v_ptr32() self.ApcStatePointer = v_bytes(size=8) # FIXME Unknown Array Type self.PreviousMode = v_uint8() self.EnableStackSwap = v_uint8() self.LargeStack = v_uint8() self.ResourceIndex = v_uint8() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.SavedApcState = KAPC_STATE() self.Alertable = v_uint8() self.ApcStateIndex = v_uint8() self.ApcQueueable = v_uint8() self.AutoAlignment = v_uint8() self.StackBase = v_ptr32() self.SuspendApc = KAPC() self.SuspendSemaphore = KSEMAPHORE() self.ThreadListEntry = LIST_ENTRY() self.FreezeCount = v_uint8() self.SuspendCount = v_uint8() self.IdealProcessor = v_uint8() self.DisableBoost = v_uint8() class ADAPTER_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFlags = v_uint32() self.Dr0 = v_uint32() self.Dr1 = v_uint32() self.Dr2 = v_uint32() self.Dr3 = v_uint32() self.Dr6 = v_uint32() self.Dr7 = v_uint32() self.FloatSave = FLOATING_SAVE_AREA() self.SegGs = v_uint32() self.SegFs = v_uint32() self.SegEs = v_uint32() self.SegDs = v_uint32() self.Edi = v_uint32() self.Esi = v_uint32() self.Ebx = v_uint32() self.Edx = v_uint32() self.Ecx = v_uint32() self.Eax = v_uint32() self.Ebp = v_uint32() self.Eip = v_uint32() self.SegCs = v_uint32() self.EFlags = v_uint32() self.Esp = v_uint32() self.SegSs = v_uint32() self.ExtendedRegisters = v_bytes(size=512) # FIXME Unknown Array Type class DBGKD_GET_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Unused = v_uint32() class DEVICE_NODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Sibling = v_ptr32() self.Child = v_ptr32() self.Parent = v_ptr32() self.LastChild = v_ptr32() self.Level = v_uint32() self.Notify = v_ptr32() self.State = v_uint32() self.PreviousState = v_uint32() self.StateHistory = v_uint32() self.StateHistoryEntry = v_uint32() self.CompletionStatus = v_uint32() self.PendingIrp = v_ptr32() self.Flags = v_uint32() self.UserFlags = v_uint32() self.Problem = v_uint32() self.PhysicalDeviceObject = v_ptr32() self.ResourceList = v_ptr32() self.ResourceListTranslated = v_ptr32() self.InstancePath = UNICODE_STRING() self.ServiceName = UNICODE_STRING() self.DuplicatePDO = v_ptr32() self.ResourceRequirements = v_ptr32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.ChildInterfaceType = v_uint32() self.ChildBusNumber = v_uint32() self.ChildBusTypeIndex = v_uint16() self.RemovalPolicy = v_uint8() self.HardwareRemovalPolicy = v_uint8() self.TargetDeviceNotify = LIST_ENTRY() self.DeviceArbiterList = LIST_ENTRY() self.DeviceTranslatorList = LIST_ENTRY() self.NoTranslatorMask = v_uint16() self.QueryTranslatorMask = v_uint16() self.NoArbiterMask = v_uint16() self.QueryArbiterMask = v_uint16() self.OverUsed1 = unnamed() self.OverUsed2 = unnamed() self.BootResources = v_ptr32() self.CapabilityFlags = v_uint32() self.DockInfo = unnamed() self.DisableableDepends = v_uint32() self.PendedSetInterfaceState = LIST_ENTRY() self.LegacyBusListEntry = LIST_ENTRY() self.DriverUnloadRetryCount = v_uint32() class RTL_ATOM_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.CriticalSection = RTL_CRITICAL_SECTION() self.RtlHandleTable = RTL_HANDLE_TABLE() self.NumberOfBuckets = v_uint32() self.Buckets = v_bytes(size=4) # FIXME Unknown Array Type class IMAGE_ROM_OPTIONAL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint16() self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.BaseOfData = v_uint32() self.BaseOfBss = v_uint32() self.GprMask = v_uint32() self.CprMask = v_bytes(size=16) # FIXME Unknown Array Type self.GpValue = v_uint32() class HEAP_FREE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.PreviousSize = v_uint16() self.SmallTagIndex = v_uint8() self.Flags = v_uint8() self.UnusedBytes = v_uint8() self.SegmentIndex = v_uint8() self.FreeList = LIST_ENTRY() class unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Argument1 = v_ptr32() self.Argument2 = v_ptr32() self.Argument3 = v_ptr32() self.Argument4 = v_ptr32() self.Argument5 = v_ptr32() class LDR_DATA_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InLoadOrderLinks = LIST_ENTRY() self.InMemoryOrderLinks = LIST_ENTRY() self.InInitializationOrderLinks = LIST_ENTRY() self.DllBase = v_ptr32() self.EntryPoint = v_ptr32() self.SizeOfImage = v_uint32() self.FullDllName = UNICODE_STRING() self.BaseDllName = UNICODE_STRING() self.Flags = v_uint32() self.LoadCount = v_uint16() self.TlsIndex = v_uint16() self.HashLinks = LIST_ENTRY() self.TimeDateStamp = v_uint32() self.EntryPointActivationContext = v_ptr32() self.PatchInformation = v_ptr32() class DBGKD_READ_MEMORY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TargetBaseAddress = v_uint64() self.TransferCount = v_uint32() self.ActualBytesRead = v_uint32() class PO_MEMORY_IMAGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.Version = v_uint32() self.CheckSum = v_uint32() self.LengthSelf = v_uint32() self.PageSelf = v_uint32() self.PageSize = v_uint32() self.ImageType = v_uint32() self._pad0020 = v_bytes(size=4) self.SystemTime = LARGE_INTEGER() self.InterruptTime = v_uint64() self.FeatureFlags = v_uint32() self.HiberFlags = v_uint8() self.spare = v_bytes(size=3) # FIXME Unknown Array Type self.NoHiberPtes = v_uint32() self.HiberVa = v_uint32() self.HiberPte = LARGE_INTEGER() self.NoFreePages = v_uint32() self.FreeMapCheck = v_uint32() self.WakeCheck = v_uint32() self.TotalPages = v_uint32() self.FirstTablePage = v_uint32() self.LastFilePage = v_uint32() self.PerfInfo = PO_HIBER_PERF() class HHIVE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.GetCellRoutine = v_ptr32() self.ReleaseCellRoutine = v_ptr32() self.Allocate = v_ptr32() self.Free = v_ptr32() self.FileSetSize = v_ptr32() self.FileWrite = v_ptr32() self.FileRead = v_ptr32() self.FileFlush = v_ptr32() self.BaseBlock = v_ptr32() self.DirtyVector = RTL_BITMAP() self.DirtyCount = v_uint32() self.DirtyAlloc = v_uint32() self.RealWrites = v_uint8() self._pad003c = v_bytes(size=3) self.Cluster = v_uint32() self.Flat = v_uint8() self.ReadOnly = v_uint8() self.Log = v_uint8() self._pad0044 = v_bytes(size=1) self.HiveFlags = v_uint32() self.LogSize = v_uint32() self.RefreshCount = v_uint32() self.StorageTypeCount = v_uint32() self.Version = v_uint32() self.Storage = v_uint32() class TEB_ACTIVE_FRAME_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.FrameName = v_ptr32() class OBJECT_SYMBOLIC_LINK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LinkTarget = UNICODE_STRING() self.LinkTargetRemaining = UNICODE_STRING() self.LinkTargetObject = v_ptr32() self.DosDeviceDriveIndex = v_uint32() class EJOB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Event = KEVENT() self.JobLinks = LIST_ENTRY() self.ProcessListHead = LIST_ENTRY() self.JobLock = ERESOURCE() self.TotalUserTime = LARGE_INTEGER() self.TotalKernelTime = LARGE_INTEGER() self.ThisPeriodTotalUserTime = LARGE_INTEGER() self.ThisPeriodTotalKernelTime = LARGE_INTEGER() self.TotalPageFaultCount = v_uint32() self.TotalProcesses = v_uint32() self.ActiveProcesses = v_uint32() self.TotalTerminatedProcesses = v_uint32() self.PerProcessUserTimeLimit = LARGE_INTEGER() self.PerJobUserTimeLimit = LARGE_INTEGER() self.LimitFlags = v_uint32() self.MinimumWorkingSetSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.ActiveProcessLimit = v_uint32() self.Affinity = v_uint32() self.PriorityClass = v_uint8() self._pad00b0 = v_bytes(size=3) self.UIRestrictionsClass = v_uint32() self.SecurityLimitFlags = v_uint32() self.Token = v_ptr32() self.Filter = v_ptr32() self.EndOfJobTimeAction = v_uint32() self.CompletionPort = v_ptr32() self.CompletionKey = v_ptr32() self.SessionId = v_uint32() self.SchedulingClass = v_uint32() self._pad00d8 = v_bytes(size=4) self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() self.IoInfo = IO_COUNTERS() self.ProcessMemoryLimit = v_uint32() self.JobMemoryLimit = v_uint32() self.PeakProcessMemoryUsed = v_uint32() self.PeakJobMemoryUsed = v_uint32() self.CurrentJobMemoryUsed = v_uint32() self.MemoryLimitsLock = FAST_MUTEX() self.JobSetLinks = LIST_ENTRY() self.MemberLevel = v_uint32() self.JobFlags = v_uint32() class DBGKD_READ_WRITE_IO_EXTENDED64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.AddressSpace = v_uint32() self.IoAddress = v_uint64() self.DataValue = v_uint32() class HANDLE_TRACE_DEBUG_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentStackIndex = v_uint32() self.TraceDb = v_uint32() class KPROCESSOR_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFrame = CONTEXT() self.SpecialRegisters = KSPECIAL_REGISTERS() class KiIoAccessMap(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DirectionMap = v_bytes(size=32) # FIXME Unknown Array Type self.IoMap = v_bytes(size=8196) # FIXME Unknown Array Type class KAPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Spare0 = v_uint32() self.Thread = v_ptr32() self.ApcListEntry = LIST_ENTRY() self.KernelRoutine = v_ptr32() self.RundownRoutine = v_ptr32() self.NormalRoutine = v_ptr32() self.NormalContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.ApcStateIndex = v_uint8() self.ApcMode = v_uint8() self.Inserted = v_uint8() class POOL_TRACKER_BIG_PAGES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Va = v_ptr32() self.Key = v_uint32() self.NumberOfPages = v_uint32() class SID_IDENTIFIER_AUTHORITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Value = v_bytes(size=6) # FIXME Unknown Array Type class RTL_RANGE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = LIST_ENTRY() self.Flags = v_uint32() self.Count = v_uint32() self.Stamp = v_uint32() class LARGE_CONTROL_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Segment = v_ptr32() self.DereferenceList = LIST_ENTRY() self.NumberOfSectionReferences = v_uint32() self.NumberOfPfnReferences = v_uint32() self.NumberOfMappedViews = v_uint32() self.NumberOfSubsections = v_uint16() self.FlushInProgressCount = v_uint16() self.NumberOfUserReferences = v_uint32() self.u = unnamed() self.FilePointer = v_ptr32() self.WaitingForDeletion = v_ptr32() self.ModifiedWriteCount = v_uint16() self.NumberOfSystemCacheViews = v_uint16() self.StartingFrame = v_uint32() self.UserGlobalList = LIST_ENTRY() self.SessionId = v_uint32() class VI_POOL_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InUse = VI_POOL_ENTRY_INUSE() class POOL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PreviousSize = v_uint16() self.BlockSize = v_uint16() self.ProcessBilled = v_ptr32() class SHARED_CACHE_MAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NodeTypeCode = v_uint16() self.NodeByteSize = v_uint16() self.OpenCount = v_uint32() self.FileSize = LARGE_INTEGER() self.BcbList = LIST_ENTRY() self.SectionSize = LARGE_INTEGER() self.ValidDataLength = LARGE_INTEGER() self.ValidDataGoal = LARGE_INTEGER() self.InitialVacbs = v_bytes(size=16) # FIXME Unknown Array Type self.Vacbs = v_ptr32() self.FileObject = v_ptr32() self.ActiveVacb = v_ptr32() self.NeedToZero = v_ptr32() self.ActivePage = v_uint32() self.NeedToZeroPage = v_uint32() self.ActiveVacbSpinLock = v_uint32() self.VacbActiveCount = v_uint32() self.DirtyPages = v_uint32() self.SharedCacheMapLinks = LIST_ENTRY() self.Flags = v_uint32() self.Status = v_uint32() self.Mbcb = v_ptr32() self.Section = v_ptr32() self.CreateEvent = v_ptr32() self.WaitOnActiveCount = v_ptr32() self.PagesToWrite = v_uint32() self.BeyondLastFlush = v_uint64() self.Callbacks = v_ptr32() self.LazyWriteContext = v_ptr32() self.PrivateList = LIST_ENTRY() self.LogHandle = v_ptr32() self.FlushToLsnRoutine = v_ptr32() self.DirtyPageThreshold = v_uint32() self.LazyWritePassCount = v_uint32() self.UninitializeEvent = v_ptr32() self.NeedToZeroVacb = v_ptr32() self.BcbSpinLock = v_uint32() self.Reserved = v_ptr32() self.Event = KEVENT() self.VacbPushLock = EX_PUSH_LOCK() self._pad00d8 = v_bytes(size=4) self.PrivateCacheMap = PRIVATE_CACHE_MAP() class TRACE_ENABLE_FLAG_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint16() self.Length = v_uint8() self.Flag = v_uint8() class MI_VERIFIER_POOL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListIndex = v_uint32() self.Verifier = v_ptr32() class MMBANKED_SECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BasePhysicalPage = v_uint32() self.BasedPte = v_ptr32() self.BankSize = v_uint32() self.BankShift = v_uint32() self.BankedRoutine = v_ptr32() self.Context = v_ptr32() self.CurrentMappedPte = v_ptr32() self.BankTemplate = v_ptr32() class PCI_POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentSystemState = v_uint32() self.CurrentDeviceState = v_uint32() self.SystemWakeLevel = v_uint32() self.DeviceWakeLevel = v_uint32() self.SystemStateMapping = v_uint32() self.WaitWakeIrp = v_ptr32() self.SavedCancelRoutine = v_ptr32() self.Paging = v_uint32() self.Hibernate = v_uint32() self.CrashDump = v_uint32() class RTL_CRITICAL_SECTION_DEBUG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.CriticalSection = v_ptr32() self.ProcessLocksList = LIST_ENTRY() self.EntryCount = v_uint32() self.ContentionCount = v_uint32() self.Spare = v_bytes(size=8) # FIXME Unknown Array Type class PNP_DEVICE_EVENT_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.Argument = v_uint32() self.CallerEvent = v_ptr32() self.Callback = v_ptr32() self.Context = v_ptr32() self.VetoType = v_ptr32() self.VetoName = v_ptr32() self.Data = PLUGPLAY_EVENT_BLOCK() class ARBITER_CONFLICT_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwningObject = v_ptr32() self._pad0008 = v_bytes(size=4) self.Start = v_uint64() self.End = v_uint64() class SID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Sid = v_ptr32() self.Attributes = v_uint32() class VI_DEADLOCK_GLOBALS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Nodes = v_bytes(size=8) # FIXME Unknown Array Type self.Resources = v_bytes(size=8) # FIXME Unknown Array Type self.Threads = v_bytes(size=8) # FIXME Unknown Array Type self.TimeAcquire = v_uint64() self.TimeRelease = v_uint64() self.BytesAllocated = v_uint32() self.ResourceDatabase = v_ptr32() self.ThreadDatabase = v_ptr32() self.AllocationFailures = v_uint32() self.NodesTrimmedBasedOnAge = v_uint32() self.NodesTrimmedBasedOnCount = v_uint32() self.NodesSearched = v_uint32() self.MaxNodesSearched = v_uint32() self.SequenceNumber = v_uint32() self.RecursionDepthLimit = v_uint32() self.SearchedNodesLimit = v_uint32() self.DepthLimitHits = v_uint32() self.SearchLimitHits = v_uint32() self.ABC_ACB_Skipped = v_uint32() self.FreeResourceList = LIST_ENTRY() self.FreeThreadList = LIST_ENTRY() self.FreeNodeList = LIST_ENTRY() self.FreeResourceCount = v_uint32() self.FreeThreadCount = v_uint32() self.FreeNodeCount = v_uint32() self.Instigator = v_ptr32() self.NumberOfParticipants = v_uint32() self.Participant = v_bytes(size=128) # FIXME Unknown Array Type self.CacheReductionInProgress = v_uint32() class TOKEN(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TokenSource = TOKEN_SOURCE() self.TokenId = LUID() self.AuthenticationId = LUID() self.ParentTokenId = LUID() self.ExpirationTime = LARGE_INTEGER() self.TokenLock = v_ptr32() self._pad0038 = v_bytes(size=4) self.AuditPolicy = SEP_AUDIT_POLICY() self.ModifiedId = LUID() self.SessionId = v_uint32() self.UserAndGroupCount = v_uint32() self.RestrictedSidCount = v_uint32() self.PrivilegeCount = v_uint32() self.VariableLength = v_uint32() self.DynamicCharged = v_uint32() self.DynamicAvailable = v_uint32() self.DefaultOwnerIndex = v_uint32() self.UserAndGroups = v_ptr32() self.RestrictedSids = v_ptr32() self.PrimaryGroup = v_ptr32() self.Privileges = v_ptr32() self.DynamicPart = v_ptr32() self.DefaultDacl = v_ptr32() self.TokenType = v_uint32() self.ImpersonationLevel = v_uint32() self.TokenFlags = v_uint32() self.TokenInUse = v_uint8() self._pad0090 = v_bytes(size=3) self.ProxyData = v_ptr32() self.AuditData = v_ptr32() self.OriginatingLogonSession = LUID() self.VariablePart = v_uint32() class MMCOLOR_TABLES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint32() self.Blink = v_ptr32() self.Count = v_uint32() class DISPATCHER_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.Absolute = v_uint8() self.Size = v_uint8() self.Inserted = v_uint8() self.SignalState = v_uint32() self.WaitListHead = LIST_ENTRY() class DBGKD_READ_WRITE_IO64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IoAddress = v_uint64() self.DataSize = v_uint32() self.DataValue = v_uint32() class PROCESSOR_POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdleFunction = v_ptr32() self.Idle0KernelTimeLimit = v_uint32() self.Idle0LastTime = v_uint32() self.IdleHandlers = v_ptr32() self.IdleState = v_ptr32() self.IdleHandlersCount = v_uint32() self.LastCheck = v_uint64() self.IdleTimes = PROCESSOR_IDLE_TIMES() self.IdleTime1 = v_uint32() self.PromotionCheck = v_uint32() self.IdleTime2 = v_uint32() self.CurrentThrottle = v_uint8() self.ThermalThrottleLimit = v_uint8() self.CurrentThrottleIndex = v_uint8() self.ThermalThrottleIndex = v_uint8() self.LastKernelUserTime = v_uint32() self.LastIdleThreadKernelTime = v_uint32() self.PackageIdleStartTime = v_uint32() self.PackageIdleTime = v_uint32() self.DebugCount = v_uint32() self.LastSysTime = v_uint32() self.TotalIdleStateTime = v_bytes(size=24) # FIXME Unknown Array Type self.TotalIdleTransitions = v_bytes(size=12) # FIXME Unknown Array Type self._pad0090 = v_bytes(size=4) self.PreviousC3StateTime = v_uint64() self.KneeThrottleIndex = v_uint8() self.ThrottleLimitIndex = v_uint8() self.PerfStatesCount = v_uint8() self.ProcessorMinThrottle = v_uint8() self.ProcessorMaxThrottle = v_uint8() self.EnableIdleAccounting = v_uint8() self.LastC3Percentage = v_uint8() self.LastAdjustedBusyPercentage = v_uint8() self.PromotionCount = v_uint32() self.DemotionCount = v_uint32() self.ErrorCount = v_uint32() self.RetryCount = v_uint32() self.Flags = v_uint32() self._pad00b8 = v_bytes(size=4) self.PerfCounterFrequency = LARGE_INTEGER() self.PerfTickCount = v_uint32() self._pad00c8 = v_bytes(size=4) self.PerfTimer = KTIMER() self.PerfDpc = KDPC() self.PerfStates = v_ptr32() self.PerfSetThrottle = v_ptr32() self.LastC3KernelUserTime = v_uint32() self.LastPackageIdleTime = v_uint32() class SECURITY_CLIENT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityQos = SECURITY_QUALITY_OF_SERVICE() self.ClientToken = v_ptr32() self.DirectlyAccessClientToken = v_uint8() self.DirectAccessEffectiveOnly = v_uint8() self.ServerIsRemote = v_uint8() self._pad0014 = v_bytes(size=1) self.ClientTokenControl = TOKEN_CONTROL() class DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pad = v_uint16() self.Limit = v_uint16() self.Base = v_uint32() class DBGKD_MANIPULATE_STATE64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ApiNumber = v_uint32() self.ProcessorLevel = v_uint16() self.Processor = v_uint16() self.ReturnStatus = v_uint32() self._pad0010 = v_bytes(size=4) self.u = unnamed() class LPCP_PORT_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NonPagedPortQueue = v_ptr32() self.Semaphore = v_ptr32() self.ReceiveHead = LIST_ENTRY() class PHYSICAL_MEMORY_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NumberOfRuns = v_uint32() self.NumberOfPages = v_uint32() self.Run = v_uint32() class CACHE_UNINITIALIZE_EVENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Event = KEVENT() class MMSESSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemSpaceViewLock = FAST_MUTEX() self.SystemSpaceViewLockPointer = v_ptr32() self.SystemSpaceViewStart = v_ptr32() self.SystemSpaceViewTable = v_ptr32() self.SystemSpaceHashSize = v_uint32() self.SystemSpaceHashEntries = v_uint32() self.SystemSpaceHashKey = v_uint32() self.SystemSpaceBitMap = v_ptr32() class COMPRESSED_DATA_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CompressionFormatAndEngine = v_uint16() self.CompressionUnitShift = v_uint8() self.ChunkShift = v_uint8() self.ClusterShift = v_uint8() self.Reserved = v_uint8() self.NumberOfChunks = v_uint16() self.CompressedChunkSizes = v_bytes(size=4) # FIXME Unknown Array Type class PEB_FREE_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Size = v_uint32() class CMHIVE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Hive = HHIVE() self.FileHandles = v_bytes(size=12) # FIXME Unknown Array Type self.NotifyList = LIST_ENTRY() self.HiveList = LIST_ENTRY() self.HiveLock = v_ptr32() self.ViewLock = v_ptr32() self.LRUViewListHead = LIST_ENTRY() self.PinViewListHead = LIST_ENTRY() self.FileObject = v_ptr32() self.FileFullPath = UNICODE_STRING() self.FileUserName = UNICODE_STRING() self.MappedViews = v_uint16() self.PinnedViews = v_uint16() self.UseCount = v_uint32() self.SecurityCount = v_uint32() self.SecurityCacheSize = v_uint32() self.SecurityHitHint = v_uint32() self.SecurityCache = v_ptr32() self.SecurityHash = v_ptr32() self.UnloadEvent = v_ptr32() self.RootKcb = v_ptr32() self.Frozen = v_uint8() self._pad047c = v_bytes(size=3) self.UnloadWorkItem = v_ptr32() self.GrowOnlyMode = v_uint8() self._pad0484 = v_bytes(size=3) self.GrowOffset = v_uint32() self.KcbConvertListHead = LIST_ENTRY() self.KnodeConvertListHead = LIST_ENTRY() self.CellRemapArray = v_ptr32() class POP_SHUTDOWN_BUG_CHECK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Code = v_uint32() self.Parameter1 = v_uint32() self.Parameter2 = v_uint32() self.Parameter3 = v_uint32() self.Parameter4 = v_uint32() class SECTION_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartingVa = v_ptr32() self.EndingVa = v_ptr32() self.Parent = v_ptr32() self.LeftChild = v_ptr32() self.RightChild = v_ptr32() self.Segment = v_ptr32() class LUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class OBJECT_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PointerCount = v_uint32() self.HandleCount = v_uint32() self.Type = v_ptr32() self.NameInfoOffset = v_uint8() self.HandleInfoOffset = v_uint8() self.QuotaInfoOffset = v_uint8() self.Flags = v_uint8() self.ObjectCreateInfo = v_ptr32() self.SecurityDescriptor = v_ptr32() self.Body = QUAD() class PCI_MN_DISPATCH_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DispatchStyle = v_uint32() self.DispatchFunction = v_ptr32() class PCI_HEADER_TYPE_2(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SocketRegistersBaseAddress = v_uint32() self.CapabilitiesPtr = v_uint8() self.Reserved = v_uint8() self.SecondaryStatus = v_uint16() self.PrimaryBus = v_uint8() self.SecondaryBus = v_uint8() self.SubordinateBus = v_uint8() self.SecondaryLatency = v_uint8() self.Range = v_uint8() self.InterruptLine = v_uint8() self.InterruptPin = v_uint8() self.BridgeControl = v_uint16() class PCI_HEADER_TYPE_1(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseAddresses = v_bytes(size=8) # FIXME Unknown Array Type self.PrimaryBus = v_uint8() self.SecondaryBus = v_uint8() self.SubordinateBus = v_uint8() self.SecondaryLatency = v_uint8() self.IOBase = v_uint8() self.IOLimit = v_uint8() self.SecondaryStatus = v_uint16() self.MemoryBase = v_uint16() self.MemoryLimit = v_uint16() self.PrefetchBase = v_uint16() self.PrefetchLimit = v_uint16() self.PrefetchBaseUpper32 = v_uint32() self.PrefetchLimitUpper32 = v_uint32() self.IOBaseUpper16 = v_uint16() self.IOLimitUpper16 = v_uint16() self.CapabilitiesPtr = v_uint8() self.Reserved1 = v_bytes(size=3) # FIXME Unknown Array Type self.ROMBaseAddress = v_uint32() self.InterruptLine = v_uint8() self.InterruptPin = v_uint8() self.BridgeControl = v_uint16() class PCI_HEADER_TYPE_0(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseAddresses = v_bytes(size=24) # FIXME Unknown Array Type self.CIS = v_uint32() self.SubVendorID = v_uint16() self.SubSystemID = v_uint16() self.ROMBaseAddress = v_uint32() self.CapabilitiesPtr = v_uint8() self.Reserved1 = v_bytes(size=3) # FIXME Unknown Array Type self.Reserved2 = v_uint32() self.InterruptLine = v_uint8() self.InterruptPin = v_uint8() self.MinimumGrant = v_uint8() self.MaximumLatency = v_uint8() class OBJECT_DUMP_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Stream = v_ptr32() self.Detail = v_uint32() class CACHE_MANAGER_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AcquireForLazyWrite = v_ptr32() self.ReleaseFromLazyWrite = v_ptr32() self.AcquireForReadAhead = v_ptr32() self.ReleaseFromReadAhead = v_ptr32() class DBGKD_CONTINUE2(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContinueStatus = v_uint32() self.ControlSet = X86_DBGKD_CONTROL_SET() class HANDLE_TRACE_DB_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientId = CLIENT_ID() self.Handle = v_ptr32() self.Type = v_uint32() self.StackTrace = v_bytes(size=64) # FIXME Unknown Array Type class LPCP_NONPAGED_PORT_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Semaphore = KSEMAPHORE() self.BackPointer = v_ptr32() class DEVICE_RELATIONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Objects = v_bytes(size=4) # FIXME Unknown Array Type class HEAP_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint32() self.TagIndex = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.TagName = v_bytes(size=48) # FIXME Unknown Array Type class MMPAGING_FILE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint32() self.MaximumSize = v_uint32() self.MinimumSize = v_uint32() self.FreeSpace = v_uint32() self.CurrentUsage = v_uint32() self.PeakUsage = v_uint32() self.Hint = v_uint32() self.HighestPage = v_uint32() self.Entry = v_bytes(size=8) # FIXME Unknown Array Type self.Bitmap = v_ptr32() self.File = v_ptr32() self.PageFileName = UNICODE_STRING() self.PageFileNumber = v_uint32() self.Extended = v_uint8() self.HintSetToZero = v_uint8() self.BootPartition = v_uint8() self._pad0040 = v_bytes(size=1) self.FileHandle = v_ptr32() class STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class FNSAVE_FORMAT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint32() self.StatusWord = v_uint32() self.TagWord = v_uint32() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.RegisterArea = v_bytes(size=80) # FIXME Unknown Array Type class CMP_OFFSET_ARRAY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FileOffset = v_uint32() self.DataBuffer = v_ptr32() self.DataLength = v_uint32() class CM_KEY_VALUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint16() self.NameLength = v_uint16() self.DataLength = v_uint32() self.Data = v_uint32() self.Type = v_uint32() self.Flags = v_uint16() self.Spare = v_uint16() self.Name = v_bytes(size=2) # FIXME Unknown Array Type class MMVAD_FLAGS2(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FileOffset = v_uint32() class LIST_ENTRY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint32() self.Blink = v_uint32() class MMWSLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u1 = unnamed() class DBGKD_BREAKPOINTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakPointCount = v_uint32() self.ContinueStatus = v_uint32() class FILE_NETWORK_OPEN_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.FileAttributes = v_uint32() class PCI_SECONDARY_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.List = SINGLE_LIST_ENTRY() self.ExtensionType = v_uint32() self.Destructor = v_ptr32() class DBGKD_QUERY_MEMORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_uint64() self.Reserved = v_uint64() self.AddressSpace = v_uint32() self.Flags = v_uint32() class PCI_SLOT_NUMBER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u = unnamed() class KDEVICE_QUEUE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceListEntry = LIST_ENTRY() self.SortKey = v_uint32() self.Inserted = v_uint8() class MMPTE_SUBSECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class PO_DEVICE_NOTIFY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Link = LIST_ENTRY() self.TargetDevice = v_ptr32() self.WakeNeeded = v_uint8() self.OrderLevel = v_uint8() self._pad0010 = v_bytes(size=2) self.DeviceObject = v_ptr32() self.Node = v_ptr32() self.DeviceName = v_ptr32() self.DriverName = v_ptr32() self.ChildCount = v_uint32() self.ActiveChild = v_uint32() class HMAP_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Directory = v_bytes(size=4096) # FIXME Unknown Array Type class DBGKD_LOAD_SYMBOLS64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PathNameLength = v_uint32() self._pad0008 = v_bytes(size=4) self.BaseOfDll = v_uint64() self.ProcessId = v_uint64() self.CheckSum = v_uint32() self.SizeOfImage = v_uint32() self.UnloadSymbols = v_uint8() class HEAP_STOP_ON_VALUES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocAddress = v_uint32() self.AllocTag = HEAP_STOP_ON_TAG() self.ReAllocAddress = v_uint32() self.ReAllocTag = HEAP_STOP_ON_TAG() self.FreeAddress = v_uint32() self.FreeTag = HEAP_STOP_ON_TAG() class WMI_BUFFER_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Wnode = WNODE_HEADER() self.Offset = v_uint32() self.EventsLost = v_uint32() self.InstanceGuid = GUID() class RTL_HANDLE_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() class ARBITER_ALTERNATIVE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Minimum = v_uint64() self.Maximum = v_uint64() self.Length = v_uint32() self.Alignment = v_uint32() self.Priority = v_uint32() self.Flags = v_uint32() self.Descriptor = v_ptr32() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type class EX_FAST_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr32() class INTERLOCK_SEQ(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Depth = v_uint16() self.FreeEntryOffset = v_uint16() self.Sequence = v_uint32() class HMAP_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Table = v_uint32() class KSPIN_LOCK_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Lock = v_ptr32() class FS_FILTER_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbacks = v_uint32() self.Reserved = v_uint32() self.PreAcquireForSectionSynchronization = v_ptr32() self.PostAcquireForSectionSynchronization = v_ptr32() self.PreReleaseForSectionSynchronization = v_ptr32() self.PostReleaseForSectionSynchronization = v_ptr32() self.PreAcquireForCcFlush = v_ptr32() self.PostAcquireForCcFlush = v_ptr32() self.PreReleaseForCcFlush = v_ptr32() self.PostReleaseForCcFlush = v_ptr32() self.PreAcquireForModifiedPageWriter = v_ptr32() self.PostAcquireForModifiedPageWriter = v_ptr32() self.PreReleaseForModifiedPageWriter = v_ptr32() self.PostReleaseForModifiedPageWriter = v_ptr32() class HANDLE_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr32() self.GrantedAccess = v_uint32() class IO_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Option = v_uint8() self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Spare1 = v_uint8() self.Flags = v_uint16() self.Spare2 = v_uint16() self.u = unnamed() class EX_PUSH_LOCK_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locks = v_bytes(size=4) # FIXME Unknown Array Type class THERMAL_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ThermalStamp = v_uint32() self.ThermalConstant1 = v_uint32() self.ThermalConstant2 = v_uint32() self.Processors = v_uint32() self.SamplingPeriod = v_uint32() self.CurrentTemperature = v_uint32() self.PassiveTripPoint = v_uint32() self.CriticalTripPoint = v_uint32() self.ActiveTripPointCount = v_uint8() self._pad0024 = v_bytes(size=3) self.ActiveTripPoint = v_bytes(size=40) # FIXME Unknown Array Type class CLIENT_ID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UniqueProcess = v_ptr32() self.UniqueThread = v_ptr32() class IMAGE_OPTIONAL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint16() self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.BaseOfData = v_uint32() self.ImageBase = v_uint32() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint32() self.SizeOfStackCommit = v_uint32() self.SizeOfHeapReserve = v_uint32() self.SizeOfHeapCommit = v_uint32() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = v_uint32() class SCSI_REQUEST_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class OBJECT_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.RootDirectory = v_ptr32() self.ObjectName = v_ptr32() self.Attributes = v_uint32() self.SecurityDescriptor = v_ptr32() self.SecurityQualityOfService = v_ptr32() class SUBSECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlArea = v_ptr32() self.u = unnamed() self.StartingSector = v_uint32() self.NumberOfFullSectors = v_uint32() self.SubsectionBase = v_ptr32() self.UnusedPtes = v_uint32() self.PtesInSubsection = v_uint32() self.NextSubsection = v_ptr32() class ETHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Tcb = KTHREAD() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.ExitStatus = v_uint32() self.PostBlockList = LIST_ENTRY() self.TerminationPort = v_ptr32() self.ActiveTimerListLock = v_uint32() self.ActiveTimerListHead = LIST_ENTRY() self.Cid = CLIENT_ID() self.LpcReplySemaphore = KSEMAPHORE() self.LpcReplyMessage = v_ptr32() self.ImpersonationInfo = v_ptr32() self.IrpList = LIST_ENTRY() self.TopLevelIrp = v_uint32() self.DeviceToVerify = v_ptr32() self.ThreadsProcess = v_ptr32() self.StartAddress = v_ptr32() self.Win32StartAddress = v_ptr32() self.ThreadListEntry = LIST_ENTRY() self.RundownProtect = EX_RUNDOWN_REF() self.ThreadLock = EX_PUSH_LOCK() self.LpcReplyMessageId = v_uint32() self.ReadClusterSize = v_uint32() self.GrantedAccess = v_uint32() self.CrossThreadFlags = v_uint32() self.SameThreadPassiveFlags = v_uint32() self.SameThreadApcFlags = v_uint32() self.ForwardClusterOnly = v_uint8() self.DisablePageFaultClustering = v_uint8() class FAST_MUTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Owner = v_ptr32() self.Contention = v_uint32() self.Event = KEVENT() self.OldIrql = v_uint32() class MM_SESSION_SPACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ReferenceCount = v_uint32() self.u = unnamed() self.SessionId = v_uint32() self.SessionPageDirectoryIndex = v_uint32() self.GlobalVirtualAddress = v_ptr32() self.ProcessList = LIST_ENTRY() self.NonPagedPoolBytes = v_uint32() self.PagedPoolBytes = v_uint32() self.NonPagedPoolAllocations = v_uint32() self.PagedPoolAllocations = v_uint32() self.NonPagablePages = v_uint32() self.CommittedPages = v_uint32() self._pad0038 = v_bytes(size=4) self.LastProcessSwappedOutTime = LARGE_INTEGER() self.PageTables = v_ptr32() self.PagedPoolMutex = FAST_MUTEX() self.PagedPoolStart = v_ptr32() self.PagedPoolEnd = v_ptr32() self.PagedPoolBasePde = v_ptr32() self.PagedPoolInfo = MM_PAGED_POOL_INFO() self.Color = v_uint32() self.ProcessOutSwapCount = v_uint32() self.ImageList = LIST_ENTRY() self.GlobalPteEntry = v_ptr32() self.CopyOnWriteCount = v_uint32() self.SessionPoolAllocationFailures = v_bytes(size=16) # FIXME Unknown Array Type self.AttachCount = v_uint32() self.AttachEvent = KEVENT() self.LastProcess = v_ptr32() self._pad00d8 = v_bytes(size=4) self.Vm = MMSUPPORT() self.Wsle = v_ptr32() self.WsLock = ERESOURCE() self.WsListEntry = LIST_ENTRY() self.Session = MMSESSION() self.Win32KDriverObject = DRIVER_OBJECT() self.WorkingSetLockOwner = v_ptr32() self.PagedPool = POOL_DESCRIPTOR() self.ProcessReferenceToSession = v_uint32() self.LocaleId = v_uint32() class CM_NAME_CONTROL_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Compressed = v_uint8() self._pad0002 = v_bytes(size=1) self.RefCount = v_uint16() self.NameHash = CM_NAME_HASH() class KDEVICE_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceListHead = LIST_ENTRY() self.Lock = v_uint32() self.Busy = v_uint8() class IO_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() class PCI_BUS_INTERFACE_STANDARD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.Context = v_ptr32() self.InterfaceReference = v_ptr32() self.InterfaceDereference = v_ptr32() self.ReadConfig = v_ptr32() self.WriteConfig = v_ptr32() self.PinToLine = v_ptr32() self.LineToPin = v_ptr32() class PORT_MESSAGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u1 = unnamed() self.u2 = unnamed() self.ClientId = CLIENT_ID() self.MessageId = v_uint32() self.ClientViewSize = v_uint32() class PCI_COMMON_CONFIG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VendorID = v_uint16() self.DeviceID = v_uint16() self.Command = v_uint16() self.Status = v_uint16() self.RevisionID = v_uint8() self.ProgIf = v_uint8() self.SubClass = v_uint8() self.BaseClass = v_uint8() self.CacheLineSize = v_uint8() self.LatencyTimer = v_uint8() self.HeaderType = v_uint8() self.BIST = v_uint8() self.u = unnamed() self.DeviceSpecific = v_bytes(size=192) # FIXME Unknown Array Type class IO_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityQos = v_ptr32() self.AccessState = v_ptr32() self.DesiredAccess = v_uint32() self.FullCreateOptions = v_uint32() class TERMINATION_PORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Port = v_ptr32() class SYSTEM_POWER_POLICY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint32() self.PowerButton = POWER_ACTION_POLICY() self.SleepButton = POWER_ACTION_POLICY() self.LidClose = POWER_ACTION_POLICY() self.LidOpenWake = v_uint32() self.Reserved = v_uint32() self.Idle = POWER_ACTION_POLICY() self.IdleTimeout = v_uint32() self.IdleSensitivity = v_uint8() self.DynamicThrottle = v_uint8() self.Spare2 = v_bytes(size=2) # FIXME Unknown Array Type self.MinSleep = v_uint32() self.MaxSleep = v_uint32() self.ReducedLatencySleep = v_uint32() self.WinLogonFlags = v_uint32() self.Spare3 = v_uint32() self.DozeS4Timeout = v_uint32() self.BroadcastCapacityResolution = v_uint32() self.DischargePolicy = v_uint32() self.VideoTimeout = v_uint32() self.VideoDimDisplay = v_uint8() self._pad00c8 = v_bytes(size=3) self.VideoReserved = v_bytes(size=12) # FIXME Unknown Array Type self.SpindownTimeout = v_uint32() self.OptimizeForPower = v_uint8() self.FanThrottleTolerance = v_uint8() self.ForcedThrottle = v_uint8() self.MinThrottle = v_uint8() self.OverThrottled = POWER_ACTION_POLICY() class IO_CLIENT_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextExtension = v_ptr32() self.ClientIdentificationAddress = v_ptr32() class INITIAL_PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class PCI_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Atom = v_uint32() self.OldIrql = v_uint8() class POOL_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PoolType = v_uint32() self.PoolIndex = v_uint32() self.RunningAllocs = v_uint32() self.RunningDeAllocs = v_uint32() self.TotalPages = v_uint32() self.TotalBigPages = v_uint32() self.Threshold = v_uint32() self.LockAddress = v_ptr32() self.PendingFrees = v_ptr32() self.PendingFreeDepth = v_uint32() self.ListHeads = v_uint32() class DBGKD_QUERY_SPECIAL_CALLS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NumberOfSpecialCalls = v_uint32() class HEAP_UNCOMMMTTED_RANGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Address = v_uint32() self.Size = v_uint32() self.filler = v_uint32() class DUMP_STACK_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Init = DUMP_INITIALIZATION_CONTEXT() self.PartitionOffset = LARGE_INTEGER() self.DumpPointers = v_ptr32() self.PointersLength = v_uint32() self.ModulePrefix = v_ptr32() self.DriverList = LIST_ENTRY() self.InitMsg = STRING() self.ProgMsg = STRING() self.DoneMsg = STRING() self.FileObject = v_ptr32() self.UsageType = v_uint32() class PNP_DEVICE_EVENT_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self.EventQueueMutex = KMUTANT() self.Lock = FAST_MUTEX() self.List = LIST_ENTRY() class PROCESSOR_IDLE_TIMES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartTime = v_uint64() self.EndTime = v_uint64() self.IdleHandlerReserved = v_bytes(size=16) # FIXME Unknown Array Type class KWAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitListEntry = LIST_ENTRY() self.Thread = v_ptr32() self.Object = v_ptr32() self.NextWaitBlock = v_ptr32() self.WaitKey = v_uint16() self.WaitType = v_uint16() class DBGKD_READ_WRITE_IO32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSize = v_uint32() self.IoAddress = v_uint32() self.DataValue = v_uint32() class POP_HIBER_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WriteToFile = v_uint8() self.ReserveLoaderMemory = v_uint8() self.ReserveFreeMemory = v_uint8() self.VerifyOnWake = v_uint8() self.Reset = v_uint8() self.HiberFlags = v_uint8() self.LinkFile = v_uint8() self._pad0008 = v_bytes(size=1) self.LinkFileHandle = v_ptr32() self.Lock = v_uint32() self.MapFrozen = v_uint8() self._pad0014 = v_bytes(size=3) self.MemoryMap = RTL_BITMAP() self.ClonedRanges = LIST_ENTRY() self.ClonedRangeCount = v_uint32() self.NextCloneRange = v_ptr32() self.NextPreserve = v_uint32() self.LoaderMdl = v_ptr32() self.Clones = v_ptr32() self.NextClone = v_ptr32() self.NoClones = v_uint32() self.Spares = v_ptr32() self._pad0048 = v_bytes(size=4) self.PagesOut = v_uint64() self.IoPage = v_ptr32() self.CurrentMcb = v_ptr32() self.DumpStack = v_ptr32() self.WakeState = v_ptr32() self.NoRanges = v_uint32() self.HiberVa = v_uint32() self.HiberPte = LARGE_INTEGER() self.Status = v_uint32() self.MemoryImage = v_ptr32() self.TableHead = v_ptr32() self.CompressionWorkspace = v_ptr32() self.CompressedWriteBuffer = v_ptr32() self.PerformanceStats = v_ptr32() self.CompressionBlock = v_ptr32() self.DmaIO = v_ptr32() self.TemporaryHeap = v_ptr32() self._pad0098 = v_bytes(size=4) self.PerfInfo = PO_HIBER_PERF() class RTL_HANDLE_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MaximumNumberOfHandles = v_uint32() self.SizeOfHandleTableEntry = v_uint32() self.Reserved = v_bytes(size=8) # FIXME Unknown Array Type self.FreeHandles = v_ptr32() self.CommittedHandles = v_ptr32() self.UnCommittedHandles = v_ptr32() self.MaxReservedHandles = v_ptr32() class PS_JOB_TOKEN_FILTER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CapturedSidCount = v_uint32() self.CapturedSids = v_ptr32() self.CapturedSidsLength = v_uint32() self.CapturedGroupCount = v_uint32() self.CapturedGroups = v_ptr32() self.CapturedGroupsLength = v_uint32() self.CapturedPrivilegeCount = v_uint32() self.CapturedPrivileges = v_ptr32() self.CapturedPrivilegesLength = v_uint32() class TOKEN_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TokenId = LUID() self.AuthenticationId = LUID() self.ModifiedId = LUID() self.TokenSource = TOKEN_SOURCE() class PCI_COMMON_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.ExtensionType = v_uint32() self.IrpDispatchTable = v_ptr32() self.DeviceState = v_uint8() self.TentativeNextState = v_uint8() self._pad0010 = v_bytes(size=2) self.SecondaryExtLock = KEVENT() class HEAP_USERDATA_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SFreeListEntry = SINGLE_LIST_ENTRY() self.HeapHandle = v_ptr32() self.SizeIndex = v_uint32() self.Signature = v_uint32() class RTL_DRIVE_LETTER_CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint16() self.Length = v_uint16() self.TimeStamp = v_uint32() self.DosPath = STRING() class ULARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class TEB_ACTIVE_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.Previous = v_ptr32() self.Context = v_ptr32() class ETIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.KeTimer = KTIMER() self.TimerApc = KAPC() self.TimerDpc = KDPC() self.ActiveTimerListEntry = LIST_ENTRY() self.Lock = v_uint32() self.Period = v_uint32() self.ApcAssociated = v_uint8() self.WakeTimer = v_uint8() self._pad008c = v_bytes(size=2) self.WakeTimerListEntry = LIST_ENTRY() class GENERAL_LOOKASIDE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.Allocate = v_ptr32() self.Free = v_ptr32() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class ARBITER_ORDERING_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint16() self.Maximum = v_uint16() self.Orderings = v_ptr32() class OBJECT_DIRECTORY_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ChainLink = v_ptr32() self.Object = v_ptr32() class FXSAVE_FORMAT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint16() self.StatusWord = v_uint16() self.TagWord = v_uint16() self.ErrorOpcode = v_uint16() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.MXCsr = v_uint32() self.MXCsrMask = v_uint32() self.RegisterArea = v_bytes(size=128) # FIXME Unknown Array Type self.Reserved3 = v_bytes(size=128) # FIXME Unknown Array Type self.Reserved4 = v_bytes(size=224) # FIXME Unknown Array Type self.Align16Byte = v_bytes(size=8) # FIXME Unknown Array Type class ARBITER_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.AlternativeCount = v_uint32() self.Alternatives = v_ptr32() self.PhysicalDeviceObject = v_ptr32() self.RequestSource = v_uint32() self.Flags = v_uint32() self.WorkSpace = v_uint32() self.InterfaceType = v_uint32() self.SlotNumber = v_uint32() self.BusNumber = v_uint32() self.Assignment = v_ptr32() self.SelectedAlternative = v_ptr32() self.Result = v_uint32() class PROCESSOR_PERF_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PercentFrequency = v_uint8() self.MinCapacity = v_uint8() self.Power = v_uint16() self.IncreaseLevel = v_uint8() self.DecreaseLevel = v_uint8() self.Flags = v_uint16() self.IncreaseTime = v_uint32() self.DecreaseTime = v_uint32() self.IncreaseCount = v_uint32() self.DecreaseCount = v_uint32() self.PerformanceTime = v_uint64() class KGDTENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LimitLow = v_uint16() self.BaseLow = v_uint16() self.HighWord = unnamed() class NAMED_PIPE_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NamedPipeType = v_uint32() self.ReadMode = v_uint32() self.CompletionMode = v_uint32() self.MaximumInstances = v_uint32() self.InboundQuota = v_uint32() self.OutboundQuota = v_uint32() self.DefaultTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class NT_TIB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionList = v_ptr32() self.StackBase = v_ptr32() self.StackLimit = v_ptr32() self.SubSystemTib = v_ptr32() self.FiberData = v_ptr32() self.ArbitraryUserPointer = v_ptr32() self.Self = v_ptr32() class POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemState = v_uint32() class UNICODE_STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class CELL_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u = u() class SECURITY_QUALITY_OF_SERVICE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.ImpersonationLevel = v_uint32() self.ContextTrackingMode = v_uint8() self.EffectiveOnly = v_uint8() class EPROCESS_QUOTA_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.QuotaEntry = v_uint8() self.QuotaList = LIST_ENTRY() self.ReferenceCount = v_uint32() self.ProcessCount = v_uint32() class CM_KEY_HASH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ConvKey = v_uint32() self.NextHash = v_ptr32() self.KeyHive = v_ptr32() self.KeyCell = v_uint32() class BUS_HANDLER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint32() self.InterfaceType = v_uint32() self.ConfigurationType = v_uint32() self.BusNumber = v_uint32() self.DeviceObject = v_ptr32() self.ParentHandler = v_ptr32() self.BusData = v_ptr32() self.DeviceControlExtensionSize = v_uint32() self.BusAddresses = v_ptr32() self.Reserved = v_bytes(size=16) # FIXME Unknown Array Type self.GetBusData = v_ptr32() self.SetBusData = v_ptr32() self.AdjustResourceList = v_ptr32() self.AssignSlotResources = v_ptr32() self.GetInterruptVector = v_ptr32() self.TranslateBusAddress = v_ptr32() self.Spare1 = v_ptr32() self.Spare2 = v_ptr32() self.Spare3 = v_ptr32() self.Spare4 = v_ptr32() self.Spare5 = v_ptr32() self.Spare6 = v_ptr32() self.Spare7 = v_ptr32() self.Spare8 = v_ptr32() class OBJECT_HEADER_NAME_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Directory = v_ptr32() self.Name = UNICODE_STRING() self.QueryReferences = v_uint32() class PEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InheritedAddressSpace = v_uint8() self.ReadImageFileExecOptions = v_uint8() self.BeingDebugged = v_uint8() self.SpareBool = v_uint8() self.Mutant = v_ptr32() self.ImageBaseAddress = v_ptr32() self.Ldr = v_ptr32() self.ProcessParameters = v_ptr32() self.SubSystemData = v_ptr32() self.ProcessHeap = v_ptr32() self.FastPebLock = v_ptr32() self.FastPebLockRoutine = v_ptr32() self.FastPebUnlockRoutine = v_ptr32() self.EnvironmentUpdateCount = v_uint32() self.KernelCallbackTable = v_ptr32() self.SystemReserved = v_bytes(size=4) # FIXME Unknown Array Type self.AtlThunkSListPtr32 = v_uint32() self.FreeList = v_ptr32() self.TlsExpansionCounter = v_uint32() self.TlsBitmap = v_ptr32() self.TlsBitmapBits = v_bytes(size=8) # FIXME Unknown Array Type self.ReadOnlySharedMemoryBase = v_ptr32() self.ReadOnlySharedMemoryHeap = v_ptr32() self.ReadOnlyStaticServerData = v_ptr32() self.AnsiCodePageData = v_ptr32() self.OemCodePageData = v_ptr32() self.UnicodeCaseTableData = v_ptr32() self.NumberOfProcessors = v_uint32() self.NtGlobalFlag = v_uint32() self._pad0070 = v_bytes(size=4) self.CriticalSectionTimeout = LARGE_INTEGER() self.HeapSegmentReserve = v_uint32() self.HeapSegmentCommit = v_uint32() self.HeapDeCommitTotalFreeThreshold = v_uint32() self.HeapDeCommitFreeBlockThreshold = v_uint32() self.NumberOfHeaps = v_uint32() self.MaximumNumberOfHeaps = v_uint32() self.ProcessHeaps = v_ptr32() self.GdiSharedHandleTable = v_ptr32() self.ProcessStarterHelper = v_ptr32() self.GdiDCAttributeList = v_uint32() self.LoaderLock = v_ptr32() self.OSMajorVersion = v_uint32() self.OSMinorVersion = v_uint32() self.OSBuildNumber = v_uint16() self.OSCSDVersion = v_uint16() self.OSPlatformId = v_uint32() self.ImageSubsystem = v_uint32() self.ImageSubsystemMajorVersion = v_uint32() self.ImageSubsystemMinorVersion = v_uint32() self.ImageProcessAffinityMask = v_uint32() self.GdiHandleBuffer = v_bytes(size=136) # FIXME Unknown Array Type self.PostProcessInitRoutine = v_ptr32() self.TlsExpansionBitmap = v_ptr32() self.TlsExpansionBitmapBits = v_bytes(size=128) # FIXME Unknown Array Type self.SessionId = v_uint32() self.AppCompatFlags = ULARGE_INTEGER() self.AppCompatFlagsUser = ULARGE_INTEGER() self.pShimData = v_ptr32() self.AppCompatInfo = v_ptr32() self.CSDVersion = UNICODE_STRING() self.ActivationContextData = v_ptr32() self.ProcessAssemblyStorageMap = v_ptr32() self.SystemDefaultActivationContextData = v_ptr32() self.SystemAssemblyStorageMap = v_ptr32() self.MinimumStackCommit = v_uint32() class DBGKD_ANY_CONTROL_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.X86ControlSet = X86_DBGKD_CONTROL_SET() class MMSUPPORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LastTrimTime = LARGE_INTEGER() self.Flags = MMSUPPORT_FLAGS() self.PageFaultCount = v_uint32() self.PeakWorkingSetSize = v_uint32() self.WorkingSetSize = v_uint32() self.MinimumWorkingSetSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.VmWorkingSetList = v_ptr32() self.WorkingSetExpansionLinks = LIST_ENTRY() self.Claim = v_uint32() self.NextEstimationSlot = v_uint32() self.NextAgingSlot = v_uint32() self.EstimatedAvailable = v_uint32() self.GrowthSinceLastEstimate = v_uint32() class HBASE_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.Sequence1 = v_uint32() self.Sequence2 = v_uint32() self.TimeStamp = LARGE_INTEGER() self.Major = v_uint32() self.Minor = v_uint32() self.Type = v_uint32() self.Format = v_uint32() self.RootCell = v_uint32() self.Length = v_uint32() self.Cluster = v_uint32() self.FileName = v_bytes(size=64) # FIXME Unknown Array Type self.Reserved1 = v_bytes(size=396) # FIXME Unknown Array Type self.CheckSum = v_uint32() self.Reserved2 = v_bytes(size=3576) # FIXME Unknown Array Type self.BootType = v_uint32() self.BootRecover = v_uint32() class BUS_EXTENSION_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.BusExtension = v_ptr32() class DBGKD_GET_SET_BUS_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BusDataType = v_uint32() self.BusNumber = v_uint32() self.SlotNumber = v_uint32() self.Offset = v_uint32() self.Length = v_uint32() class KDPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Number = v_uint8() self.Importance = v_uint8() self.DpcListEntry = LIST_ENTRY() self.DeferredRoutine = v_ptr32() self.DeferredContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.Lock = v_ptr32() class KEVENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class KSEMAPHORE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.Limit = v_uint32() class PCI_ARBITER_INSTANCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = PCI_SECONDARY_EXTENSION() self.Interface = v_ptr32() self.BusFdoExtension = v_ptr32() self.InstanceName = v_bytes(size=48) # FIXME Unknown Array Type self.CommonInstance = ARBITER_INSTANCE() class PI_RESOURCE_ARBITER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceArbiterList = LIST_ENTRY() self.ResourceType = v_uint8() self._pad000c = v_bytes(size=3) self.ArbiterInterface = v_ptr32() self.Level = v_uint32() self.ResourceList = LIST_ENTRY() self.BestResourceList = LIST_ENTRY() self.BestConfig = LIST_ENTRY() self.ActiveArbiterList = LIST_ENTRY() self.State = v_uint8() self.ResourcesChanged = v_uint8() class OBJECT_TYPE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mutex = ERESOURCE() self.TypeList = LIST_ENTRY() self.Name = UNICODE_STRING() self.DefaultObject = v_ptr32() self.Index = v_uint32() self.TotalNumberOfObjects = v_uint32() self.TotalNumberOfHandles = v_uint32() self.HighWaterNumberOfObjects = v_uint32() self.HighWaterNumberOfHandles = v_uint32() self.TypeInfo = OBJECT_TYPE_INITIALIZER() self.Key = v_uint32() self.ObjectLocks = v_uint32() class DBGKD_SET_INTERNAL_BREAKPOINT32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakpointAddress = v_uint32() self.Flags = v_uint32() class DBGKD_CONTINUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContinueStatus = v_uint32() class POOL_HACKER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = POOL_HEADER() self.Contents = v_bytes(size=32) # FIXME Unknown Array Type class HANDLE_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TableCode = v_uint32() self.QuotaProcess = v_ptr32() self.UniqueProcessId = v_ptr32() self.HandleTableLock = v_ptr32() self.HandleTableList = LIST_ENTRY() self.HandleContentionEvent = EX_PUSH_LOCK() self.DebugInfo = v_ptr32() self.ExtraInfoPages = v_uint32() self.FirstFree = v_uint32() self.LastFree = v_uint32() self.NextHandleNeedingPool = v_uint32() self.HandleCount = v_uint32() self.Flags = v_uint32() class PO_HIBER_PERF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IoTicks = v_uint64() self.InitTicks = v_uint64() self.CopyTicks = v_uint64() self.StartCount = v_uint64() self.ElapsedTime = v_uint32() self.IoTime = v_uint32() self.CopyTime = v_uint32() self.InitTime = v_uint32() self.PagesWritten = v_uint32() self.PagesProcessed = v_uint32() self.BytesCopied = v_uint32() self.DumpCount = v_uint32() self.FileRuns = v_uint32() class DEFERRED_WRITE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NodeTypeCode = v_uint16() self.NodeByteSize = v_uint16() self.FileObject = v_ptr32() self.BytesToWrite = v_uint32() self.DeferredWriteLinks = LIST_ENTRY() self.Event = v_ptr32() self.PostRoutine = v_ptr32() self.Context1 = v_ptr32() self.Context2 = v_ptr32() self.LimitModifiedPages = v_uint8() class ARBITER_INSTANCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.MutexEvent = v_ptr32() self.Name = v_ptr32() self.ResourceType = v_uint32() self.Allocation = v_ptr32() self.PossibleAllocation = v_ptr32() self.OrderingList = ARBITER_ORDERING_LIST() self.ReservedList = ARBITER_ORDERING_LIST() self.ReferenceCount = v_uint32() self.Interface = v_ptr32() self.AllocationStackMaxSize = v_uint32() self.AllocationStack = v_ptr32() self.UnpackRequirement = v_ptr32() self.PackResource = v_ptr32() self.UnpackResource = v_ptr32() self.ScoreRequirement = v_ptr32() self.TestAllocation = v_ptr32() self.RetestAllocation = v_ptr32() self.CommitAllocation = v_ptr32() self.RollbackAllocation = v_ptr32() self.BootAllocation = v_ptr32() self.QueryArbitrate = v_ptr32() self.QueryConflict = v_ptr32() self.AddReserved = v_ptr32() self.StartArbiter = v_ptr32() self.PreprocessEntry = v_ptr32() self.AllocateEntry = v_ptr32() self.GetNextAllocationRange = v_ptr32() self.FindSuitableRange = v_ptr32() self.AddAllocation = v_ptr32() self.BacktrackAllocation = v_ptr32() self.OverrideConflict = v_ptr32() self.TransactionInProgress = v_uint8() self._pad008c = v_bytes(size=3) self.Extension = v_ptr32() self.BusDeviceObject = v_ptr32() self.ConflictCallbackContext = v_ptr32() self.ConflictCallback = v_ptr32() class MMMOD_WRITER_LISTHEAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = LIST_ENTRY() self.Event = KEVENT() class MMPFNENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Modified = v_uint32() class POP_IDLE_HANDLER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Latency = v_uint32() self.TimeCheck = v_uint32() self.DemoteLimit = v_uint32() self.PromoteLimit = v_uint32() self.PromoteCount = v_uint32() self.Demote = v_uint8() self.Promote = v_uint8() self.PromotePercent = v_uint8() self.DemotePercent = v_uint8() self.State = v_uint8() self.Spare = v_bytes(size=3) # FIXME Unknown Array Type self.IdleFunction = v_ptr32() class MMSUPPORT_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SessionSpace = v_uint32() class HEAP_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = unnamed() class EXCEPTION_REGISTRATION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Handler = v_ptr32() class FILE_BASIC_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.FileAttributes = v_uint32() class PLUGPLAY_EVENT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EventGuid = GUID() self.EventCategory = v_uint32() self.Result = v_ptr32() self.Flags = v_uint32() self.TotalSize = v_uint32() self.DeviceObject = v_ptr32() self.u = unnamed() class LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_ptr32() self.Blink = v_ptr32() class CM_KEY_SECURITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint16() self.Reserved = v_uint16() self.Flink = v_uint32() self.Blink = v_uint32() self.ReferenceCount = v_uint32() self.DescriptorLength = v_uint32() self.Descriptor = SECURITY_DESCRIPTOR_RELATIVE() class HMAP_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BlockAddress = v_uint32() self.BinAddress = v_uint32() self.CmView = v_ptr32() self.MemAlloc = v_uint32() class POP_ACTION_TRIGGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() self.Flags = v_uint8() self.Spare = v_bytes(size=3) # FIXME Unknown Array Type self.Battery = unnamed() class CM_CACHED_VALUE_INDEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CellIndex = v_uint32() self.Data = unnamed() class DEVICE_MAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DosDevicesDirectory = v_ptr32() self.GlobalDosDevicesDirectory = v_ptr32() self.ReferenceCount = v_uint32() self.DriveMap = v_uint32() self.DriveType = v_bytes(size=32) # FIXME Unknown Array Type class CONTROL_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Segment = v_ptr32() self.DereferenceList = LIST_ENTRY() self.NumberOfSectionReferences = v_uint32() self.NumberOfPfnReferences = v_uint32() self.NumberOfMappedViews = v_uint32() self.NumberOfSubsections = v_uint16() self.FlushInProgressCount = v_uint16() self.NumberOfUserReferences = v_uint32() self.u = unnamed() self.FilePointer = v_ptr32() self.WaitingForDeletion = v_ptr32() self.ModifiedWriteCount = v_uint16() self.NumberOfSystemCacheViews = v_uint16() class GUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data1 = v_uint32() self.Data2 = v_uint16() self.Data3 = v_uint16() self.Data4 = v_bytes(size=8) # FIXME Unknown Array Type class KAPC_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ApcListHead = v_bytes(size=8) # FIXME Unknown Array Type self.Process = v_ptr32() self.KernelApcInProgress = v_uint8() self.KernelApcPending = v_uint8() self.UserApcPending = v_uint8() class MMVAD_SHORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartingVpn = v_uint32() self.EndingVpn = v_uint32() self.Parent = v_ptr32() self.LeftChild = v_ptr32() self.RightChild = v_ptr32() self.u = unnamed() class DBGKD_GET_VERSION32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.ProtocolVersion = v_uint16() self.Flags = v_uint16() self.KernBase = v_uint32() self.PsLoadedModuleList = v_uint32() self.MachineType = v_uint16() self.ThCallbackStack = v_uint16() self.NextCallback = v_uint16() self.FramePointer = v_uint16() self.KiCallUserMode = v_uint32() self.KeUserCallbackDispatcher = v_uint32() self.BreakpointWithStatus = v_uint32() self.DebuggerDataList = v_uint32() class CM_CELL_REMAP_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OldCell = v_uint32() self.NewCell = v_uint32() class KIDTENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint16() self.Selector = v_uint16() self.Access = v_uint16() self.ExtendedOffset = v_uint16() class PO_MEMORY_RANGE_ARRAY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Range = unnamed() class GENERIC_MAPPING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GenericRead = v_uint32() self.GenericWrite = v_uint32() self.GenericExecute = v_uint32() self.GenericAll = v_uint32() class IRP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.MdlAddress = v_ptr32() self.Flags = v_uint32() self.AssociatedIrp = unnamed() self.ThreadListEntry = LIST_ENTRY() self.IoStatus = IO_STATUS_BLOCK() self.RequestorMode = v_uint8() self.PendingReturned = v_uint8() self.StackCount = v_uint8() self.CurrentLocation = v_uint8() self.Cancel = v_uint8() self.CancelIrql = v_uint8() self.ApcEnvironment = v_uint8() self.AllocationFlags = v_uint8() self.UserIosb = v_ptr32() self.UserEvent = v_ptr32() self.Overlay = unnamed() self.CancelRoutine = v_ptr32() self.UserBuffer = v_ptr32() self.Tail = unnamed() class MMADDRESS_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartVpn = v_uint32() self.EndVpn = v_uint32() class DRIVER_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Flags = v_uint32() self.DriverStart = v_ptr32() self.DriverSize = v_uint32() self.DriverSection = v_ptr32() self.DriverExtension = v_ptr32() self.DriverName = UNICODE_STRING() self.HardwareDatabase = v_ptr32() self.FastIoDispatch = v_ptr32() self.DriverInit = v_ptr32() self.DriverStartIo = v_ptr32() self.DriverUnload = v_ptr32() self.MajorFunction = v_bytes(size=112) # FIXME Unknown Array Type class SECURITY_DESCRIPTOR_RELATIVE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.Sbz1 = v_uint8() self.Control = v_uint16() self.Owner = v_uint32() self.Group = v_uint32() self.Sacl = v_uint32() self.Dacl = v_uint32() class DUMP_INITIALIZATION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Reserved = v_uint32() self.MemoryBlock = v_ptr32() self.CommonBuffer = v_bytes(size=8) # FIXME Unknown Array Type self._pad0018 = v_bytes(size=4) self.PhysicalAddress = v_bytes(size=8) # FIXME Unknown Array Type self.StallRoutine = v_ptr32() self.OpenRoutine = v_ptr32() self.WriteRoutine = v_ptr32() self.FinishRoutine = v_ptr32() self.AdapterObject = v_ptr32() self.MappedRegisterBase = v_ptr32() self.PortConfiguration = v_ptr32() self.CrashDump = v_uint8() self._pad0048 = v_bytes(size=3) self.MaximumTransferSize = v_uint32() self.CommonBufferSize = v_uint32() self.TargetAddress = v_ptr32() self.WritePendingRoutine = v_ptr32() self.PartitionStyle = v_uint32() self.DiskInfo = unnamed() class FILE_GET_QUOTA_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextEntryOffset = v_uint32() self.SidLength = v_uint32() self.Sid = SID() class IO_COMPLETION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = v_ptr32() self.Key = v_ptr32() class DRIVER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DriverObject = v_ptr32() self.AddDevice = v_ptr32() self.Count = v_uint32() self.ServiceKeyName = UNICODE_STRING() self.ClientDriverExtension = v_ptr32() self.FsFilterCallbacks = v_ptr32() class TOKEN_SOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SourceName = v_bytes(size=8) # FIXME Unknown Array Type self.SourceIdentifier = LUID() class MMPFN(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u1 = unnamed() self.PteAddress = v_ptr32() self.u2 = unnamed() self.u3 = unnamed() self.OriginalPte = MMPTE() self.u4 = unnamed() class flags(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Removable = v_uint8() class DBGKD_SEARCH_MEMORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SearchAddress = v_uint64() self.SearchLength = v_uint64() self.PatternLength = v_uint32() class PM_SUPPORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Rsvd2 = v_uint8() class KPRCB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinorVersion = v_uint16() self.MajorVersion = v_uint16() self.CurrentThread = v_ptr32() self.NextThread = v_ptr32() self.IdleThread = v_ptr32() self.Number = v_uint8() self.Reserved = v_uint8() self.BuildType = v_uint16() self.SetMember = v_uint32() self.CpuType = v_uint8() self.CpuID = v_uint8() self.CpuStep = v_uint16() self.ProcessorState = KPROCESSOR_STATE() self.KernelReserved = v_bytes(size=64) # FIXME Unknown Array Type self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.PrcbPad0 = v_bytes(size=92) # FIXME Unknown Array Type self.LockQueue = v_bytes(size=92) # FIXME Unknown Array Type self.PrcbPad1 = v_bytes(size=8) # FIXME Unknown Array Type self.NpxThread = v_ptr32() self.InterruptCount = v_uint32() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.DpcTime = v_uint32() self.DebugDpcTime = v_uint32() self.InterruptTime = v_uint32() self.AdjustDpcThreshold = v_uint32() self.PageColor = v_uint32() self.SkipTick = v_uint32() self.MultiThreadSetBusy = v_uint8() self.Spare2 = v_bytes(size=3) # FIXME Unknown Array Type self.ParentNode = v_ptr32() self.MultiThreadProcessorSet = v_uint32() self.MultiThreadSetMaster = v_ptr32() self.ThreadStartCount = v_bytes(size=8) # FIXME Unknown Array Type self.CcFastReadNoWait = v_uint32() self.CcFastReadWait = v_uint32() self.CcFastReadNotPossible = v_uint32() self.CcCopyReadNoWait = v_uint32() self.CcCopyReadWait = v_uint32() self.CcCopyReadNoWaitMiss = v_uint32() self.KeAlignmentFixupCount = v_uint32() self.KeContextSwitches = v_uint32() self.KeDcacheFlushCount = v_uint32() self.KeExceptionDispatchCount = v_uint32() self.KeFirstLevelTbFills = v_uint32() self.KeFloatingEmulationCount = v_uint32() self.KeIcacheFlushCount = v_uint32() self.KeSecondLevelTbFills = v_uint32() self.KeSystemCalls = v_uint32() self.SpareCounter0 = v_bytes(size=4) # FIXME Unknown Array Type self.PPLookasideList = v_bytes(size=4) # FIXME Unknown Array Type self.PPNPagedLookasideList = v_bytes(size=4) # FIXME Unknown Array Type self.PPPagedLookasideList = v_bytes(size=4) # FIXME Unknown Array Type self.PacketBarrier = v_uint32() self.ReverseStall = v_uint32() self.IpiFrame = v_ptr32() self.PrcbPad2 = v_bytes(size=52) # FIXME Unknown Array Type self.CurrentPacket = v_bytes(size=12) # FIXME Unknown Array Type self.TargetSet = v_uint32() self.WorkerRoutine = v_ptr32() self.IpiFrozen = v_uint32() self.PrcbPad3 = v_bytes(size=40) # FIXME Unknown Array Type self.RequestSummary = v_uint32() self.SignalDone = v_ptr32() self.PrcbPad4 = v_bytes(size=56) # FIXME Unknown Array Type self.DpcListHead = LIST_ENTRY() self.DpcStack = v_ptr32() self.DpcCount = v_uint32() self.DpcQueueDepth = v_uint32() self.DpcRoutineActive = v_uint32() self.DpcInterruptRequested = v_uint32() self.DpcLastCount = v_uint32() self.DpcRequestRate = v_uint32() self.MaximumDpcQueueDepth = v_uint32() self.MinimumDpcRate = v_uint32() self.QuantumEnd = v_uint32() self.PrcbPad5 = v_bytes(size=16) # FIXME Unknown Array Type self.DpcLock = v_uint32() self.PrcbPad6 = v_bytes(size=28) # FIXME Unknown Array Type self.CallDpc = KDPC() self.ChainedInterruptList = v_ptr32() self.LookasideIrpFloat = v_uint32() self.SpareFields0 = v_bytes(size=24) # FIXME Unknown Array Type self.VendorString = v_bytes(size=13) # FIXME Unknown Array Type self.InitialApicId = v_uint8() self.LogicalProcessorsPerPhysicalProcessor = v_uint8() self._pad0910 = v_bytes(size=1) self.MHz = v_uint32() self.FeatureBits = v_uint32() self.UpdateSignature = LARGE_INTEGER() self.NpxSaveArea = FX_SAVE_AREA() self.PowerState = PROCESSOR_POWER_STATE() class HEAP_VIRTUAL_ALLOC_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = LIST_ENTRY() self.ExtraStuff = HEAP_ENTRY_EXTRA() self.CommitSize = v_uint32() self.ReserveSize = v_uint32() self.BusyBlock = HEAP_ENTRY() class VI_DEADLOCK_THREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Thread = v_ptr32() self.CurrentSpinNode = v_ptr32() self.CurrentOtherNode = v_ptr32() self.ListEntry = LIST_ENTRY() self.NodeCount = v_uint32() self.PagingCount = v_uint32() class SUPPORTED_RANGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.SystemAddressSpace = v_uint32() self.SystemBase = v_uint64() self.Base = v_uint64() self.Limit = v_uint64() class ARBITER_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Parameters = unnamed() class EXCEPTION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionCode = v_uint32() self.ExceptionFlags = v_uint32() self.ExceptionRecord = v_ptr32() self.ExceptionAddress = v_ptr32() self.NumberParameters = v_uint32() self.ExceptionInformation = v_bytes(size=60) # FIXME Unknown Array Type class MMPTE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u = unnamed() class VI_DEADLOCK_NODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Parent = v_ptr32() self.ChildrenList = LIST_ENTRY() self.SiblingsList = LIST_ENTRY() self.ResourceList = LIST_ENTRY() self.Root = v_ptr32() self.ThreadEntry = v_ptr32() self.Active = v_uint32() self.StackTrace = v_bytes(size=32) # FIXME Unknown Array Type self.ParentStackTrace = v_bytes(size=32) # FIXME Unknown Array Type class KPCR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.SelfPcr = v_ptr32() self.Prcb = v_ptr32() self.Irql = v_uint8() self._pad0028 = v_bytes(size=3) self.IRR = v_uint32() self.IrrActive = v_uint32() self.IDR = v_uint32() self.KdVersionBlock = v_ptr32() self.IDT = v_ptr32() self.GDT = v_ptr32() self.TSS = v_ptr32() self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.SetMember = v_uint32() self.StallScaleFactor = v_uint32() self.DebugActive = v_uint8() self.Number = v_uint8() self.Spare0 = v_uint8() self.SecondLevelCacheAssociativity = v_uint8() self.VdmAlert = v_uint32() self.KernelReserved = v_bytes(size=56) # FIXME Unknown Array Type self.SecondLevelCacheSize = v_uint32() self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.InterruptMode = v_uint32() self.Spare1 = v_uint8() self._pad00dc = v_bytes(size=3) self.KernelReserved2 = v_bytes(size=68) # FIXME Unknown Array Type self.PrcbData = KPRCB() class IMAGE_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Machine = v_uint16() self.NumberOfSections = v_uint16() self.TimeDateStamp = v_uint32() self.PointerToSymbolTable = v_uint32() self.NumberOfSymbols = v_uint32() self.SizeOfOptionalHeader = v_uint16() self.Characteristics = v_uint16() class CM_KEY_INDEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint16() self.Count = v_uint16() self.List = v_bytes(size=4) # FIXME Unknown Array Type class IMAGE_DEBUG_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Characteristics = v_uint32() self.TimeDateStamp = v_uint32() self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.Type = v_uint32() self.SizeOfData = v_uint32() self.AddressOfRawData = v_uint32() self.PointerToRawData = v_uint32() class SYSPTES_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = LIST_ENTRY() self.Count = v_uint32() class DBGKD_READ_WRITE_IO_EXTENDED32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.AddressSpace = v_uint32() self.IoAddress = v_uint32() self.DataValue = v_uint32() class PEB_LDR_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Initialized = v_uint8() self._pad0008 = v_bytes(size=3) self.SsHandle = v_ptr32() self.InLoadOrderModuleList = LIST_ENTRY() self.InMemoryOrderModuleList = LIST_ENTRY() self.InInitializationOrderModuleList = LIST_ENTRY() self.EntryInProgress = v_ptr32() class DBGKD_WRITE_BREAKPOINT64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakPointAddress = v_uint64() self.BreakPointHandle = v_uint32() class MMPFNLIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Total = v_uint32() self.ListName = v_uint32() self.Flink = v_uint32() self.Blink = v_uint32() class HEAP_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.PreviousSize = v_uint16() self.SmallTagIndex = v_uint8() self.Flags = v_uint8() self.UnusedBytes = v_uint8() self.SegmentIndex = v_uint8() class SECURITY_SUBJECT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientToken = v_ptr32() self.ImpersonationLevel = v_uint32() self.PrimaryToken = v_ptr32() self.ProcessAuditId = v_ptr32() class X86_DBGKD_CONTROL_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TraceFlag = v_uint32() self.Dr7 = v_uint32() self.CurrentSymbolStart = v_uint32() self.CurrentSymbolEnd = v_uint32() class SEP_AUDIT_POLICY_OVERLAY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PolicyBits = v_uint64() class MI_VERIFIER_DRIVER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Links = LIST_ENTRY() self.Loads = v_uint32() self.Unloads = v_uint32() self.BaseName = UNICODE_STRING() self.StartAddress = v_ptr32() self.EndAddress = v_ptr32() self.Flags = v_uint32() self.Signature = v_uint32() self.Reserved = v_uint32() self.VerifierPoolLock = v_uint32() self.PoolHash = v_ptr32() self.PoolHashSize = v_uint32() self.PoolHashFree = v_uint32() self.PoolHashReserved = v_uint32() self.CurrentPagedPoolAllocations = v_uint32() self.CurrentNonPagedPoolAllocations = v_uint32() self.PeakPagedPoolAllocations = v_uint32() self.PeakNonPagedPoolAllocations = v_uint32() self.PagedBytes = v_uint32() self.NonPagedBytes = v_uint32() self.PeakPagedBytes = v_uint32() self.PeakNonPagedBytes = v_uint32() class GDI_TEB_BATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint32() self.HDC = v_uint32() self.Buffer = v_bytes(size=1240) # FIXME Unknown Array Type class WMI_CLIENT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ProcessorNumber = v_uint8() self.Alignment = v_uint8() self.LoggerId = v_uint16() class PCI_MJ_DISPATCH_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PnpIrpMaximumMinorFunction = v_uint32() self.PnpIrpDispatchTable = v_ptr32() self.PowerIrpMaximumMinorFunction = v_uint32() self.PowerIrpDispatchTable = v_ptr32() self.SystemControlIrpDispatchStyle = v_uint32() self.SystemControlIrpDispatchFunction = v_ptr32() self.OtherIrpDispatchStyle = v_uint32() self.OtherIrpDispatchFunction = v_ptr32() class INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.Context = v_ptr32() self.InterfaceReference = v_ptr32() self.InterfaceDereference = v_ptr32() class OBJECT_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashBuckets = v_bytes(size=148) # FIXME Unknown Array Type self.Lock = EX_PUSH_LOCK() self.DeviceMap = v_ptr32() self.SessionId = v_uint32() self.Reserved = v_uint16() self.SymbolicLinkUsageCount = v_uint16() class WMI_LOGGER_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BufferSpinLock = v_uint32() self._pad0008 = v_bytes(size=4) self.StartTime = LARGE_INTEGER() self.LogFileHandle = v_ptr32() self.LoggerSemaphore = KSEMAPHORE() self.LoggerThread = v_ptr32() self.LoggerEvent = KEVENT() self.FlushEvent = KEVENT() self.LoggerStatus = v_uint32() self.LoggerId = v_uint32() self.BuffersAvailable = v_uint32() self.UsePerfClock = v_uint32() self.WriteFailureLimit = v_uint32() self.BuffersDirty = v_uint32() self.BuffersInUse = v_uint32() self.SwitchingInProgress = v_uint32() self._pad0070 = v_bytes(size=4) self.FreeList = SLIST_HEADER() self.FlushList = SLIST_HEADER() self.GlobalList = SLIST_HEADER() self.ProcessorBuffers = v_ptr32() self.LoggerName = UNICODE_STRING() self.LogFileName = UNICODE_STRING() self.LogFilePattern = UNICODE_STRING() self.NewLogFileName = UNICODE_STRING() self.EndPageMarker = v_ptr32() self.CollectionOn = v_uint32() self.KernelTraceOn = v_uint32() self.PerfLogInTransition = v_uint32() self.RequestFlag = v_uint32() self.EnableFlags = v_uint32() self.MaximumFileSize = v_uint32() self.LoggerMode = v_uint32() self.LastFlushedBuffer = v_uint32() self.RefCount = v_uint32() self.FlushTimer = v_uint32() self.FirstBufferOffset = LARGE_INTEGER() self.ByteOffset = LARGE_INTEGER() self.BufferAgeLimit = LARGE_INTEGER() self.MaximumBuffers = v_uint32() self.MinimumBuffers = v_uint32() self.EventsLost = v_uint32() self.BuffersWritten = v_uint32() self.LogBuffersLost = v_uint32() self.RealTimeBuffersLost = v_uint32() self.BufferSize = v_uint32() self.NumberOfBuffers = v_uint32() self.SequencePtr = v_ptr32() self.InstanceGuid = GUID() self.LoggerHeader = v_ptr32() self.GetCpuClock = v_ptr32() self.ClientSecurityContext = SECURITY_CLIENT_CONTEXT() self.LoggerExtension = v_ptr32() self.ReleaseQueue = v_uint32() self.EnableFlagExtension = TRACE_ENABLE_FLAG_EXTENSION() self.LocalSequence = v_uint32() self.MaximumIrql = v_uint32() self.EnableFlagArray = v_ptr32() self.LoggerMutex = KMUTANT() self.MutexCount = v_uint32() self.FileCounter = v_uint32() self.BufferCallback = v_ptr32() self.CallbackContext = v_ptr32() self.PoolType = v_uint32() self._pad01b8 = v_bytes(size=4) self.ReferenceSystemTime = LARGE_INTEGER() self.ReferenceTimeStamp = LARGE_INTEGER() class DBGKD_READ_WRITE_MSR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Msr = v_uint32() self.DataValueLow = v_uint32() self.DataValueHigh = v_uint32() class IMAGE_DATA_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.Size = v_uint32() class FILE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Vpb = v_ptr32() self.FsContext = v_ptr32() self.FsContext2 = v_ptr32() self.SectionObjectPointer = v_ptr32() self.PrivateCacheMap = v_ptr32() self.FinalStatus = v_uint32() self.RelatedFileObject = v_ptr32() self.LockOperation = v_uint8() self.DeletePending = v_uint8() self.ReadAccess = v_uint8() self.WriteAccess = v_uint8() self.DeleteAccess = v_uint8() self.SharedRead = v_uint8() self.SharedWrite = v_uint8() self.SharedDelete = v_uint8() self.Flags = v_uint32() self.FileName = UNICODE_STRING() self.CurrentByteOffset = LARGE_INTEGER() self.Waiters = v_uint32() self.Busy = v_uint32() self.LastLock = v_ptr32() self.Lock = KEVENT() self.Event = KEVENT() self.CompletionContext = v_ptr32() class MMWSLE_HASH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Key = v_ptr32() self.Index = v_uint32() class SECTION_IMAGE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TransferAddress = v_ptr32() self.ZeroBits = v_uint32() self.MaximumStackSize = v_uint32() self.CommittedStackSize = v_uint32() self.SubSystemType = v_uint32() self.SubSystemMinorVersion = v_uint16() self.SubSystemMajorVersion = v_uint16() self.GpValue = v_uint32() self.ImageCharacteristics = v_uint16() self.DllCharacteristics = v_uint16() self.Machine = v_uint16() self.ImageContainsCode = v_uint8() self.Spare1 = v_uint8() self.LoaderFlags = v_uint32() self.ImageFileSize = v_uint32() self.Reserved = v_bytes(size=4) # FIXME Unknown Array Type class HEAP_SUBSEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Bucket = v_ptr32() self.UserBlocks = v_ptr32() self.AggregateExchg = INTERLOCK_SEQ() self.BlockSize = v_uint16() self.FreeThreshold = v_uint16() self.BlockCount = v_uint16() self.SizeIndex = v_uint8() self.AffinityIndex = v_uint8() self.SFreeListEntry = SINGLE_LIST_ENTRY() self.Lock = v_uint32() class ERESOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemResourcesList = LIST_ENTRY() self.OwnerTable = v_ptr32() self.ActiveCount = v_uint16() self.Flag = v_uint16() self.SharedWaiters = v_ptr32() self.ExclusiveWaiters = v_ptr32() self.OwnerThreads = v_ptr32() self.ContentionCount = v_uint32() self.NumberOfSharedWaiters = v_uint16() self.NumberOfExclusiveWaiters = v_uint16() self.Address = v_ptr32() self.SpinLock = v_uint32() class MBCB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NodeTypeCode = v_uint16() self.NodeIsInZone = v_uint16() self.PagesToWrite = v_uint32() self.DirtyPages = v_uint32() self.Reserved = v_uint32() self.BitmapRanges = LIST_ENTRY() self.ResumeWritePage = v_uint64() self.BitmapRange1 = BITMAP_RANGE() self.BitmapRange2 = BITMAP_RANGE() self.BitmapRange3 = BITMAP_RANGE() class RTL_ATOM_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashLink = v_ptr32() self.HandleIndex = v_uint16() self.Atom = v_uint16() self.ReferenceCount = v_uint16() self.Flags = v_uint8() self.NameLength = v_uint8() self.Name = v_bytes(size=2) # FIXME Unknown Array Type class CHILD_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = v_uint32() class RTL_RANGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = v_uint64() self.End = v_uint64() self.UserData = v_ptr32() self.Owner = v_ptr32() self.Attributes = v_uint8() self.Flags = v_uint8() class MMSUBSECTION_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ReadOnly = v_uint32() class EX_PUSH_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Waiting = v_uint32() class ARBITER_INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.Context = v_ptr32() self.InterfaceReference = v_ptr32() self.InterfaceDereference = v_ptr32() self.ArbiterHandler = v_ptr32() self.Flags = v_uint32() class SLIST_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Alignment = v_uint64() class HEAP_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.Signature = v_uint32() self.Flags = v_uint32() self.Heap = v_ptr32() self.LargestUnCommittedRange = v_uint32() self.BaseAddress = v_ptr32() self.NumberOfPages = v_uint32() self.FirstEntry = v_ptr32() self.LastValidEntry = v_ptr32() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.UnCommittedRanges = v_ptr32() self.AllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self.LastEntryInSegment = v_ptr32() class POP_DEVICE_POWER_IRP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Free = SINGLE_LIST_ENTRY() self.Irp = v_ptr32() self.Notify = v_ptr32() self.Pending = LIST_ENTRY() self.Complete = LIST_ENTRY() self.Abort = LIST_ENTRY() self.Failed = LIST_ENTRY() class PRIVATE_CACHE_MAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NodeTypeCode = v_uint16() self._pad0004 = v_bytes(size=2) self.ReadAheadMask = v_uint32() self.FileObject = v_ptr32() self._pad0010 = v_bytes(size=4) self.FileOffset1 = LARGE_INTEGER() self.BeyondLastByte1 = LARGE_INTEGER() self.FileOffset2 = LARGE_INTEGER() self.BeyondLastByte2 = LARGE_INTEGER() self.ReadAheadOffset = LARGE_INTEGER() self.ReadAheadLength = v_bytes(size=8) # FIXME Unknown Array Type self.ReadAheadSpinLock = v_uint32() self.PrivateLinks = LIST_ENTRY() class SEP_AUDIT_POLICY_CATEGORIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.System = v_uint32() self.AccountLogon = v_uint32() class IMAGE_SECTION_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = v_bytes(size=8) # FIXME Unknown Array Type self.Misc = unnamed() self.VirtualAddress = v_uint32() self.SizeOfRawData = v_uint32() self.PointerToRawData = v_uint32() self.PointerToRelocations = v_uint32() self.PointerToLinenumbers = v_uint32() self.NumberOfRelocations = v_uint16() self.NumberOfLinenumbers = v_uint16() self.Characteristics = v_uint32() class PO_DEVICE_NOTIFY_ORDER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DevNodeSequence = v_uint32() self.WarmEjectPdoPointer = v_ptr32() self.OrderLevel = v_ptr32() class DBGKD_WRITE_MEMORY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TargetBaseAddress = v_uint64() self.TransferCount = v_uint32() self.ActualBytesWritten = v_uint32() class LIST_ENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint64() self.Blink = v_uint64() class VACB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseAddress = v_ptr32() self.SharedCacheMap = v_ptr32() self.Overlay = unnamed() self.LruList = LIST_ENTRY() class WAIT_CONTEXT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitQueueEntry = KDEVICE_QUEUE_ENTRY() self.DeviceRoutine = v_ptr32() self.DeviceContext = v_ptr32() self.NumberOfMapRegisters = v_uint32() self.DeviceObject = v_ptr32() self.CurrentIrp = v_ptr32() self.BufferChainingDpc = v_ptr32() class CM_KEY_NODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint16() self.Flags = v_uint16() self.LastWriteTime = LARGE_INTEGER() self.Spare = v_uint32() self.Parent = v_uint32() self.SubKeyCounts = v_bytes(size=8) # FIXME Unknown Array Type self.SubKeyLists = v_bytes(size=8) # FIXME Unknown Array Type self.ValueList = CHILD_LIST() self.Security = v_uint32() self.Class = v_uint32() self.MaxNameLen = v_uint32() self.MaxClassLen = v_uint32() self.MaxValueNameLen = v_uint32() self.MaxValueDataLen = v_uint32() self.WorkVar = v_uint32() self.NameLength = v_uint16() self.ClassLength = v_uint16() self.Name = v_bytes(size=2) # FIXME Unknown Array Type class SE_AUDIT_PROCESS_CREATION_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ImageFileName = v_ptr32() class ACTIVATION_CONTEXT_STACK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.NextCookieSequenceNumber = v_uint32() self.ActiveFrame = v_ptr32() self.FrameListCache = LIST_ENTRY() class SECURITY_TOKEN_PROXY_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.ProxyClass = v_uint32() self.PathInfo = UNICODE_STRING() self.ContainerMask = v_uint32() self.ObjectMask = v_uint32() class HEAP_UCR_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.ReservedSize = v_uint32() self.CommittedSize = v_uint32() self.filler = v_uint32() class TEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.EnvironmentPointer = v_ptr32() self.ClientId = CLIENT_ID() self.ActiveRpcHandle = v_ptr32() self.ThreadLocalStoragePointer = v_ptr32() self.ProcessEnvironmentBlock = v_ptr32() self.LastErrorValue = v_uint32() self.CountOfOwnedCriticalSections = v_uint32() self.CsrClientThread = v_ptr32() self.Win32ThreadInfo = v_ptr32() self.User32Reserved = v_bytes(size=104) # FIXME Unknown Array Type self.UserReserved = v_bytes(size=20) # FIXME Unknown Array Type self.WOW32Reserved = v_ptr32() self.CurrentLocale = v_uint32() self.FpSoftwareStatusRegister = v_uint32() self.SystemReserved1 = v_bytes(size=216) # FIXME Unknown Array Type self.ExceptionCode = v_uint32() self.ActivationContextStack = ACTIVATION_CONTEXT_STACK() self.SpareBytes1 = v_bytes(size=24) # FIXME Unknown Array Type self.GdiTebBatch = GDI_TEB_BATCH() self.RealClientId = CLIENT_ID() self.GdiCachedProcessHandle = v_ptr32() self.GdiClientPID = v_uint32() self.GdiClientTID = v_uint32() self.GdiThreadLocalInfo = v_ptr32() self.Win32ClientInfo = v_bytes(size=248) # FIXME Unknown Array Type self.glDispatchTable = v_bytes(size=932) # FIXME Unknown Array Type self.glReserved1 = v_bytes(size=116) # FIXME Unknown Array Type self.glReserved2 = v_ptr32() self.glSectionInfo = v_ptr32() self.glSection = v_ptr32() self.glTable = v_ptr32() self.glCurrentRC = v_ptr32() self.glContext = v_ptr32() self.LastStatusValue = v_uint32() self.StaticUnicodeString = UNICODE_STRING() self.StaticUnicodeBuffer = v_bytes(size=522) # FIXME Unknown Array Type self._pad0e0c = v_bytes(size=2) self.DeallocationStack = v_ptr32() self.TlsSlots = v_bytes(size=256) # FIXME Unknown Array Type self.TlsLinks = LIST_ENTRY() self.Vdm = v_ptr32() self.ReservedForNtRpc = v_ptr32() self.DbgSsReserved = v_bytes(size=8) # FIXME Unknown Array Type self.HardErrorsAreDisabled = v_uint32() self.Instrumentation = v_bytes(size=64) # FIXME Unknown Array Type self.WinSockData = v_ptr32() self.GdiBatchCount = v_uint32() self.InDbgPrint = v_uint8() self.FreeStackOnTermination = v_uint8() self.HasFiberData = v_uint8() self.IdealProcessor = v_uint8() self.Spare3 = v_uint32() self.ReservedForPerf = v_ptr32() self.ReservedForOle = v_ptr32() self.WaitingOnLoaderLock = v_uint32() self.Wx86Thread = Wx86ThreadState() self.TlsExpansionSlots = v_ptr32() self.ImpersonationLocale = v_uint32() self.IsImpersonating = v_uint32() self.NlsCache = v_ptr32() self.pShimData = v_ptr32() self.HeapVirtualAffinity = v_uint32() self.CurrentTransactionHandle = v_ptr32() self.ActiveFrame = v_ptr32() self.SafeThunkCall = v_uint8() self.BooleanSpare = v_bytes(size=3) # FIXME Unknown Array Type class EX_RUNDOWN_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() class CM_NOTIFY_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HiveList = LIST_ENTRY() self.PostList = LIST_ENTRY() self.KeyControlBlock = v_ptr32() self.KeyBody = v_ptr32() self.Filter = v_uint32() self.SubjectContext = SECURITY_SUBJECT_CONTEXT() class MMPTE_PROTOTYPE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class PCI_HEADER_TYPE_DEPENDENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.type0 = unnamed() class CM_BIG_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint16() self.Count = v_uint16() self.List = v_uint32() class IMAGE_DOS_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.e_magic = v_uint16() self.e_cblp = v_uint16() self.e_cp = v_uint16() self.e_crlc = v_uint16() self.e_cparhdr = v_uint16() self.e_minalloc = v_uint16() self.e_maxalloc = v_uint16() self.e_ss = v_uint16() self.e_sp = v_uint16() self.e_csum = v_uint16() self.e_ip = v_uint16() self.e_cs = v_uint16() self.e_lfarlc = v_uint16() self.e_ovno = v_uint16() self.e_res = v_bytes(size=8) # FIXME Unknown Array Type self.e_oemid = v_uint16() self.e_oeminfo = v_uint16() self.e_res2 = v_bytes(size=20) # FIXME Unknown Array Type self.e_lfanew = v_uint32() class DBGKD_FILL_MEMORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_uint64() self.Length = v_uint32() self.Flags = v_uint16() self.PatternLength = v_uint16() class CM_KEY_SECURITY_CACHE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Cell = v_uint32() self.CachedSecurity = v_ptr32() class ARBITER_ORDERING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = v_uint64() self.End = v_uint64() class MMVIEW(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = v_uint32() self.ControlArea = v_ptr32() class EXCEPTION_RECORD32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionCode = v_uint32() self.ExceptionFlags = v_uint32() self.ExceptionRecord = v_uint32() self.ExceptionAddress = v_uint32() self.NumberParameters = v_uint32() self.ExceptionInformation = v_bytes(size=60) # FIXME Unknown Array Type class DBGKD_READ_MEMORY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TargetBaseAddress = v_uint32() self.TransferCount = v_uint32() self.ActualBytesRead = v_uint32() class QUAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DoNotUseThisField = v_uint64() class LPCP_PORT_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ConnectionPort = v_ptr32() self.ConnectedPort = v_ptr32() self.MsgQueue = LPCP_PORT_QUEUE() self.Creator = CLIENT_ID() self.ClientSectionBase = v_ptr32() self.ServerSectionBase = v_ptr32() self.PortContext = v_ptr32() self.ClientThread = v_ptr32() self.SecurityQos = SECURITY_QUALITY_OF_SERVICE() self.StaticSecurity = SECURITY_CLIENT_CONTEXT() self.LpcReplyChainHead = LIST_ENTRY() self.LpcDataInfoChainHead = LIST_ENTRY() self.ServerProcess = v_ptr32() self.MaxMessageLength = v_uint16() self.MaxConnectionInfoLength = v_uint16() self.Flags = v_uint32() self.WaitEvent = KEVENT() class CALL_PERFORMANCE_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SpinLock = v_uint32() self.HashTable = v_uint32() class EXCEPTION_POINTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionRecord = v_ptr32() self.ContextRecord = v_ptr32() class CM_KEY_SECURITY_CACHE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Cell = v_uint32() self.ConvKey = v_uint32() self.List = LIST_ENTRY() self.DescriptorLength = v_uint32() self.Descriptor = SECURITY_DESCRIPTOR_RELATIVE() class POP_TRIGGER_WAIT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Event = KEVENT() self.Status = v_uint32() self.Link = LIST_ENTRY() self.Trigger = v_ptr32() class DEVICE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.ReferenceCount = v_uint32() self.DriverObject = v_ptr32() self.NextDevice = v_ptr32() self.AttachedDevice = v_ptr32() self.CurrentIrp = v_ptr32() self.Timer = v_ptr32() self.Flags = v_uint32() self.Characteristics = v_uint32() self.Vpb = v_ptr32() self.DeviceExtension = v_ptr32() self.DeviceType = v_uint32() self.StackSize = v_uint8() self._pad0034 = v_bytes(size=3) self.Queue = unnamed() self.AlignmentRequirement = v_uint32() self.DeviceQueue = KDEVICE_QUEUE() self.Dpc = KDPC() self.ActiveThreadCount = v_uint32() self.SecurityDescriptor = v_ptr32() self.DeviceLock = KEVENT() self.SectorSize = v_uint16() self.Spare1 = v_uint16() self.DeviceObjectExtension = v_ptr32() self.Reserved = v_ptr32() class MMVAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartingVpn = v_uint32() self.EndingVpn = v_uint32() self.Parent = v_ptr32() self.LeftChild = v_ptr32() self.RightChild = v_ptr32() self.u = unnamed() self.ControlArea = v_ptr32() self.FirstPrototypePte = v_ptr32() self.LastContiguousPte = v_ptr32() self.u2 = unnamed() class CM_NAME_HASH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ConvKey = v_uint32() self.NextHash = v_ptr32() self.NameLength = v_uint16() self.Name = v_bytes(size=2) # FIXME Unknown Array Type class EX_PUSH_LOCK_WAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WakeEvent = KEVENT() self.Next = v_ptr32() self.ShareCount = v_uint32() self.Exclusive = v_uint8() class LPCP_MESSAGE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = LIST_ENTRY() self.SenderPort = v_ptr32() self.RepliedToThread = v_ptr32() self.PortContext = v_ptr32() self._pad0018 = v_bytes(size=4) self.Request = PORT_MESSAGE() class EX_QUEUE_WORKER_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.QueueDisabled = v_uint32() class PCI_FDO_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.List = SINGLE_LIST_ENTRY() self.ExtensionType = v_uint32() self.IrpDispatchTable = v_ptr32() self.DeviceState = v_uint8() self.TentativeNextState = v_uint8() self._pad0010 = v_bytes(size=2) self.SecondaryExtLock = KEVENT() self.PhysicalDeviceObject = v_ptr32() self.FunctionalDeviceObject = v_ptr32() self.AttachedDeviceObject = v_ptr32() self.ChildListLock = KEVENT() self.ChildPdoList = v_ptr32() self.BusRootFdoExtension = v_ptr32() self.ParentFdoExtension = v_ptr32() self.ChildBridgePdoList = v_ptr32() self.PciBusInterface = v_ptr32() self.MaxSubordinateBus = v_uint8() self._pad0054 = v_bytes(size=3) self.BusHandler = v_ptr32() self.BaseBus = v_uint8() self.Fake = v_uint8() self.ChildDelete = v_uint8() self.Scanned = v_uint8() self.ArbitersInitialized = v_uint8() self.BrokenVideoHackApplied = v_uint8() self.Hibernated = v_uint8() self._pad0060 = v_bytes(size=1) self.PowerState = PCI_POWER_STATE() self.SecondaryExtension = SINGLE_LIST_ENTRY() self.ChildWaitWakeCount = v_uint32() self.PreservedConfig = v_ptr32() self.Lock = PCI_LOCK() self.HotPlugParameters = unnamed() self._pad00bc = v_bytes(size=3) self.BusHackFlags = v_uint32() class PS_IMPERSONATION_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Token = v_ptr32() self.CopyOnOpen = v_uint8() self.EffectiveOnly = v_uint8() self._pad0008 = v_bytes(size=2) self.ImpersonationLevel = v_uint32() class DBGKD_WRITE_BREAKPOINT32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BreakPointAddress = v_uint32() self.BreakPointHandle = v_uint32() class IMAGE_NT_HEADERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER() class SINGLE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() class IO_STACK_LOCATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorFunction = v_uint8() self.MinorFunction = v_uint8() self.Flags = v_uint8() self.Control = v_uint8() self.Parameters = unnamed() self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.CompletionRoutine = v_ptr32() self.Context = v_ptr32() class PCI_PDO_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.ExtensionType = v_uint32() self.IrpDispatchTable = v_ptr32() self.DeviceState = v_uint8() self.TentativeNextState = v_uint8() self._pad0010 = v_bytes(size=2) self.SecondaryExtLock = KEVENT() self.Slot = PCI_SLOT_NUMBER() self.PhysicalDeviceObject = v_ptr32() self.ParentFdoExtension = v_ptr32() self.SecondaryExtension = SINGLE_LIST_ENTRY() self.BusInterfaceReferenceCount = v_uint32() self.AgpInterfaceReferenceCount = v_uint32() self.VendorId = v_uint16() self.DeviceId = v_uint16() self.SubsystemVendorId = v_uint16() self.SubsystemId = v_uint16() self.RevisionId = v_uint8() self.ProgIf = v_uint8() self.SubClass = v_uint8() self.BaseClass = v_uint8() self.AdditionalResourceCount = v_uint8() self.AdjustedInterruptLine = v_uint8() self.InterruptPin = v_uint8() self.RawInterruptLine = v_uint8() self.CapabilitiesPtr = v_uint8() self.SavedLatencyTimer = v_uint8() self.SavedCacheLineSize = v_uint8() self.HeaderType = v_uint8() self.NotPresent = v_uint8() self.ReportedMissing = v_uint8() self.ExpectedWritebackFailure = v_uint8() self.NoTouchPmeEnable = v_uint8() self.LegacyDriver = v_uint8() self.UpdateHardware = v_uint8() self.MovedDevice = v_uint8() self.DisablePowerDown = v_uint8() self.NeedsHotPlugConfiguration = v_uint8() self.SwitchedIDEToNativeMode = v_uint8() self.BIOSAllowsIDESwitchToNativeMode = v_uint8() self.IoSpaceUnderNativeIdeControl = v_uint8() self.OnDebugPath = v_uint8() self._pad005c = v_bytes(size=3) self.PowerState = PCI_POWER_STATE() self.Dependent = PCI_HEADER_TYPE_DEPENDENT() self.HackFlags = v_uint64() self.Resources = v_ptr32() self.BridgeFdoExtension = v_ptr32() self.NextBridge = v_ptr32() self.NextHashEntry = v_ptr32() self.Lock = PCI_LOCK() self.PowerCapabilities = PCI_PMC() self.TargetAgpCapabilityId = v_uint8() self._pad00c4 = v_bytes(size=1) self.CommandEnables = v_uint16() self.InitialCommand = v_uint16() class KNODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ProcessorMask = v_uint32() self.Color = v_uint32() self.MmShiftedColor = v_uint32() self.FreeCount = v_bytes(size=8) # FIXME Unknown Array Type self._pad0018 = v_bytes(size=4) self.DeadStackList = SLIST_HEADER() self.PfnDereferenceSListHead = SLIST_HEADER() self.PfnDeferredList = v_ptr32() self.Seed = v_uint8() self.Flags = flags() class SYSTEM_POWER_CAPABILITIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PowerButtonPresent = v_uint8() self.SleepButtonPresent = v_uint8() self.LidPresent = v_uint8() self.SystemS1 = v_uint8() self.SystemS2 = v_uint8() self.SystemS3 = v_uint8() self.SystemS4 = v_uint8() self.SystemS5 = v_uint8() self.HiberFilePresent = v_uint8() self.FullWake = v_uint8() self.VideoDimPresent = v_uint8() self.ApmPresent = v_uint8() self.UpsPresent = v_uint8() self.ThermalControl = v_uint8() self.ProcessorThrottle = v_uint8() self.ProcessorMinThrottle = v_uint8() self.ProcessorMaxThrottle = v_uint8() self.spare2 = v_bytes(size=4) # FIXME Unknown Array Type self.DiskSpinDown = v_uint8() self.spare3 = v_bytes(size=8) # FIXME Unknown Array Type self.SystemBatteriesPresent = v_uint8() self.BatteriesAreShortTerm = v_uint8() self.BatteryScale = v_uint8() self.AcOnLineWake = v_uint32() self.SoftLidWake = v_uint32() self.RtcWake = v_uint32() self.MinDeviceWakeState = v_uint32() self.DefaultLowLatencyWake = v_uint32() class DBGKD_SET_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFlags = v_uint32() class MMEXTEND_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CommittedSize = v_uint64() self.ReferenceCount = v_uint32() class RTL_USER_PROCESS_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MaximumLength = v_uint32() self.Length = v_uint32() self.Flags = v_uint32() self.DebugFlags = v_uint32() self.ConsoleHandle = v_ptr32() self.ConsoleFlags = v_uint32() self.StandardInput = v_ptr32() self.StandardOutput = v_ptr32() self.StandardError = v_ptr32() self.CurrentDirectory = CURDIR() self.DllPath = UNICODE_STRING() self.ImagePathName = UNICODE_STRING() self.CommandLine = UNICODE_STRING() self.Environment = v_ptr32() self.StartingX = v_uint32() self.StartingY = v_uint32() self.CountX = v_uint32() self.CountY = v_uint32() self.CountCharsX = v_uint32() self.CountCharsY = v_uint32() self.FillAttribute = v_uint32() self.WindowFlags = v_uint32() self.ShowWindowFlags = v_uint32() self.WindowTitle = UNICODE_STRING() self.DesktopInfo = UNICODE_STRING() self.ShellInfo = UNICODE_STRING() self.RuntimeData = UNICODE_STRING() self.CurrentDirectores = UNICODE_STRING() class u(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.KeyNode = CM_KEY_NODE() class IO_RESOURCE_REQUIREMENTS_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.SlotNumber = v_uint32() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type self.AlternativeLists = v_uint32() self.List = v_uint32() class POWER_CHANNEL_SUMMARY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.TotalCount = v_uint32() self.D0Count = v_uint32() self.NotifyList = LIST_ENTRY()
Python
# Version: 5.1 # Architecture: i386 import vstruct from vstruct.primitives import * DEVICE_RELATION_TYPE = v_enum() DEVICE_RELATION_TYPE.BusRelations = 0 DEVICE_RELATION_TYPE.EjectionRelations = 1 DEVICE_RELATION_TYPE.PowerRelations = 2 DEVICE_RELATION_TYPE.RemovalRelations = 3 DEVICE_RELATION_TYPE.TargetDeviceRelation = 4 DEVICE_RELATION_TYPE.SingleBusRelations = 5 IO_ALLOCATION_ACTION = v_enum() IO_ALLOCATION_ACTION.KeepObject = 0 IO_ALLOCATION_ACTION.DeallocateObject = 1 IO_ALLOCATION_ACTION.DeallocateObjectKeepRegisters = 2 BUS_QUERY_ID_TYPE = v_enum() BUS_QUERY_ID_TYPE.BusQueryDeviceID = 0 BUS_QUERY_ID_TYPE.BusQueryHardwareIDs = 1 BUS_QUERY_ID_TYPE.BusQueryCompatibleIDs = 2 BUS_QUERY_ID_TYPE.BusQueryInstanceID = 3 BUS_QUERY_ID_TYPE.BusQueryDeviceSerialNumber = 4 DEVICE_POWER_STATE = v_enum() DEVICE_POWER_STATE.PowerDeviceUnspecified = 0 DEVICE_POWER_STATE.PowerDeviceD0 = 1 DEVICE_POWER_STATE.PowerDeviceD1 = 2 DEVICE_POWER_STATE.PowerDeviceD2 = 3 DEVICE_POWER_STATE.PowerDeviceD3 = 4 DEVICE_POWER_STATE.PowerDeviceMaximum = 5 FSINFOCLASS = v_enum() FSINFOCLASS.FileFsVolumeInformation = 0 FSINFOCLASS.FileFsLabelInformation = 1 FSINFOCLASS.FileFsSizeInformation = 2 FSINFOCLASS.FileFsDeviceInformation = 3 FSINFOCLASS.FileFsAttributeInformation = 4 FSINFOCLASS.FileFsControlInformation = 5 FSINFOCLASS.FileFsFullSizeInformation = 6 FSINFOCLASS.FileFsObjectIdInformation = 7 FSINFOCLASS.FileFsDriverPathInformation = 8 FSINFOCLASS.FileFsMaximumInformation = 9 GDIObjType = v_enum() GDIObjType.GDIObjType_DEF_TYPE = 0 GDIObjType.GDIObjType_DC_TYPE = 1 GDIObjType.GDIObjType_UNUSED1_TYPE = 2 GDIObjType.GDIObjType_UNUSED2_TYPE = 3 GDIObjType.GDIObjType_RGN_TYPE = 4 GDIObjType.GDIObjType_SURF_TYPE = 5 GDIObjType.GDIObjType_CLIENTOBJ_TYPE = 6 GDIObjType.GDIObjType_PATH_TYPE = 7 GDIObjType.GDIObjType_PAL_TYPE = 8 GDIObjType.GDIObjType_ICMLCS_TYPE = 9 GDIObjType.GDIObjType_LFONT_TYPE = 10 GDIObjType.GDIObjType_RFONT_TYPE = 11 GDIObjType.GDIObjType_PFE_TYPE = 12 GDIObjType.GDIObjType_PFT_TYPE = 13 GDIObjType.GDIObjType_ICMCXF_TYPE = 14 GDIObjType.GDIObjType_SPRITE_TYPE = 15 GDIObjType.GDIObjType_BRUSH_TYPE = 16 GDIObjType.GDIObjType_UMPD_TYPE = 17 GDIObjType.GDIObjType_UNUSED4_TYPE = 18 GDIObjType.GDIObjType_SPACE_TYPE = 19 GDIObjType.GDIObjType_UNUSED5_TYPE = 20 GDIObjType.GDIObjType_META_TYPE = 21 GDIObjType.GDIObjType_EFSTATE_TYPE = 22 GDIObjType.GDIObjType_BMFD_TYPE = 23 GDIObjType.GDIObjType_VTFD_TYPE = 24 GDIObjType.GDIObjType_TTFD_TYPE = 25 GDIObjType.GDIObjType_RC_TYPE = 26 GDIObjType.GDIObjType_TEMP_TYPE = 27 GDIObjType.GDIObjType_DRVOBJ_TYPE = 28 GDIObjType.GDIObjType_DCIOBJ_TYPE = 29 GDIObjType.GDIObjType_SPOOL_TYPE = 30 GDIObjType.GDIObjType_MAX_TYPE = 31 GDIObjType.GDIObjTypeTotal = 32 POOL_TYPE = v_enum() POOL_TYPE.NonPagedPool = 0 POOL_TYPE.PagedPool = 1 POOL_TYPE.NonPagedPoolMustSucceed = 2 POOL_TYPE.DontUseThisType = 3 POOL_TYPE.NonPagedPoolCacheAligned = 4 POOL_TYPE.PagedPoolCacheAligned = 5 POOL_TYPE.NonPagedPoolCacheAlignedMustS = 6 POOL_TYPE.MaxPoolType = 7 POOL_TYPE.NonPagedPoolSession = 8 POOL_TYPE.PagedPoolSession = 9 POOL_TYPE.NonPagedPoolMustSucceedSession = 10 POOL_TYPE.DontUseThisTypeSession = 11 POOL_TYPE.NonPagedPoolCacheAlignedSession = 12 POOL_TYPE.PagedPoolCacheAlignedSession = 13 POOL_TYPE.NonPagedPoolCacheAlignedMustSSession = 14 MODE = v_enum() MODE.KernelMode = 0 MODE.UserMode = 1 MODE.MaximumMode = 2 OB_OPEN_REASON = v_enum() OB_OPEN_REASON.ObCreateHandle = 0 OB_OPEN_REASON.ObOpenHandle = 1 OB_OPEN_REASON.ObDuplicateHandle = 2 OB_OPEN_REASON.ObInheritHandle = 3 OB_OPEN_REASON.ObMaxOpenReason = 4 DEVICE_TEXT_TYPE = v_enum() DEVICE_TEXT_TYPE.DeviceTextDescription = 0 DEVICE_TEXT_TYPE.DeviceTextLocationInformation = 1 POWER_STATE_TYPE = v_enum() POWER_STATE_TYPE.SystemPowerState = 0 POWER_STATE_TYPE.DevicePowerState = 1 FILE_INFORMATION_CLASS = v_enum() FILE_INFORMATION_CLASS.FileDirectoryInformation = 0 FILE_INFORMATION_CLASS.FileFullDirectoryInformation = 1 FILE_INFORMATION_CLASS.FileBothDirectoryInformation = 2 FILE_INFORMATION_CLASS.FileBasicInformation = 3 FILE_INFORMATION_CLASS.FileStandardInformation = 4 FILE_INFORMATION_CLASS.FileInternalInformation = 5 FILE_INFORMATION_CLASS.FileEaInformation = 6 FILE_INFORMATION_CLASS.FileAccessInformation = 7 FILE_INFORMATION_CLASS.FileNameInformation = 8 FILE_INFORMATION_CLASS.FileRenameInformation = 9 FILE_INFORMATION_CLASS.FileLinkInformation = 10 FILE_INFORMATION_CLASS.FileNamesInformation = 11 FILE_INFORMATION_CLASS.FileDispositionInformation = 12 FILE_INFORMATION_CLASS.FilePositionInformation = 13 FILE_INFORMATION_CLASS.FileFullEaInformation = 14 FILE_INFORMATION_CLASS.FileModeInformation = 15 FILE_INFORMATION_CLASS.FileAlignmentInformation = 16 FILE_INFORMATION_CLASS.FileAllInformation = 17 FILE_INFORMATION_CLASS.FileAllocationInformation = 18 FILE_INFORMATION_CLASS.FileEndOfFileInformation = 19 FILE_INFORMATION_CLASS.FileAlternateNameInformation = 20 FILE_INFORMATION_CLASS.FileStreamInformation = 21 FILE_INFORMATION_CLASS.FilePipeInformation = 22 FILE_INFORMATION_CLASS.FilePipeLocalInformation = 23 FILE_INFORMATION_CLASS.FilePipeRemoteInformation = 24 FILE_INFORMATION_CLASS.FileMailslotQueryInformation = 25 FILE_INFORMATION_CLASS.FileMailslotSetInformation = 26 FILE_INFORMATION_CLASS.FileCompressionInformation = 27 FILE_INFORMATION_CLASS.FileObjectIdInformation = 28 FILE_INFORMATION_CLASS.FileCompletionInformation = 29 FILE_INFORMATION_CLASS.FileMoveClusterInformation = 30 FILE_INFORMATION_CLASS.FileQuotaInformation = 31 FILE_INFORMATION_CLASS.FileReparsePointInformation = 32 FILE_INFORMATION_CLASS.FileNetworkOpenInformation = 33 FILE_INFORMATION_CLASS.FileAttributeTagInformation = 34 FILE_INFORMATION_CLASS.FileTrackingInformation = 35 FILE_INFORMATION_CLASS.FileIdBothDirectoryInformation = 36 FILE_INFORMATION_CLASS.FileIdFullDirectoryInformation = 37 FILE_INFORMATION_CLASS.FileValidDataLengthInformation = 38 FILE_INFORMATION_CLASS.FileShortNameInformation = 39 FILE_INFORMATION_CLASS.FileMaximumInformation = 40 GDILoObjType = v_enum() GDILoObjType.GDILoObjType_LO_BRUSH_TYPE = 0 GDILoObjType.GDILoObjType_LO_DC_TYPE = 1 GDILoObjType.GDILoObjType_LO_BITMAP_TYPE = 2 GDILoObjType.GDILoObjType_LO_PALETTE_TYPE = 3 GDILoObjType.GDILoObjType_LO_FONT_TYPE = 4 GDILoObjType.GDILoObjType_LO_REGION_TYPE = 5 GDILoObjType.GDILoObjType_LO_ICMLCS_TYPE = 6 GDILoObjType.GDILoObjType_LO_CLIENTOBJ_TYPE = 7 GDILoObjType.GDILoObjType_LO_ALTDC_TYPE = 8 GDILoObjType.GDILoObjType_LO_PEN_TYPE = 9 GDILoObjType.GDILoObjType_LO_EXTPEN_TYPE = 10 GDILoObjType.GDILoObjType_LO_DIBSECTION_TYPE = 11 GDILoObjType.GDILoObjType_LO_METAFILE16_TYPE = 12 GDILoObjType.GDILoObjType_LO_METAFILE_TYPE = 13 GDILoObjType.GDILoObjType_LO_METADC16_TYPE = 14 SECURITY_OPERATION_CODE = v_enum() SECURITY_OPERATION_CODE.SetSecurityDescriptor = 0 SECURITY_OPERATION_CODE.QuerySecurityDescriptor = 1 SECURITY_OPERATION_CODE.DeleteSecurityDescriptor = 2 SECURITY_OPERATION_CODE.AssignSecurityDescriptor = 3 SECURITY_IMPERSONATION_LEVEL = v_enum() SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous = 0 SECURITY_IMPERSONATION_LEVEL.SecurityIdentification = 1 SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation = 2 SECURITY_IMPERSONATION_LEVEL.SecurityDelegation = 3 DEVICE_USAGE_NOTIFICATION_TYPE = v_enum() DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeUndefined = 0 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypePaging = 1 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeHibernation = 2 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeDumpFile = 3 INTERFACE_TYPE = v_enum() INTERFACE_TYPE.InterfaceTypeUndefined = 0 INTERFACE_TYPE.Internal = 1 INTERFACE_TYPE.Isa = 2 INTERFACE_TYPE.Eisa = 3 INTERFACE_TYPE.MicroChannel = 4 INTERFACE_TYPE.TurboChannel = 5 INTERFACE_TYPE.PCIBus = 6 INTERFACE_TYPE.VMEBus = 7 INTERFACE_TYPE.NuBus = 8 INTERFACE_TYPE.PCMCIABus = 9 INTERFACE_TYPE.CBus = 10 INTERFACE_TYPE.MPIBus = 11 INTERFACE_TYPE.MPSABus = 12 INTERFACE_TYPE.ProcessorInternal = 13 INTERFACE_TYPE.InternalPowerBus = 14 INTERFACE_TYPE.PNPISABus = 15 INTERFACE_TYPE.PNPBus = 16 INTERFACE_TYPE.MaximumInterfaceType = 17 MEMORY_TYPE = v_enum() MEMORY_TYPE.MemoryExceptionBlock = 0 MEMORY_TYPE.MemorySystemBlock = 1 MEMORY_TYPE.MemoryFree = 2 MEMORY_TYPE.MemoryBad = 3 MEMORY_TYPE.MemoryLoadedProgram = 4 MEMORY_TYPE.MemoryFirmwareTemporary = 5 MEMORY_TYPE.MemoryFirmwarePermanent = 6 MEMORY_TYPE.MemoryFreeContiguous = 7 MEMORY_TYPE.MemorySpecialMemory = 8 MEMORY_TYPE.MemoryMaximum = 9 ReplacesCorHdrNumericDefines = v_enum() ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY = 0 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED = 1 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY = 2 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED = 3 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA = 4 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR_V2 = 5 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR = 6 ReplacesCorHdrNumericDefines.COR_VERSION_MINOR = 7 ReplacesCorHdrNumericDefines.COR_DELETED_NAME_LENGTH = 8 ReplacesCorHdrNumericDefines.COR_VTABLEGAP_NAME_LENGTH = 9 ReplacesCorHdrNumericDefines.NATIVE_TYPE_MAX_CB = 10 ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 11 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_METHODRVA = 12 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_EHRVA = 13 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_BASICBLOCK = 14 ReplacesCorHdrNumericDefines.COR_VTABLE_32BIT = 15 ReplacesCorHdrNumericDefines.COR_VTABLE_64BIT = 16 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED = 17 ReplacesCorHdrNumericDefines.COR_VTABLE_CALL_MOST_DERIVED = 18 ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE = 19 ReplacesCorHdrNumericDefines.MAX_CLASS_NAME = 20 ReplacesCorHdrNumericDefines.MAX_PACKAGE_NAME = 21 SYSTEM_POWER_STATE = v_enum() SYSTEM_POWER_STATE.PowerSystemUnspecified = 0 SYSTEM_POWER_STATE.PowerSystemWorking = 1 SYSTEM_POWER_STATE.PowerSystemSleeping1 = 2 SYSTEM_POWER_STATE.PowerSystemSleeping2 = 3 SYSTEM_POWER_STATE.PowerSystemSleeping3 = 4 SYSTEM_POWER_STATE.PowerSystemHibernate = 5 SYSTEM_POWER_STATE.PowerSystemShutdown = 6 SYSTEM_POWER_STATE.PowerSystemMaximum = 7 MEMORY_CACHING_TYPE_ORIG = v_enum() MEMORY_CACHING_TYPE_ORIG.MmFrameBufferCached = 0 POWER_ACTION = v_enum() POWER_ACTION.PowerActionNone = 0 POWER_ACTION.PowerActionReserved = 1 POWER_ACTION.PowerActionSleep = 2 POWER_ACTION.PowerActionHibernate = 3 POWER_ACTION.PowerActionShutdown = 4 POWER_ACTION.PowerActionShutdownReset = 5 POWER_ACTION.PowerActionShutdownOff = 6 POWER_ACTION.PowerActionWarmEject = 7 class OBJECT_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.RootDirectory = v_ptr32() self.ObjectName = v_ptr32() self.Attributes = v_uint32() self.SecurityDescriptor = v_ptr32() self.SecurityQualityOfService = v_ptr32() class SECURITY_SUBJECT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientToken = v_ptr32() self.ImpersonationLevel = v_uint32() self.PrimaryToken = v_ptr32() self.ProcessAuditId = v_ptr32() class CM_FULL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.PartialResourceList = CM_PARTIAL_RESOURCE_LIST() class FAST_IO_DISPATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFastIoDispatch = v_uint32() self.FastIoCheckIfPossible = v_ptr32() self.FastIoRead = v_ptr32() self.FastIoWrite = v_ptr32() self.FastIoQueryBasicInfo = v_ptr32() self.FastIoQueryStandardInfo = v_ptr32() self.FastIoLock = v_ptr32() self.FastIoUnlockSingle = v_ptr32() self.FastIoUnlockAll = v_ptr32() self.FastIoUnlockAllByKey = v_ptr32() self.FastIoDeviceControl = v_ptr32() self.AcquireFileForNtCreateSection = v_ptr32() self.ReleaseFileForNtCreateSection = v_ptr32() self.FastIoDetachDevice = v_ptr32() self.FastIoQueryNetworkOpenInfo = v_ptr32() self.AcquireForModWrite = v_ptr32() self.MdlRead = v_ptr32() self.MdlReadComplete = v_ptr32() self.PrepareMdlWrite = v_ptr32() self.MdlWriteComplete = v_ptr32() self.FastIoReadCompressed = v_ptr32() self.FastIoWriteCompressed = v_ptr32() self.MdlReadCompleteCompressed = v_ptr32() self.MdlWriteCompleteCompressed = v_ptr32() self.FastIoQueryOpen = v_ptr32() self.ReleaseForModWrite = v_ptr32() self.AcquireForCcFlush = v_ptr32() self.ReleaseForCcFlush = v_ptr32() class ACCESS_STATE::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InitialPrivilegeSet = INITIAL_PRIVILEGE_SET() class LARGE_INTEGER::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class IMAGE_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Machine = v_uint16() self.NumberOfSections = v_uint16() self.TimeDateStamp = v_uint32() self.PointerToSymbolTable = v_uint32() self.NumberOfSymbols = v_uint32() self.SizeOfOptionalHeader = v_uint16() self.Characteristics = v_uint16() class IO_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Option = v_uint8() self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Spare1 = v_uint8() self.Flags = v_uint16() self.Spare2 = v_uint16() self.u = IO_RESOURCE_DESCRIPTOR::__unnamed() class EX_PUSH_LOCK_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locks = v_bytes(size=4) # FIXME Unknown Array Type class EX_PUSH_LOCK::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Waiting = v_uint32() class IMAGE_NT_HEADERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER() class IMAGE_OPTIONAL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint16() self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.BaseOfData = v_uint32() self.ImageBase = v_uint32() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint32() self.SizeOfStackCommit = v_uint32() self.SizeOfHeapReserve = v_uint32() self.SizeOfHeapCommit = v_uint32() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = v_uint32() class OWNER_ENTRY::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwnerCount = v_uint32() class ETHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class FAST_MUTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Owner = v_ptr32() self.Contention = v_uint32() self.Event = KEVENT() self.OldIrql = v_uint32() class VPB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Flags = v_uint16() self.VolumeLabelLength = v_uint16() self.DeviceObject = v_ptr32() self.RealDevice = v_ptr32() self.SerialNumber = v_uint32() self.ReferenceCount = v_uint32() self.VolumeLabel = v_bytes(size=64) # FIXME Unknown Array Type class IO_RESOURCE_DESCRIPTOR::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = IO_RESOURCE_DESCRIPTOR::__unnamed::__unnamed() class tagWin32AllocStats(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.dwMaxMem = v_uint32() self.dwCrtMem = v_uint32() self.dwMaxAlloc = v_uint32() self.dwCrtAlloc = v_uint32() self.pHead = v_ptr32() class KDEVICE_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceListHead = LIST_ENTRY() self.Lock = v_uint32() self.Busy = v_uint8() class ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.einfo = EINFO() self.ObjectOwner = OBJECTOWNER() self.FullUnique = v_uint16() self.Objt = v_uint8() self.Flags = v_uint8() self.pUser = v_ptr32() class IRP::__unnamed::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.CurrentStackLocation = v_ptr32() class CM_PARTIAL_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.PartialDescriptors = v_uint32() class IO_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityQos = v_ptr32() self.AccessState = v_ptr32() self.DesiredAccess = v_uint32() self.FullCreateOptions = v_uint32() class LUID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Luid = LUID() self.Attributes = v_uint32() class IRP::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceQueueEntry = KDEVICE_QUEUE_ENTRY() self.Thread = v_ptr32() self.AuxiliaryBuffer = v_ptr32() self.ListEntry = LIST_ENTRY() self.CurrentStackLocation = v_ptr32() self.OriginalFileObject = v_ptr32() class DEVICE_CAPABILITIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.DeviceD1 = v_uint32() self.Address = v_uint32() self.UINumber = v_uint32() self.DeviceState = v_uint32() self.SystemWake = v_uint32() self.DeviceWake = v_uint32() self.D1Latency = v_uint32() self.D2Latency = v_uint32() self.D3Latency = v_uint32() class INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.Context = v_ptr32() self.InterfaceReference = v_ptr32() self.InterfaceDereference = v_ptr32() class SLIST_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Alignment = v_uint64() class KTHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class IO_STACK_LOCATION::__unnamed::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ReplaceIfExists = v_uint8() self.AdvanceOnly = v_uint8() class IO_STATUS_BLOCK::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() class IMAGE_DATA_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.Size = v_uint32() class FILE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Vpb = v_ptr32() self.FsContext = v_ptr32() self.FsContext2 = v_ptr32() self.SectionObjectPointer = v_ptr32() self.PrivateCacheMap = v_ptr32() self.FinalStatus = v_uint32() self.RelatedFileObject = v_ptr32() self.LockOperation = v_uint8() self.DeletePending = v_uint8() self.ReadAccess = v_uint8() self.WriteAccess = v_uint8() self.DeleteAccess = v_uint8() self.SharedRead = v_uint8() self.SharedWrite = v_uint8() self.SharedDelete = v_uint8() self.Flags = v_uint32() self.FileName = UNICODE_STRING() self.CurrentByteOffset = LARGE_INTEGER() self.Waiters = v_uint32() self.Busy = v_uint32() self.LastLock = v_ptr32() self.Lock = KEVENT() self.Event = KEVENT() self.CompletionContext = v_ptr32() class ERESOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemResourcesList = LIST_ENTRY() self.OwnerTable = v_ptr32() self.ActiveCount = v_uint16() self.Flag = v_uint16() self.SharedWaiters = v_ptr32() self.ExclusiveWaiters = v_ptr32() self.OwnerThreads = v_ptr32() self.ContentionCount = v_uint32() self.NumberOfSharedWaiters = v_uint16() self.NumberOfExclusiveWaiters = v_uint16() self.Address = v_ptr32() self.SpinLock = v_uint32() class FILE_NETWORK_OPEN_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.FileAttributes = v_uint32() class GENERAL_LOOKASIDE::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LastAllocateMisses = v_uint32() class OBJECTOWNER_S(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = v_uint32() class OBJECT_HANDLE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HandleAttributes = v_uint32() self.GrantedAccess = v_uint32() class IRP::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Overlay = IRP::__unnamed::__unnamed() class INITIAL_PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class ULARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class GENERAL_LOOKASIDE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.Allocate = v_ptr32() self.Free = v_ptr32() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class EX_PUSH_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Waiting = v_uint32() class CM_PARTIAL_RESOURCE_DESCRIPTOR::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Generic = CM_PARTIAL_RESOURCE_DESCRIPTOR::__unnamed::__unnamed() class SECTION_OBJECT_POINTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSectionObject = v_ptr32() self.SharedCacheMap = v_ptr32() self.ImageSectionObject = v_ptr32() class DEVOBJ_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() class tagVSTATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.fl = v_uint32() self.bSystemStable = v_uint32() self.ulRandomSeed = v_uint32() self.ulFailureMask = v_uint32() self.ulDebugLevel = v_uint32() self.hsemPoolTracker = v_ptr32() self.lePoolTrackerHead = LIST_ENTRY() class EX_RUNDOWN_REF::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() class POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemState = v_uint32() class UNICODE_STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class GDIHandleBitFields(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Index = v_uint32() class ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OperationID = LUID() self.SecurityEvaluated = v_uint8() self.GenerateAudit = v_uint8() self.GenerateOnClose = v_uint8() self.PrivilegesAllocated = v_uint8() self.Flags = v_uint32() self.RemainingDesiredAccess = v_uint32() self.PreviouslyGrantedAccess = v_uint32() self.OriginalDesiredAccess = v_uint32() self.SubjectSecurityContext = SECURITY_SUBJECT_CONTEXT() self.SecurityDescriptor = v_ptr32() self.AuxData = v_ptr32() self.Privileges = ACCESS_STATE::__unnamed() self.AuditPrivileges = v_uint8() self._pad0064 = v_bytes(size=3) self.ObjectName = UNICODE_STRING() self.ObjectTypeName = UNICODE_STRING() class FILE_STANDARD_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.NumberOfLinks = v_uint32() self.DeletePending = v_uint8() self.Directory = v_uint8() class KAPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Spare0 = v_uint32() self.Thread = v_ptr32() self.ApcListEntry = LIST_ENTRY() self.KernelRoutine = v_ptr32() self.RundownRoutine = v_ptr32() self.NormalRoutine = v_ptr32() self.NormalContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.ApcStateIndex = v_uint8() self.ApcMode = v_uint8() self.Inserted = v_uint8() class WAIT_CONTEXT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitQueueEntry = KDEVICE_QUEUE_ENTRY() self.DeviceRoutine = v_ptr32() self.DeviceContext = v_ptr32() self.NumberOfMapRegisters = v_uint32() self.DeviceObject = v_ptr32() self.CurrentIrp = v_ptr32() self.BufferChainingDpc = v_ptr32() class EX_PUSH_LOCK::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Waiting = v_uint32() class MDL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Size = v_uint16() self.MdlFlags = v_uint16() self.Process = v_ptr32() self.MappedSystemVa = v_ptr32() self.StartVa = v_ptr32() self.ByteCount = v_uint32() self.ByteOffset = v_uint32() class EX_RUNDOWN_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() class W32THREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.pEThread = v_ptr32() self.RefCount = v_uint32() self.ptlW32 = v_ptr32() self.pgdiDcattr = v_ptr32() self.pgdiBrushAttr = v_ptr32() self.pUMPDObjs = v_ptr32() self.pUMPDHeap = v_ptr32() self.dwEngAcquireCount = v_uint32() self.pSemTable = v_ptr32() self.pUMPDObj = v_ptr32() class KDPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Number = v_uint8() self.Importance = v_uint8() self.DpcListEntry = LIST_ENTRY() self.DeferredRoutine = v_ptr32() self.DeferredContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.Lock = v_ptr32() class OWNER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwnerThread = v_uint32() self.OwnerCount = v_uint32() class KEVENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class KSEMAPHORE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.Limit = v_uint32() class PAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = FAST_MUTEX() class OBJECT_TYPE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mutex = ERESOURCE() self.TypeList = LIST_ENTRY() self.Name = UNICODE_STRING() self.DefaultObject = v_ptr32() self.Index = v_uint32() self.TotalNumberOfObjects = v_uint32() self.TotalNumberOfHandles = v_uint32() self.HighWaterNumberOfObjects = v_uint32() self.HighWaterNumberOfHandles = v_uint32() self.TypeInfo = OBJECT_TYPE_INITIALIZER() self.Key = v_uint32() self.ObjectLocks = v_uint32() class DEVICE_OBJECT::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() class DISPATCHER_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.Absolute = v_uint8() self.Size = v_uint8() self.Inserted = v_uint8() self.SignalState = v_uint32() self.WaitListHead = LIST_ENTRY() class IRP::__unnamed::__unnamed::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CurrentStackLocation = v_ptr32() class HOBJ(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.unused = v_uint32() class IO_TIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class OBJECT_TYPE_INITIALIZER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.UseDefaultObject = v_uint8() self.CaseInsensitive = v_uint8() self.InvalidAttributes = v_uint32() self.GenericMapping = GENERIC_MAPPING() self.ValidAccessMask = v_uint32() self.SecurityRequired = v_uint8() self.MaintainHandleCount = v_uint8() self.MaintainTypeList = v_uint8() self._pad0020 = v_bytes(size=1) self.PoolType = v_uint32() self.DefaultPagedPoolCharge = v_uint32() self.DefaultNonPagedPoolCharge = v_uint32() self.DumpProcedure = v_ptr32() self.OpenProcedure = v_ptr32() self.CloseProcedure = v_ptr32() self.DeleteProcedure = v_ptr32() self.ParseProcedure = v_ptr32() self.SecurityProcedure = v_ptr32() self.QueryNameProcedure = v_ptr32() self.OkayToCloseProcedure = v_ptr32() class SCSI_REQUEST_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class IO_STACK_LOCATION::__unnamed::__unnamed::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ReplaceIfExists = v_uint8() self.AdvanceOnly = v_uint8() class FILE_BASIC_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.FileAttributes = v_uint32() class DEVICE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.ReferenceCount = v_uint32() self.DriverObject = v_ptr32() self.NextDevice = v_ptr32() self.AttachedDevice = v_ptr32() self.CurrentIrp = v_ptr32() self.Timer = v_ptr32() self.Flags = v_uint32() self.Characteristics = v_uint32() self.Vpb = v_ptr32() self.DeviceExtension = v_ptr32() self.DeviceType = v_uint32() self.StackSize = v_uint8() self._pad0034 = v_bytes(size=3) self.Queue = DEVICE_OBJECT::__unnamed() self.AlignmentRequirement = v_uint32() self.DeviceQueue = KDEVICE_QUEUE() self.Dpc = KDPC() self.ActiveThreadCount = v_uint32() self.SecurityDescriptor = v_ptr32() self.DeviceLock = KEVENT() self.SectorSize = v_uint16() self.Spare1 = v_uint16() self.DeviceObjectExtension = v_ptr32() self.Reserved = v_ptr32() class LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_ptr32() self.Blink = v_ptr32() class EINFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.pobj = v_ptr32() class SECURITY_QUALITY_OF_SERVICE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.ImpersonationLevel = v_uint32() self.ContextTrackingMode = v_uint8() self.EffectiveOnly = v_uint8() class COMPRESSED_DATA_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CompressionFormatAndEngine = v_uint16() self.CompressionUnitShift = v_uint8() self.ChunkShift = v_uint8() self.ClusterShift = v_uint8() self.Reserved = v_uint8() self.NumberOfChunks = v_uint16() self.CompressedChunkSizes = v_bytes(size=4) # FIXME Unknown Array Type class BASEOBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.hHmgr = v_ptr32() self.ulShareCount = v_uint32() self.cExclusiveLock = v_uint16() self.BaseFlags = v_uint16() self.Tid = v_ptr32() class HSEMAPHORE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.unused = v_uint32() class LUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class LARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class tagPOOLRECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExtraData = v_ptr32() self.size = v_uint32() self.trace = v_bytes(size=24) # FIXME Unknown Array Type class GUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data1 = v_uint32() self.Data2 = v_uint16() self.Data3 = v_uint16() self.Data4 = v_bytes(size=8) # FIXME Unknown Array Type class OBJECT_DUMP_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Stream = v_ptr32() self.Detail = v_uint32() class NPAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = v_uint32() class ULARGE_INTEGER::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class OBJECTOWNER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Share = OBJECTOWNER_S() class tagWin32PoolHead(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.size = v_uint32() self.pPrev = v_ptr32() self.pNext = v_ptr32() self.pTrace = v_ptr32() class TL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.next = v_ptr32() self.pobj = v_ptr32() self.pfnFree = v_ptr32() class IO_STACK_LOCATION::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Argument1 = v_ptr32() self.Argument2 = v_ptr32() self.Argument3 = v_ptr32() self.Argument4 = v_ptr32() class CM_PARTIAL_RESOURCE_DESCRIPTOR::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSize = v_uint32() self.Reserved1 = v_uint32() self.Reserved2 = v_uint32() class ERESOURCE::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_ptr32() class IO_STACK_LOCATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorFunction = v_uint8() self.MinorFunction = v_uint8() self.Flags = v_uint8() self.Control = v_uint8() self.Parameters = IO_STACK_LOCATION::__unnamed() self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.CompletionRoutine = v_ptr32() self.Context = v_ptr32() class IO_RESOURCE_DESCRIPTOR::__unnamed::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Priority = v_uint32() self.Reserved1 = v_uint32() self.Reserved2 = v_uint32() class STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class GENERIC_MAPPING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GenericRead = v_uint32() self.GenericWrite = v_uint32() self.GenericExecute = v_uint32() self.GenericAll = v_uint32() class IRP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.MdlAddress = v_ptr32() self.Flags = v_uint32() self.AssociatedIrp = IRP::__unnamed() self.ThreadListEntry = LIST_ENTRY() self.IoStatus = IO_STATUS_BLOCK() self.RequestorMode = v_uint8() self.PendingReturned = v_uint8() self.StackCount = v_uint8() self.CurrentLocation = v_uint8() self.Cancel = v_uint8() self.CancelIrql = v_uint8() self.ApcEnvironment = v_uint8() self.AllocationFlags = v_uint8() self.UserIosb = v_ptr32() self.UserEvent = v_ptr32() self.Overlay = IRP::__unnamed() self.CancelRoutine = v_ptr32() self.UserBuffer = v_ptr32() self.Tail = IRP::__unnamed() class OBJECT_NAME_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = UNICODE_STRING() class IO_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.Descriptors = v_uint32() class DRIVER_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Flags = v_uint32() self.DriverStart = v_ptr32() self.DriverSize = v_uint32() self.DriverSection = v_ptr32() self.DriverExtension = v_ptr32() self.DriverName = UNICODE_STRING() self.HardwareDatabase = v_ptr32() self.FastIoDispatch = v_ptr32() self.DriverInit = v_ptr32() self.DriverStartIo = v_ptr32() self.DriverUnload = v_ptr32() self.MajorFunction = v_bytes(size=112) # FIXME Unknown Array Type class IO_STATUS_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self.Information = v_uint32() class PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class CM_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = v_uint32() class EPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class LIST_ENTRY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint32() self.Blink = v_uint32() class tagVERIFIERTRACKHDR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.list = LIST_ENTRY() self.ulSize = v_uint32() self.ulTag = v_uint32() class SINGLE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() class POWER_SEQUENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SequenceD1 = v_uint32() self.SequenceD2 = v_uint32() self.SequenceD3 = v_uint32() class IO_COMPLETION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = v_ptr32() self.Key = v_ptr32() class DRIVER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DriverObject = v_ptr32() self.AddDevice = v_ptr32() self.Count = v_uint32() self.ServiceKeyName = UNICODE_STRING() class IO_STACK_LOCATION::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Create = IO_STACK_LOCATION::__unnamed::__unnamed() class KDEVICE_QUEUE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceListEntry = LIST_ENTRY() self.SortKey = v_uint32() self.Inserted = v_uint8() class LIST_ENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint64() self.Blink = v_uint64() class IO_RESOURCE_REQUIREMENTS_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.SlotNumber = v_uint32() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type self.AlternativeLists = v_uint32() self.List = v_uint32() class SLIST_HEADER::__unnamed(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = SINGLE_LIST_ENTRY() self.Depth = v_uint16() self.Sequence = v_uint16() class CM_PARTIAL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Flags = v_uint16() self.u = CM_PARTIAL_RESOURCE_DESCRIPTOR::__unnamed()
Python
# Version: 6.1 # Architecture: i386 import vstruct from vstruct.primitives import * KPROCESS_STATE = v_enum() KPROCESS_STATE.ProcessInMemory = 0 KPROCESS_STATE.ProcessOutOfMemory = 1 KPROCESS_STATE.ProcessInTransition = 2 KPROCESS_STATE.ProcessOutTransition = 3 KPROCESS_STATE.ProcessInSwap = 4 KPROCESS_STATE.ProcessOutSwap = 5 KPROCESS_STATE.ProcessAllSwapStates = 6 WHEA_ERROR_SEVERITY = v_enum() WHEA_ERROR_SEVERITY.WheaErrSevRecoverable = 0 WHEA_ERROR_SEVERITY.WheaErrSevFatal = 1 WHEA_ERROR_SEVERITY.WheaErrSevCorrected = 2 WHEA_ERROR_SEVERITY.WheaErrSevInformational = 3 REG_NOTIFY_CLASS = v_enum() REG_NOTIFY_CLASS.RegNtDeleteKey = 0 REG_NOTIFY_CLASS.RegNtPreDeleteKey = 1 REG_NOTIFY_CLASS.RegNtSetValueKey = 2 REG_NOTIFY_CLASS.RegNtPreSetValueKey = 3 REG_NOTIFY_CLASS.RegNtDeleteValueKey = 4 REG_NOTIFY_CLASS.RegNtPreDeleteValueKey = 5 REG_NOTIFY_CLASS.RegNtSetInformationKey = 6 REG_NOTIFY_CLASS.RegNtPreSetInformationKey = 7 REG_NOTIFY_CLASS.RegNtRenameKey = 8 REG_NOTIFY_CLASS.RegNtPreRenameKey = 9 REG_NOTIFY_CLASS.RegNtEnumerateKey = 10 REG_NOTIFY_CLASS.RegNtPreEnumerateKey = 11 REG_NOTIFY_CLASS.RegNtEnumerateValueKey = 12 REG_NOTIFY_CLASS.RegNtPreEnumerateValueKey = 13 REG_NOTIFY_CLASS.RegNtQueryKey = 14 REG_NOTIFY_CLASS.RegNtPreQueryKey = 15 REG_NOTIFY_CLASS.RegNtQueryValueKey = 16 REG_NOTIFY_CLASS.RegNtPreQueryValueKey = 17 REG_NOTIFY_CLASS.RegNtQueryMultipleValueKey = 18 REG_NOTIFY_CLASS.RegNtPreQueryMultipleValueKey = 19 REG_NOTIFY_CLASS.RegNtPreCreateKey = 20 REG_NOTIFY_CLASS.RegNtPostCreateKey = 21 REG_NOTIFY_CLASS.RegNtPreOpenKey = 22 REG_NOTIFY_CLASS.RegNtPostOpenKey = 23 REG_NOTIFY_CLASS.RegNtKeyHandleClose = 24 REG_NOTIFY_CLASS.RegNtPreKeyHandleClose = 25 REG_NOTIFY_CLASS.RegNtPostDeleteKey = 26 REG_NOTIFY_CLASS.RegNtPostSetValueKey = 27 REG_NOTIFY_CLASS.RegNtPostDeleteValueKey = 28 REG_NOTIFY_CLASS.RegNtPostSetInformationKey = 29 REG_NOTIFY_CLASS.RegNtPostRenameKey = 30 REG_NOTIFY_CLASS.RegNtPostEnumerateKey = 31 REG_NOTIFY_CLASS.RegNtPostEnumerateValueKey = 32 REG_NOTIFY_CLASS.RegNtPostQueryKey = 33 REG_NOTIFY_CLASS.RegNtPostQueryValueKey = 34 REG_NOTIFY_CLASS.RegNtPostQueryMultipleValueKey = 35 REG_NOTIFY_CLASS.RegNtPostKeyHandleClose = 36 REG_NOTIFY_CLASS.RegNtPreCreateKeyEx = 37 REG_NOTIFY_CLASS.RegNtPostCreateKeyEx = 38 REG_NOTIFY_CLASS.RegNtPreOpenKeyEx = 39 REG_NOTIFY_CLASS.RegNtPostOpenKeyEx = 40 REG_NOTIFY_CLASS.RegNtPreFlushKey = 41 REG_NOTIFY_CLASS.RegNtPostFlushKey = 42 REG_NOTIFY_CLASS.RegNtPreLoadKey = 43 REG_NOTIFY_CLASS.RegNtPostLoadKey = 44 REG_NOTIFY_CLASS.RegNtPreUnLoadKey = 45 REG_NOTIFY_CLASS.RegNtPostUnLoadKey = 46 REG_NOTIFY_CLASS.RegNtPreQueryKeySecurity = 47 REG_NOTIFY_CLASS.RegNtPostQueryKeySecurity = 48 REG_NOTIFY_CLASS.RegNtPreSetKeySecurity = 49 REG_NOTIFY_CLASS.RegNtPostSetKeySecurity = 50 REG_NOTIFY_CLASS.RegNtCallbackObjectContextCleanup = 51 REG_NOTIFY_CLASS.RegNtPreRestoreKey = 52 REG_NOTIFY_CLASS.RegNtPostRestoreKey = 53 REG_NOTIFY_CLASS.RegNtPreSaveKey = 54 REG_NOTIFY_CLASS.RegNtPostSaveKey = 55 REG_NOTIFY_CLASS.RegNtPreReplaceKey = 56 REG_NOTIFY_CLASS.RegNtPostReplaceKey = 57 REG_NOTIFY_CLASS.MaxRegNtNotifyClass = 58 DEVICE_RELATION_TYPE = v_enum() DEVICE_RELATION_TYPE.BusRelations = 0 DEVICE_RELATION_TYPE.EjectionRelations = 1 DEVICE_RELATION_TYPE.PowerRelations = 2 DEVICE_RELATION_TYPE.RemovalRelations = 3 DEVICE_RELATION_TYPE.TargetDeviceRelation = 4 DEVICE_RELATION_TYPE.SingleBusRelations = 5 DEVICE_RELATION_TYPE.TransportRelations = 6 FILE_INFORMATION_CLASS = v_enum() FILE_INFORMATION_CLASS.FileDirectoryInformation = 0 FILE_INFORMATION_CLASS.FileFullDirectoryInformation = 1 FILE_INFORMATION_CLASS.FileBothDirectoryInformation = 2 FILE_INFORMATION_CLASS.FileBasicInformation = 3 FILE_INFORMATION_CLASS.FileStandardInformation = 4 FILE_INFORMATION_CLASS.FileInternalInformation = 5 FILE_INFORMATION_CLASS.FileEaInformation = 6 FILE_INFORMATION_CLASS.FileAccessInformation = 7 FILE_INFORMATION_CLASS.FileNameInformation = 8 FILE_INFORMATION_CLASS.FileRenameInformation = 9 FILE_INFORMATION_CLASS.FileLinkInformation = 10 FILE_INFORMATION_CLASS.FileNamesInformation = 11 FILE_INFORMATION_CLASS.FileDispositionInformation = 12 FILE_INFORMATION_CLASS.FilePositionInformation = 13 FILE_INFORMATION_CLASS.FileFullEaInformation = 14 FILE_INFORMATION_CLASS.FileModeInformation = 15 FILE_INFORMATION_CLASS.FileAlignmentInformation = 16 FILE_INFORMATION_CLASS.FileAllInformation = 17 FILE_INFORMATION_CLASS.FileAllocationInformation = 18 FILE_INFORMATION_CLASS.FileEndOfFileInformation = 19 FILE_INFORMATION_CLASS.FileAlternateNameInformation = 20 FILE_INFORMATION_CLASS.FileStreamInformation = 21 FILE_INFORMATION_CLASS.FilePipeInformation = 22 FILE_INFORMATION_CLASS.FilePipeLocalInformation = 23 FILE_INFORMATION_CLASS.FilePipeRemoteInformation = 24 FILE_INFORMATION_CLASS.FileMailslotQueryInformation = 25 FILE_INFORMATION_CLASS.FileMailslotSetInformation = 26 FILE_INFORMATION_CLASS.FileCompressionInformation = 27 FILE_INFORMATION_CLASS.FileObjectIdInformation = 28 FILE_INFORMATION_CLASS.FileCompletionInformation = 29 FILE_INFORMATION_CLASS.FileMoveClusterInformation = 30 FILE_INFORMATION_CLASS.FileQuotaInformation = 31 FILE_INFORMATION_CLASS.FileReparsePointInformation = 32 FILE_INFORMATION_CLASS.FileNetworkOpenInformation = 33 FILE_INFORMATION_CLASS.FileAttributeTagInformation = 34 FILE_INFORMATION_CLASS.FileTrackingInformation = 35 FILE_INFORMATION_CLASS.FileIdBothDirectoryInformation = 36 FILE_INFORMATION_CLASS.FileIdFullDirectoryInformation = 37 FILE_INFORMATION_CLASS.FileValidDataLengthInformation = 38 FILE_INFORMATION_CLASS.FileShortNameInformation = 39 FILE_INFORMATION_CLASS.FileIoCompletionNotificationInformation = 40 FILE_INFORMATION_CLASS.FileIoStatusBlockRangeInformation = 41 FILE_INFORMATION_CLASS.FileIoPriorityHintInformation = 42 FILE_INFORMATION_CLASS.FileSfioReserveInformation = 43 FILE_INFORMATION_CLASS.FileSfioVolumeInformation = 44 FILE_INFORMATION_CLASS.FileHardLinkInformation = 45 FILE_INFORMATION_CLASS.FileProcessIdsUsingFileInformation = 46 FILE_INFORMATION_CLASS.FileNormalizedNameInformation = 47 FILE_INFORMATION_CLASS.FileNetworkPhysicalNameInformation = 48 FILE_INFORMATION_CLASS.FileIdGlobalTxDirectoryInformation = 49 FILE_INFORMATION_CLASS.FileIsRemoteDeviceInformation = 50 FILE_INFORMATION_CLASS.FileAttributeCacheInformation = 51 FILE_INFORMATION_CLASS.FileNumaNodeInformation = 52 FILE_INFORMATION_CLASS.FileStandardLinkInformation = 53 FILE_INFORMATION_CLASS.FileRemoteProtocolInformation = 54 FILE_INFORMATION_CLASS.FileMaximumInformation = 55 ALTERNATIVE_ARCHITECTURE_TYPE = v_enum() ALTERNATIVE_ARCHITECTURE_TYPE.StandardDesign = 0 ALTERNATIVE_ARCHITECTURE_TYPE.NEC98x86 = 1 ALTERNATIVE_ARCHITECTURE_TYPE.EndAlternatives = 2 BUS_QUERY_ID_TYPE = v_enum() BUS_QUERY_ID_TYPE.BusQueryDeviceID = 0 BUS_QUERY_ID_TYPE.BusQueryHardwareIDs = 1 BUS_QUERY_ID_TYPE.BusQueryCompatibleIDs = 2 BUS_QUERY_ID_TYPE.BusQueryInstanceID = 3 BUS_QUERY_ID_TYPE.BusQueryDeviceSerialNumber = 4 BUS_QUERY_ID_TYPE.BusQueryContainerID = 5 KOBJECTS = v_enum() KOBJECTS.EventNotificationObject = 0 KOBJECTS.EventSynchronizationObject = 1 KOBJECTS.MutantObject = 2 KOBJECTS.ProcessObject = 3 KOBJECTS.QueueObject = 4 KOBJECTS.SemaphoreObject = 5 KOBJECTS.ThreadObject = 6 KOBJECTS.GateObject = 7 KOBJECTS.TimerNotificationObject = 8 KOBJECTS.TimerSynchronizationObject = 9 KOBJECTS.Spare2Object = 10 KOBJECTS.Spare3Object = 11 KOBJECTS.Spare4Object = 12 KOBJECTS.Spare5Object = 13 KOBJECTS.Spare6Object = 14 KOBJECTS.Spare7Object = 15 KOBJECTS.Spare8Object = 16 KOBJECTS.Spare9Object = 17 KOBJECTS.ApcObject = 18 KOBJECTS.DpcObject = 19 KOBJECTS.DeviceQueueObject = 20 KOBJECTS.EventPairObject = 21 KOBJECTS.InterruptObject = 22 KOBJECTS.ProfileObject = 23 KOBJECTS.ThreadedDpcObject = 24 KOBJECTS.MaximumKernelObject = 25 NT_PRODUCT_TYPE = v_enum() NT_PRODUCT_TYPE.NtProductWinNt = 0 NT_PRODUCT_TYPE.NtProductLanManNt = 1 NT_PRODUCT_TYPE.NtProductServer = 2 DEVICE_POWER_STATE = v_enum() DEVICE_POWER_STATE.PowerDeviceUnspecified = 0 DEVICE_POWER_STATE.PowerDeviceD0 = 1 DEVICE_POWER_STATE.PowerDeviceD1 = 2 DEVICE_POWER_STATE.PowerDeviceD2 = 3 DEVICE_POWER_STATE.PowerDeviceD3 = 4 DEVICE_POWER_STATE.PowerDeviceMaximum = 5 WHEA_ERROR_SOURCE_TYPE = v_enum() WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeMCE = 0 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeCMC = 1 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeCPE = 2 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeNMI = 3 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypePCIe = 4 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeGeneric = 5 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeINIT = 6 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeBOOT = 7 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeSCIGeneric = 8 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFMCA = 9 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFCMC = 10 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFCPE = 11 WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeMax = 12 PROC_HYPERVISOR_STATE = v_enum() PROC_HYPERVISOR_STATE.ProcHypervisorNone = 0 PROC_HYPERVISOR_STATE.ProcHypervisorPresent = 1 PROC_HYPERVISOR_STATE.ProcHypervisorPower = 2 RTL_GENERIC_COMPARE_RESULTS = v_enum() RTL_GENERIC_COMPARE_RESULTS.GenericLessThan = 0 RTL_GENERIC_COMPARE_RESULTS.GenericGreaterThan = 1 RTL_GENERIC_COMPARE_RESULTS.GenericEqual = 2 KWAIT_BLOCK_STATE = v_enum() KWAIT_BLOCK_STATE.WaitBlockBypassStart = 0 KWAIT_BLOCK_STATE.WaitBlockBypassComplete = 1 KWAIT_BLOCK_STATE.WaitBlockActive = 2 KWAIT_BLOCK_STATE.WaitBlockInactive = 3 KWAIT_BLOCK_STATE.WaitBlockAllStates = 4 WHEA_ERROR_TYPE = v_enum() WHEA_ERROR_TYPE.WheaErrTypeProcessor = 0 WHEA_ERROR_TYPE.WheaErrTypeMemory = 1 WHEA_ERROR_TYPE.WheaErrTypePCIExpress = 2 WHEA_ERROR_TYPE.WheaErrTypeNMI = 3 WHEA_ERROR_TYPE.WheaErrTypePCIXBus = 4 WHEA_ERROR_TYPE.WheaErrTypePCIXDevice = 5 WHEA_ERROR_TYPE.WheaErrTypeGeneric = 6 PROCESSOR_CACHE_TYPE = v_enum() PROCESSOR_CACHE_TYPE.CacheUnified = 0 PROCESSOR_CACHE_TYPE.CacheInstruction = 1 PROCESSOR_CACHE_TYPE.CacheData = 2 PROCESSOR_CACHE_TYPE.CacheTrace = 3 MCA_EXCEPTION_TYPE = v_enum() MCA_EXCEPTION_TYPE.HAL_MCE_RECORD = 0 MCA_EXCEPTION_TYPE.HAL_MCA_RECORD = 1 EVENT_TYPE = v_enum() EVENT_TYPE.NotificationEvent = 0 EVENT_TYPE.SynchronizationEvent = 1 KSPIN_LOCK_QUEUE_NUMBER = v_enum() KSPIN_LOCK_QUEUE_NUMBER.LockQueueUnusedSpare0 = 0 KSPIN_LOCK_QUEUE_NUMBER.LockQueueExpansionLock = 1 KSPIN_LOCK_QUEUE_NUMBER.LockQueueUnusedSpare2 = 2 KSPIN_LOCK_QUEUE_NUMBER.LockQueueSystemSpaceLock = 3 KSPIN_LOCK_QUEUE_NUMBER.LockQueueVacbLock = 4 KSPIN_LOCK_QUEUE_NUMBER.LockQueueMasterLock = 5 KSPIN_LOCK_QUEUE_NUMBER.LockQueueNonPagedPoolLock = 6 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoCancelLock = 7 KSPIN_LOCK_QUEUE_NUMBER.LockQueueWorkQueueLock = 8 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoVpbLock = 9 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoDatabaseLock = 10 KSPIN_LOCK_QUEUE_NUMBER.LockQueueIoCompletionLock = 11 KSPIN_LOCK_QUEUE_NUMBER.LockQueueNtfsStructLock = 12 KSPIN_LOCK_QUEUE_NUMBER.LockQueueAfdWorkQueueLock = 13 KSPIN_LOCK_QUEUE_NUMBER.LockQueueBcbLock = 14 KSPIN_LOCK_QUEUE_NUMBER.LockQueueMmNonPagedPoolLock = 15 KSPIN_LOCK_QUEUE_NUMBER.LockQueueUnusedSpare16 = 16 KSPIN_LOCK_QUEUE_NUMBER.LockQueueMaximumLock = 17 TP_CALLBACK_PRIORITY = v_enum() TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_HIGH = 0 TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_NORMAL = 1 TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_LOW = 2 TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_INVALID = 3 FSINFOCLASS = v_enum() FSINFOCLASS.FileFsVolumeInformation = 0 FSINFOCLASS.FileFsLabelInformation = 1 FSINFOCLASS.FileFsSizeInformation = 2 FSINFOCLASS.FileFsDeviceInformation = 3 FSINFOCLASS.FileFsAttributeInformation = 4 FSINFOCLASS.FileFsControlInformation = 5 FSINFOCLASS.FileFsFullSizeInformation = 6 FSINFOCLASS.FileFsObjectIdInformation = 7 FSINFOCLASS.FileFsDriverPathInformation = 8 FSINFOCLASS.FileFsVolumeFlagsInformation = 9 FSINFOCLASS.FileFsMaximumInformation = 10 WORKING_SET_TYPE = v_enum() WORKING_SET_TYPE.WorkingSetTypeUser = 0 WORKING_SET_TYPE.WorkingSetTypeSession = 1 WORKING_SET_TYPE.WorkingSetTypeSystemTypes = 2 WORKING_SET_TYPE.WorkingSetTypeSystemCache = 3 WORKING_SET_TYPE.WorkingSetTypePagedPool = 4 WORKING_SET_TYPE.WorkingSetTypeSystemPtes = 5 WORKING_SET_TYPE.WorkingSetTypeMaximum = 6 POOL_TYPE = v_enum() POOL_TYPE.NonPagedPool = 0 POOL_TYPE.PagedPool = 1 POOL_TYPE.NonPagedPoolMustSucceed = 2 POOL_TYPE.DontUseThisType = 3 POOL_TYPE.NonPagedPoolCacheAligned = 4 POOL_TYPE.PagedPoolCacheAligned = 5 POOL_TYPE.NonPagedPoolCacheAlignedMustS = 6 POOL_TYPE.MaxPoolType = 7 POOL_TYPE.NonPagedPoolSession = 8 POOL_TYPE.PagedPoolSession = 9 POOL_TYPE.NonPagedPoolMustSucceedSession = 10 POOL_TYPE.DontUseThisTypeSession = 11 POOL_TYPE.NonPagedPoolCacheAlignedSession = 12 POOL_TYPE.PagedPoolCacheAlignedSession = 13 POOL_TYPE.NonPagedPoolCacheAlignedMustSSession = 14 IO_PRIORITY_HINT = v_enum() IO_PRIORITY_HINT.IoPriorityVeryLow = 0 IO_PRIORITY_HINT.IoPriorityLow = 1 IO_PRIORITY_HINT.IoPriorityNormal = 2 IO_PRIORITY_HINT.IoPriorityHigh = 3 IO_PRIORITY_HINT.IoPriorityCritical = 4 IO_PRIORITY_HINT.MaxIoPriorityTypes = 5 MODE = v_enum() MODE.KernelMode = 0 MODE.UserMode = 1 MODE.MaximumMode = 2 FS_FILTER_SECTION_SYNC_TYPE = v_enum() FS_FILTER_SECTION_SYNC_TYPE.SyncTypeOther = 0 FS_FILTER_SECTION_SYNC_TYPE.SyncTypeCreateSection = 1 OB_OPEN_REASON = v_enum() OB_OPEN_REASON.ObCreateHandle = 0 OB_OPEN_REASON.ObOpenHandle = 1 OB_OPEN_REASON.ObDuplicateHandle = 2 OB_OPEN_REASON.ObInheritHandle = 3 OB_OPEN_REASON.ObMaxOpenReason = 4 HEAP_FAILURE_TYPE = v_enum() HEAP_FAILURE_TYPE.heap_failure_internal = 0 HEAP_FAILURE_TYPE.heap_failure_unknown = 1 HEAP_FAILURE_TYPE.heap_failure_generic = 2 HEAP_FAILURE_TYPE.heap_failure_entry_corruption = 3 HEAP_FAILURE_TYPE.heap_failure_multiple_entries_corruption = 4 HEAP_FAILURE_TYPE.heap_failure_virtual_block_corruption = 5 HEAP_FAILURE_TYPE.heap_failure_buffer_overrun = 6 HEAP_FAILURE_TYPE.heap_failure_buffer_underrun = 7 HEAP_FAILURE_TYPE.heap_failure_block_not_busy = 8 HEAP_FAILURE_TYPE.heap_failure_invalid_argument = 9 HEAP_FAILURE_TYPE.heap_failure_usage_after_free = 10 HEAP_FAILURE_TYPE.heap_failure_cross_heap_operation = 11 HEAP_FAILURE_TYPE.heap_failure_freelists_corruption = 12 HEAP_FAILURE_TYPE.heap_failure_listentry_corruption = 13 DEVICE_TEXT_TYPE = v_enum() DEVICE_TEXT_TYPE.DeviceTextDescription = 0 DEVICE_TEXT_TYPE.DeviceTextLocationInformation = 1 POWER_STATE_TYPE = v_enum() POWER_STATE_TYPE.SystemPowerState = 0 POWER_STATE_TYPE.DevicePowerState = 1 IRQ_PRIORITY = v_enum() IRQ_PRIORITY.IrqPriorityUndefined = 0 IRQ_PRIORITY.IrqPriorityLow = 1 IRQ_PRIORITY.IrqPriorityNormal = 2 IRQ_PRIORITY.IrqPriorityHigh = 3 KWAIT_STATE = v_enum() KWAIT_STATE.WaitInProgress = 0 KWAIT_STATE.WaitCommitted = 1 KWAIT_STATE.WaitAborted = 2 KWAIT_STATE.MaximumWaitState = 3 LSA_FOREST_TRUST_RECORD_TYPE = v_enum() LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName = 0 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx = 1 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo = 2 LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustRecordTypeLast = 3 IO_ALLOCATION_ACTION = v_enum() IO_ALLOCATION_ACTION.KeepObject = 0 IO_ALLOCATION_ACTION.DeallocateObject = 1 IO_ALLOCATION_ACTION.DeallocateObjectKeepRegisters = 2 EXCEPTION_DISPOSITION = v_enum() EXCEPTION_DISPOSITION.ExceptionContinueExecution = 0 EXCEPTION_DISPOSITION.ExceptionContinueSearch = 1 EXCEPTION_DISPOSITION.ExceptionNestedException = 2 EXCEPTION_DISPOSITION.ExceptionCollidedUnwind = 3 SECURITY_OPERATION_CODE = v_enum() SECURITY_OPERATION_CODE.SetSecurityDescriptor = 0 SECURITY_OPERATION_CODE.QuerySecurityDescriptor = 1 SECURITY_OPERATION_CODE.DeleteSecurityDescriptor = 2 SECURITY_OPERATION_CODE.AssignSecurityDescriptor = 3 PP_NPAGED_LOOKASIDE_NUMBER = v_enum() PP_NPAGED_LOOKASIDE_NUMBER.LookasideSmallIrpList = 0 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMediumIrpList = 1 PP_NPAGED_LOOKASIDE_NUMBER.LookasideLargeIrpList = 2 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMdlList = 3 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCreateInfoList = 4 PP_NPAGED_LOOKASIDE_NUMBER.LookasideNameBufferList = 5 PP_NPAGED_LOOKASIDE_NUMBER.LookasideTwilightList = 6 PP_NPAGED_LOOKASIDE_NUMBER.LookasideCompletionList = 7 PP_NPAGED_LOOKASIDE_NUMBER.LookasideScratchBufferList = 8 PP_NPAGED_LOOKASIDE_NUMBER.LookasideMaximumList = 9 WHEA_ERROR_PACKET_DATA_FORMAT = v_enum() WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatIPFSalRecord = 0 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatXPFMCA = 1 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatMemory = 2 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIExpress = 3 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatNMIPort = 4 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIXBus = 5 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIXDevice = 6 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatGeneric = 7 WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatMax = 8 FS_FILTER_STREAM_FO_NOTIFICATION_TYPE = v_enum() FS_FILTER_STREAM_FO_NOTIFICATION_TYPE.NotifyTypeCreate = 0 FS_FILTER_STREAM_FO_NOTIFICATION_TYPE.NotifyTypeRetired = 1 DISPLAYCONFIG_SCANLINE_ORDERING = v_enum() DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = 0 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = 1 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = 2 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = 3 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = 4 DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32 = 5 SECURITY_IMPERSONATION_LEVEL = v_enum() SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous = 0 SECURITY_IMPERSONATION_LEVEL.SecurityIdentification = 1 SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation = 2 SECURITY_IMPERSONATION_LEVEL.SecurityDelegation = 3 DEVICE_USAGE_NOTIFICATION_TYPE = v_enum() DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeUndefined = 0 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypePaging = 1 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeHibernation = 2 DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeDumpFile = 3 INTERFACE_TYPE = v_enum() INTERFACE_TYPE.InterfaceTypeUndefined = 0 INTERFACE_TYPE.Internal = 1 INTERFACE_TYPE.Isa = 2 INTERFACE_TYPE.Eisa = 3 INTERFACE_TYPE.MicroChannel = 4 INTERFACE_TYPE.TurboChannel = 5 INTERFACE_TYPE.PCIBus = 6 INTERFACE_TYPE.VMEBus = 7 INTERFACE_TYPE.NuBus = 8 INTERFACE_TYPE.PCMCIABus = 9 INTERFACE_TYPE.CBus = 10 INTERFACE_TYPE.MPIBus = 11 INTERFACE_TYPE.MPSABus = 12 INTERFACE_TYPE.ProcessorInternal = 13 INTERFACE_TYPE.InternalPowerBus = 14 INTERFACE_TYPE.PNPISABus = 15 INTERFACE_TYPE.PNPBus = 16 INTERFACE_TYPE.Vmcs = 17 INTERFACE_TYPE.MaximumInterfaceType = 18 PS_RESOURCE_TYPE = v_enum() PS_RESOURCE_TYPE.PsResourceNonPagedPool = 0 PS_RESOURCE_TYPE.PsResourcePagedPool = 1 PS_RESOURCE_TYPE.PsResourcePageFile = 2 PS_RESOURCE_TYPE.PsResourceWorkingSet = 3 PS_RESOURCE_TYPE.PsResourceCpuRate = 4 PS_RESOURCE_TYPE.PsResourceMax = 5 MM_PAGE_ACCESS_TYPE = v_enum() MM_PAGE_ACCESS_TYPE.MmPteAccessType = 0 MM_PAGE_ACCESS_TYPE.MmCcReadAheadType = 1 MM_PAGE_ACCESS_TYPE.MmPfnRepurposeType = 2 MM_PAGE_ACCESS_TYPE.MmMaximumPageAccessType = 3 PF_FILE_ACCESS_TYPE = v_enum() PF_FILE_ACCESS_TYPE.PfFileAccessTypeRead = 0 PF_FILE_ACCESS_TYPE.PfFileAccessTypeWrite = 1 PF_FILE_ACCESS_TYPE.PfFileAccessTypeMax = 2 HARDWARE_COUNTER_TYPE = v_enum() HARDWARE_COUNTER_TYPE.PMCCounter = 0 HARDWARE_COUNTER_TYPE.MaxHardwareCounterType = 1 ReplacesCorHdrNumericDefines = v_enum() ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY = 0 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED = 1 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY = 2 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED = 3 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = 4 ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA = 5 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR_V2 = 6 ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR = 7 ReplacesCorHdrNumericDefines.COR_VERSION_MINOR = 8 ReplacesCorHdrNumericDefines.COR_DELETED_NAME_LENGTH = 9 ReplacesCorHdrNumericDefines.COR_VTABLEGAP_NAME_LENGTH = 10 ReplacesCorHdrNumericDefines.NATIVE_TYPE_MAX_CB = 11 ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 12 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_METHODRVA = 13 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_EHRVA = 14 ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_BASICBLOCK = 15 ReplacesCorHdrNumericDefines.COR_VTABLE_32BIT = 16 ReplacesCorHdrNumericDefines.COR_VTABLE_64BIT = 17 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED = 18 ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = 19 ReplacesCorHdrNumericDefines.COR_VTABLE_CALL_MOST_DERIVED = 20 ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE = 21 ReplacesCorHdrNumericDefines.MAX_CLASS_NAME = 22 ReplacesCorHdrNumericDefines.MAX_PACKAGE_NAME = 23 SYSTEM_POWER_STATE = v_enum() SYSTEM_POWER_STATE.PowerSystemUnspecified = 0 SYSTEM_POWER_STATE.PowerSystemWorking = 1 SYSTEM_POWER_STATE.PowerSystemSleeping1 = 2 SYSTEM_POWER_STATE.PowerSystemSleeping2 = 3 SYSTEM_POWER_STATE.PowerSystemSleeping3 = 4 SYSTEM_POWER_STATE.PowerSystemHibernate = 5 SYSTEM_POWER_STATE.PowerSystemShutdown = 6 SYSTEM_POWER_STATE.PowerSystemMaximum = 7 MEMORY_CACHING_TYPE_ORIG = v_enum() MEMORY_CACHING_TYPE_ORIG.MmFrameBufferCached = 0 POWER_ACTION = v_enum() POWER_ACTION.PowerActionNone = 0 POWER_ACTION.PowerActionReserved = 1 POWER_ACTION.PowerActionSleep = 2 POWER_ACTION.PowerActionHibernate = 3 POWER_ACTION.PowerActionShutdown = 4 POWER_ACTION.PowerActionShutdownReset = 5 POWER_ACTION.PowerActionShutdownOff = 6 POWER_ACTION.PowerActionWarmEject = 7 class _unnamed_9074(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.McaCod = v_uint16() self.MsCod = v_uint16() self.OtherInfo = v_uint32() class _unnamed_9775(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Group = v_uint16() self.MessageCount = v_uint16() self.Vector = v_uint32() self.Affinity = v_uint32() class _unnamed_9770(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint16() self.Group = v_uint16() self.Vector = v_uint32() self.Affinity = v_uint32() class _unnamed_9079(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BankNumber = v_uint8() self.Reserved2 = v_bytes(size=7) # FIXME Unknown Array Type self.Status = MCI_STATS() self.Address = MCI_ADDR() self.Misc = v_uint64() class IO_PRIORITY_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint32() self.ThreadPriority = v_uint32() self.PagePriority = v_uint32() self.IoPriority = v_uint32() class KEXECUTE_OPTIONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExecuteDisable = v_uint8() class SID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.SubAuthorityCount = v_uint8() self.IdentifierAuthority = SID_IDENTIFIER_AUTHORITY() self.SubAuthority = v_bytes(size=4) # FIXME Unknown Array Type class WHEA_ERROR_PACKET_V2(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.Version = v_uint32() self.Length = v_uint32() self.Flags = WHEA_ERROR_PACKET_FLAGS() self.ErrorType = v_uint32() self.ErrorSeverity = v_uint32() self.ErrorSourceId = v_uint32() self.ErrorSourceType = v_uint32() self.NotifyType = GUID() self.Context = v_uint64() self.DataFormat = v_uint32() self.Reserved1 = v_uint32() self.DataOffset = v_uint32() self.DataLength = v_uint32() self.PshedDataOffset = v_uint32() self.PshedDataLength = v_uint32() class _unnamed_8009(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.FsInformationClass = v_uint32() class GROUP_AFFINITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mask = v_uint32() self.Group = v_uint16() self.Reserved = v_bytes(size=6) # FIXME Unknown Array Type class KTSS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Backlink = v_uint16() self.Reserved0 = v_uint16() self.Esp0 = v_uint32() self.Ss0 = v_uint16() self.Reserved1 = v_uint16() self.NotUsed1 = v_bytes(size=16) # FIXME Unknown Array Type self.CR3 = v_uint32() self.Eip = v_uint32() self.EFlags = v_uint32() self.Eax = v_uint32() self.Ecx = v_uint32() self.Edx = v_uint32() self.Ebx = v_uint32() self.Esp = v_uint32() self.Ebp = v_uint32() self.Esi = v_uint32() self.Edi = v_uint32() self.Es = v_uint16() self.Reserved2 = v_uint16() self.Cs = v_uint16() self.Reserved3 = v_uint16() self.Ss = v_uint16() self.Reserved4 = v_uint16() self.Ds = v_uint16() self.Reserved5 = v_uint16() self.Fs = v_uint16() self.Reserved6 = v_uint16() self.Gs = v_uint16() self.Reserved7 = v_uint16() self.LDT = v_uint16() self.Reserved8 = v_uint16() self.Flags = v_uint16() self.IoMapBase = v_uint16() self.IoMaps = v_uint16() self.IntDirectionMap = v_bytes(size=32) # FIXME Unknown Array Type class CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DosPath = UNICODE_STRING() self.Handle = v_ptr32() class PERFINFO_GROUPMASK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Masks = v_bytes(size=32) # FIXME Unknown Array Type class HANDLE_TABLE_ENTRY_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AuditMask = v_uint32() class _unnamed_9803(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length64 = v_uint32() class _unnamed_9800(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length48 = v_uint32() class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SectionOffset = v_uint32() self.SectionLength = v_uint32() self.Revision = WHEA_REVISION() self.ValidBits = WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS() self.Reserved = v_uint8() self.Flags = WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS() self.SectionType = GUID() self.FRUId = GUID() self.SectionSeverity = v_uint32() self.FRUText = v_bytes(size=20) # FIXME Unknown Array Type class PS_CPU_QUOTA_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.SessionId = v_uint32() self.CpuShareWeight = v_uint32() self.CapturedWeightData = PSP_CPU_SHARE_CAPTURED_WEIGHT_DATA() self.DuplicateInputMarker = v_uint32() self._pad0040 = v_bytes(size=36) self.CycleCredit = v_uint64() self.BlockCurrentGeneration = v_uint32() self.CpuCyclePercent = v_uint32() self.CyclesFinishedForCurrentGeneration = v_uint8() self._pad0080 = v_bytes(size=47) self.Cpu = v_uint8() class _unnamed_9783(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Channel = v_uint32() self.Port = v_uint32() self.Reserved1 = v_uint32() class RTL_TRACE_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Database = v_ptr32() self.NextSegment = v_ptr32() self.TotalSize = v_uint32() self.SegmentStart = v_ptr32() self.SegmentEnd = v_ptr32() self.SegmentFree = v_ptr32() class _unnamed_9787(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data = v_bytes(size=12) # FIXME Unknown Array Type class _unnamed_9789(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = v_uint32() self.Length = v_uint32() self.Reserved = v_uint32() class DEVICE_CAPABILITIES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.DeviceD1 = v_uint32() self.Address = v_uint32() self.UINumber = v_uint32() self.DeviceState = v_uint32() self.SystemWake = v_uint32() self.DeviceWake = v_uint32() self.D1Latency = v_uint32() self.D2Latency = v_uint32() self.D3Latency = v_uint32() class _unnamed_7990(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.EaList = v_ptr32() self.EaListLength = v_uint32() self.EaIndex = v_uint32() class _unnamed_7995(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() class KPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.ProfileListHead = LIST_ENTRY() self.DirectoryTableBase = v_uint32() self.LdtDescriptor = KGDTENTRY() self.Int21Descriptor = KIDTENTRY() self.ThreadListHead = LIST_ENTRY() self.ProcessLock = v_uint32() self.Affinity = KAFFINITY_EX() self.ReadyListHead = LIST_ENTRY() self.SwapListEntry = SINGLE_LIST_ENTRY() self.ActiveProcessors = KAFFINITY_EX() self.AutoAlignment = v_uint32() self.BasePriority = v_uint8() self.QuantumReset = v_uint8() self.Visited = v_uint8() self.Unused3 = v_uint8() self.ThreadSeed = v_bytes(size=16) # FIXME Unknown Array Type self.IdealNode = v_bytes(size=8) # FIXME Unknown Array Type self.IdealGlobalNode = v_uint16() self.Flags = KEXECUTE_OPTIONS() self.Unused1 = v_uint8() self.IopmOffset = v_uint16() self._pad009c = v_bytes(size=2) self.Unused4 = v_uint32() self.StackCount = KSTACK_COUNT() self.ProcessListEntry = LIST_ENTRY() self._pad00b0 = v_bytes(size=4) self.CycleTime = v_uint64() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.VdmTrapcHandler = v_ptr32() class DEVICE_OBJECT_POWER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class _unnamed_7909(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Key = v_uint32() self.ByteOffset = LARGE_INTEGER() class _unnamed_10332(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length48 = v_uint32() self.Alignment48 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Primary = v_uint32() class TP_CALLBACK_ENVIRON_V3(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint32() self.Pool = v_ptr32() self.CleanupGroup = v_ptr32() self.CleanupGroupCancelCallback = v_ptr32() self.RaceDll = v_ptr32() self.ActivationContext = v_ptr32() self.FinalizationCallback = v_ptr32() self.u = _unnamed_5798() self.CallbackPriority = v_uint32() self.Size = v_uint32() class _unnamed_7902(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityContext = v_ptr32() self.Options = v_uint32() self.Reserved = v_uint16() self.ShareAccess = v_uint16() self.Parameters = v_ptr32() class RTL_ACTIVATION_CONTEXT_STACK_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Previous = v_ptr32() self.ActivationContext = v_ptr32() self.Flags = v_uint32() class ALPC_PROCESS_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = EX_PUSH_LOCK() self.ViewListHead = LIST_ENTRY() self.PagedPoolQuotaCache = v_uint32() class OBJECT_HANDLE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HandleAttributes = v_uint32() self.GrantedAccess = v_uint32() class PROC_PERF_DOMAIN(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Link = LIST_ENTRY() self.Master = v_ptr32() self.Members = KAFFINITY_EX() self.FeedbackHandler = v_ptr32() self.GetFFHThrottleState = v_ptr32() self.BoostPolicyHandler = v_ptr32() self.PerfSelectionHandler = v_ptr32() self.PerfHandler = v_ptr32() self.Processors = v_ptr32() self._pad0040 = v_bytes(size=4) self.PerfChangeTime = v_uint64() self.ProcessorCount = v_uint32() self.PreviousFrequencyMhz = v_uint32() self.CurrentFrequencyMhz = v_uint32() self.PreviousFrequency = v_uint32() self.CurrentFrequency = v_uint32() self.CurrentPerfContext = v_uint32() self.DesiredFrequency = v_uint32() self.MaxFrequency = v_uint32() self.MinPerfPercent = v_uint32() self.MinThrottlePercent = v_uint32() self.MaxPercent = v_uint32() self.MinPercent = v_uint32() self.ConstrainedMaxPercent = v_uint32() self.ConstrainedMinPercent = v_uint32() self.Coordination = v_uint8() self._pad0084 = v_bytes(size=3) self.PerfChangeIntervalCount = v_uint32() class KTIMER_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = v_uint32() self.Entry = LIST_ENTRY() self._pad0010 = v_bytes(size=4) self.Time = ULARGE_INTEGER() class PS_CLIENT_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ImpersonationData = v_uint32() class RTL_AVL_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BalancedRoot = RTL_BALANCED_LINKS() self.OrderedPointer = v_ptr32() self.WhichOrderedElement = v_uint32() self.NumberGenericTableElements = v_uint32() self.DepthOfTree = v_uint32() self.RestartKey = v_ptr32() self.DeleteCount = v_uint32() self.CompareRoutine = v_ptr32() self.AllocateRoutine = v_ptr32() self.FreeRoutine = v_ptr32() self.TableContext = v_ptr32() class RTL_TRACE_DATABASE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Flags = v_uint32() self.Tag = v_uint32() self.SegmentList = v_ptr32() self.MaximumSize = v_uint32() self.CurrentSize = v_uint32() self.Owner = v_ptr32() self.Lock = RTL_CRITICAL_SECTION() self.NoOfBuckets = v_uint32() self.Buckets = v_ptr32() self.HashFunction = v_ptr32() self.NoOfTraces = v_uint32() self.NoOfHits = v_uint32() self.HashCounter = v_bytes(size=64) # FIXME Unknown Array Type class OWNER_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OwnerThread = v_uint32() self.IoPriorityBoosted = v_uint32() class DEVOBJ_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.PowerFlags = v_uint32() self.Dope = v_ptr32() self.ExtensionFlags = v_uint32() self.DeviceNode = v_ptr32() self.AttachedTo = v_ptr32() self.StartIoCount = v_uint32() self.StartIoKey = v_uint32() self.StartIoFlags = v_uint32() self.Vpb = v_ptr32() self.DependentList = LIST_ENTRY() self.ProviderList = LIST_ENTRY() class HEAP_LOCAL_SEGMENT_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Hint = v_ptr32() self.ActiveSubsegment = v_ptr32() self.CachedItems = v_bytes(size=64) # FIXME Unknown Array Type self.SListHeader = SLIST_HEADER() self.Counters = HEAP_BUCKET_COUNTERS() self.LocalData = v_ptr32() self.LastOpSequence = v_uint32() self.BucketIndex = v_uint16() self.LastUsed = v_uint16() class HANDLE_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr32() self.GrantedAccess = v_uint32() class HEAP_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalMemoryReserved = v_uint32() self.TotalMemoryCommitted = v_uint32() self.TotalMemoryLargeUCR = v_uint32() self.TotalSizeInVirtualBlocks = v_uint32() self.TotalSegments = v_uint32() self.TotalUCRs = v_uint32() self.CommittOps = v_uint32() self.DeCommitOps = v_uint32() self.LockAcquires = v_uint32() self.LockCollisions = v_uint32() self.CommitRate = v_uint32() self.DecommittRate = v_uint32() self.CommitFailures = v_uint32() self.InBlockCommitFailures = v_uint32() self.CompactHeapCalls = v_uint32() self.CompactedUCRs = v_uint32() self.AllocAndFreeOps = v_uint32() self.InBlockDeccommits = v_uint32() self.InBlockDeccomitSize = v_uint32() self.HighWatermarkSize = v_uint32() self.LastPolledSize = v_uint32() class MAILSLOT_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MailslotQuota = v_uint32() self.MaximumMessageSize = v_uint32() self.ReadTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class FS_FILTER_CALLBACK_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbackData = v_uint32() self.Operation = v_uint8() self.Reserved = v_uint8() self._pad0008 = v_bytes(size=2) self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.Parameters = FS_FILTER_PARAMETERS() class PPM_IDLE_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DomainMembers = KAFFINITY_EX() self.IdleCheck = v_ptr32() self.IdleHandler = v_ptr32() self.Context = v_ptr32() self.Latency = v_uint32() self.Power = v_uint32() self.TimeCheck = v_uint32() self.StateFlags = v_uint32() self.PromotePercent = v_uint8() self.DemotePercent = v_uint8() self.PromotePercentBase = v_uint8() self.DemotePercentBase = v_uint8() self.StateType = v_uint8() class ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OperationID = LUID() self.SecurityEvaluated = v_uint8() self.GenerateAudit = v_uint8() self.GenerateOnClose = v_uint8() self.PrivilegesAllocated = v_uint8() self.Flags = v_uint32() self.RemainingDesiredAccess = v_uint32() self.PreviouslyGrantedAccess = v_uint32() self.OriginalDesiredAccess = v_uint32() self.SubjectSecurityContext = SECURITY_SUBJECT_CONTEXT() self.SecurityDescriptor = v_ptr32() self.AuxData = v_ptr32() self.Privileges = _unnamed_7708() self.AuditPrivileges = v_uint8() self._pad0064 = v_bytes(size=3) self.ObjectName = UNICODE_STRING() self.ObjectTypeName = UNICODE_STRING() class TP_CALLBACK_INSTANCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class PROC_IDLE_ACCOUNTING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StateCount = v_uint32() self.TotalTransitions = v_uint32() self.ResetCount = v_uint32() self._pad0010 = v_bytes(size=4) self.StartTime = v_uint64() self.BucketLimits = v_bytes(size=128) # FIXME Unknown Array Type self.State = v_bytes(size=128) # FIXME Unknown Array Type class GDI_TEB_BATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint32() self.HDC = v_uint32() self.Buffer = v_bytes(size=1240) # FIXME Unknown Array Type class THREAD_PERFORMANCE_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.ProcessorNumber = PROCESSOR_NUMBER() self.ContextSwitches = v_uint32() self.HwCountersCount = v_uint32() self.UpdateCount = v_uint64() self.WaitReasonBitMap = v_uint64() self.HardwareCounters = v_uint64() self.CycleTime = COUNTER_READING() self.HwCounters = COUNTER_READING() class PAGEFAULT_HISTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class ECP_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class _unnamed_8043(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Vpb = v_ptr32() self.DeviceObject = v_ptr32() class SECTION_OBJECT_POINTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSectionObject = v_ptr32() self.SharedCacheMap = v_ptr32() self.ImageSectionObject = v_ptr32() class _unnamed_8047(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Srb = v_ptr32() class KTRAP_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DbgEbp = v_uint32() self.DbgEip = v_uint32() self.DbgArgMark = v_uint32() self.DbgArgPointer = v_uint32() self.TempSegCs = v_uint16() self.Logging = v_uint8() self.Reserved = v_uint8() self.TempEsp = v_uint32() self.Dr0 = v_uint32() self.Dr1 = v_uint32() self.Dr2 = v_uint32() self.Dr3 = v_uint32() self.Dr6 = v_uint32() self.Dr7 = v_uint32() self.SegGs = v_uint32() self.SegEs = v_uint32() self.SegDs = v_uint32() self.Edx = v_uint32() self.Ecx = v_uint32() self.Eax = v_uint32() self.PreviousPreviousMode = v_uint32() self.ExceptionList = v_ptr32() self.SegFs = v_uint32() self.Edi = v_uint32() self.Esi = v_uint32() self.Ebx = v_uint32() self.Ebp = v_uint32() self.ErrCode = v_uint32() self.Eip = v_uint32() self.SegCs = v_uint32() self.EFlags = v_uint32() self.HardwareEsp = v_uint32() self.HardwareSegSs = v_uint32() self.V86Es = v_uint32() self.V86Ds = v_uint32() self.V86Fs = v_uint32() self.V86Gs = v_uint32() class _unnamed_8120(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Capabilities = v_ptr32() class MCI_ADDR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_uint32() self.Reserved = v_uint32() class IO_TIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.TimerFlag = v_uint16() self.TimerList = LIST_ENTRY() self.TimerRoutine = v_ptr32() self.Context = v_ptr32() self.DeviceObject = v_ptr32() class WHEA_REVISION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinorRevision = v_uint8() self.MajorRevision = v_uint8() class TP_CLEANUP_GROUP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class PROC_IDLE_SNAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Time = v_uint64() self.Idle = v_uint64() class SECURITY_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Revision = v_uint8() self.Sbz1 = v_uint8() self.Control = v_uint16() self.Owner = v_ptr32() self.Group = v_ptr32() self.Sacl = v_ptr32() self.Dacl = v_ptr32() class _unnamed_7708(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InitialPrivilegeSet = INITIAL_PRIVILEGE_SET() class OBJECT_TYPE_INITIALIZER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.ObjectTypeFlags = v_uint8() self._pad0004 = v_bytes(size=1) self.ObjectTypeCode = v_uint32() self.InvalidAttributes = v_uint32() self.GenericMapping = GENERIC_MAPPING() self.ValidAccessMask = v_uint32() self.RetainAccess = v_uint32() self.PoolType = v_uint32() self.DefaultPagedPoolCharge = v_uint32() self.DefaultNonPagedPoolCharge = v_uint32() self.DumpProcedure = v_ptr32() self.OpenProcedure = v_ptr32() self.CloseProcedure = v_ptr32() self.DeleteProcedure = v_ptr32() self.ParseProcedure = v_ptr32() self.SecurityProcedure = v_ptr32() self.QueryNameProcedure = v_ptr32() self.OkayToCloseProcedure = v_ptr32() class TP_DIRECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Callback = v_ptr32() self.NumaNode = v_uint32() self.IdealProcessor = v_uint8() class XSTATE_SAVE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved1 = v_uint64() self.Reserved2 = v_uint32() self.Prev = v_ptr32() self.Reserved3 = v_ptr32() self.Thread = v_ptr32() self.Reserved4 = v_ptr32() self.Level = v_uint8() class HEAP_ENTRY_EXTRA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocatorBackTraceIndex = v_uint16() self.TagIndex = v_uint16() self.Settable = v_uint32() class HEAP_PSEUDO_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint32() class PAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = FAST_MUTEX() class _unnamed_9563(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Balance = v_uint32() class LARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class NPAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() self.Lock__ObsoleteButDoNotDelete = v_uint32() class _unnamed_7790(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UserApcRoutine = v_ptr32() self.UserApcContext = v_ptr32() class VPB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Flags = v_uint16() self.VolumeLabelLength = v_uint16() self.DeviceObject = v_ptr32() self.RealDevice = v_ptr32() self.SerialNumber = v_uint32() self.ReferenceCount = v_uint32() self.VolumeLabel = v_bytes(size=64) # FIXME Unknown Array Type class PP_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P = v_ptr32() self.L = v_ptr32() class OBJECT_NAME_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = UNICODE_STRING() class IO_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.Descriptors = v_uint32() class KUSER_SHARED_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TickCountLowDeprecated = v_uint32() self.TickCountMultiplier = v_uint32() self.InterruptTime = KSYSTEM_TIME() self.SystemTime = KSYSTEM_TIME() self.TimeZoneBias = KSYSTEM_TIME() self.ImageNumberLow = v_uint16() self.ImageNumberHigh = v_uint16() self.NtSystemRoot = v_bytes(size=520) # FIXME Unknown Array Type self.MaxStackTraceDepth = v_uint32() self.CryptoExponent = v_uint32() self.TimeZoneId = v_uint32() self.LargePageMinimum = v_uint32() self.Reserved2 = v_bytes(size=28) # FIXME Unknown Array Type self.NtProductType = v_uint32() self.ProductTypeIsValid = v_uint8() self._pad026c = v_bytes(size=3) self.NtMajorVersion = v_uint32() self.NtMinorVersion = v_uint32() self.ProcessorFeatures = v_bytes(size=64) # FIXME Unknown Array Type self.Reserved1 = v_uint32() self.Reserved3 = v_uint32() self.TimeSlip = v_uint32() self.AlternativeArchitecture = v_uint32() self.AltArchitecturePad = v_bytes(size=4) # FIXME Unknown Array Type self.SystemExpirationDate = LARGE_INTEGER() self.SuiteMask = v_uint32() self.KdDebuggerEnabled = v_uint8() self.NXSupportPolicy = v_uint8() self._pad02d8 = v_bytes(size=2) self.ActiveConsoleId = v_uint32() self.DismountCount = v_uint32() self.ComPlusPackage = v_uint32() self.LastSystemRITEventTickCount = v_uint32() self.NumberOfPhysicalPages = v_uint32() self.SafeBootMode = v_uint8() self.TscQpcData = v_uint8() self.TscQpcPad = v_bytes(size=2) # FIXME Unknown Array Type self.SharedDataFlags = v_uint32() self.DataFlagsPad = v_bytes(size=4) # FIXME Unknown Array Type self.TestRetInstruction = v_uint64() self.SystemCall = v_uint32() self.SystemCallReturn = v_uint32() self.SystemCallPad = v_bytes(size=24) # FIXME Unknown Array Type self.TickCount = KSYSTEM_TIME() self.TickCountPad = v_bytes(size=4) # FIXME Unknown Array Type self.Cookie = v_uint32() self.CookiePad = v_bytes(size=4) # FIXME Unknown Array Type self.ConsoleSessionForegroundProcessId = v_uint64() self.Wow64SharedInformation = v_bytes(size=64) # FIXME Unknown Array Type self.UserModeGlobalLogger = v_bytes(size=32) # FIXME Unknown Array Type self.ImageFileExecutionOptions = v_uint32() self.LangGenerationCount = v_uint32() self.Reserved5 = v_uint64() self.InterruptTimeBias = v_uint64() self.TscQpcBias = v_uint64() self.ActiveProcessorCount = v_uint32() self.ActiveGroupCount = v_uint16() self.Reserved4 = v_uint16() self.AitSamplingValue = v_uint32() self.AppCompatFlag = v_uint32() self.SystemDllNativeRelocation = v_uint64() self.SystemDllWowRelocation = v_uint32() self.XStatePad = v_bytes(size=4) # FIXME Unknown Array Type self.XState = XSTATE_CONFIGURATION() class SYSTEM_POWER_STATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved1 = v_uint32() class FS_FILTER_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AcquireForModifiedPageWriter = _unnamed_9854() class HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.SegmentSignature = v_uint32() self.SegmentFlags = v_uint32() self.SegmentListEntry = LIST_ENTRY() self.Heap = v_ptr32() self.BaseAddress = v_ptr32() self.NumberOfPages = v_uint32() self.FirstEntry = v_ptr32() self.LastValidEntry = v_ptr32() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.SegmentAllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self.UCRSegmentList = LIST_ENTRY() self.Flags = v_uint32() self.ForceFlags = v_uint32() self.CompatibilityFlags = v_uint32() self.EncodeFlagMask = v_uint32() self.Encoding = HEAP_ENTRY() self.PointerKey = v_uint32() self.Interceptor = v_uint32() self.VirtualMemoryThreshold = v_uint32() self.Signature = v_uint32() self.SegmentReserve = v_uint32() self.SegmentCommit = v_uint32() self.DeCommitFreeBlockThreshold = v_uint32() self.DeCommitTotalFreeThreshold = v_uint32() self.TotalFreeSize = v_uint32() self.MaximumAllocationSize = v_uint32() self.ProcessHeapsListIndex = v_uint16() self.HeaderValidateLength = v_uint16() self.HeaderValidateCopy = v_ptr32() self.NextAvailableTagIndex = v_uint16() self.MaximumTagIndex = v_uint16() self.TagEntries = v_ptr32() self.UCRList = LIST_ENTRY() self.AlignRound = v_uint32() self.AlignMask = v_uint32() self.VirtualAllocdBlocks = LIST_ENTRY() self.SegmentList = LIST_ENTRY() self.AllocatorBackTraceIndex = v_uint16() self._pad00b4 = v_bytes(size=2) self.NonDedicatedListLength = v_uint32() self.BlocksIndex = v_ptr32() self.UCRIndex = v_ptr32() self.PseudoTagEntries = v_ptr32() self.FreeLists = LIST_ENTRY() self.LockVariable = v_ptr32() self.CommitRoutine = v_ptr32() self.FrontEndHeap = v_ptr32() self.FrontHeapLockCount = v_uint16() self.FrontEndHeapType = v_uint8() self._pad00dc = v_bytes(size=1) self.Counters = HEAP_COUNTERS() self.TuningParameters = HEAP_TUNING_PARAMETERS() class IO_STATUS_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self.Information = v_uint32() class PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class CM_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = v_uint32() class EPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pcb = KPROCESS() self.ProcessLock = EX_PUSH_LOCK() self._pad00d0 = v_bytes(size=4) self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.RundownProtect = EX_RUNDOWN_REF() self.UniqueProcessId = v_ptr32() self.ActiveProcessLinks = LIST_ENTRY() self.ProcessQuotaUsage = v_bytes(size=8) # FIXME Unknown Array Type self.ProcessQuotaPeak = v_bytes(size=8) # FIXME Unknown Array Type self.CommitCharge = v_uint32() self.QuotaBlock = v_ptr32() self.CpuQuotaBlock = v_ptr32() self.PeakVirtualSize = v_uint32() self.VirtualSize = v_uint32() self.SessionProcessLinks = LIST_ENTRY() self.DebugPort = v_ptr32() self.ExceptionPortData = v_ptr32() self.ObjectTable = v_ptr32() self.Token = EX_FAST_REF() self.WorkingSetPage = v_uint32() self.AddressCreationLock = EX_PUSH_LOCK() self.RotateInProgress = v_ptr32() self.ForkInProgress = v_ptr32() self.HardwareTrigger = v_uint32() self.PhysicalVadRoot = v_ptr32() self.CloneRoot = v_ptr32() self.NumberOfPrivatePages = v_uint32() self.NumberOfLockedPages = v_uint32() self.Win32Process = v_ptr32() self.Job = v_ptr32() self.SectionObject = v_ptr32() self.SectionBaseAddress = v_ptr32() self.Cookie = v_uint32() self.Spare8 = v_uint32() self.WorkingSetWatch = v_ptr32() self.Win32WindowStation = v_ptr32() self.InheritedFromUniqueProcessId = v_ptr32() self.LdtInformation = v_ptr32() self.VdmObjects = v_ptr32() self.ConsoleHostProcess = v_uint32() self.DeviceMap = v_ptr32() self.EtwDataSource = v_ptr32() self.FreeTebHint = v_ptr32() self._pad0190 = v_bytes(size=4) self.PageDirectoryPte = HARDWARE_PTE_X86() self._pad0198 = v_bytes(size=4) self.Session = v_ptr32() self.ImageFileName = v_bytes(size=15) # FIXME Unknown Array Type self.PriorityClass = v_uint8() self.JobLinks = LIST_ENTRY() self.LockedPagesList = v_ptr32() self.ThreadListHead = LIST_ENTRY() self.SecurityPort = v_ptr32() self.PaeTop = v_ptr32() self.ActiveThreads = v_uint32() self.ImagePathHash = v_uint32() self.DefaultHardErrorProcessing = v_uint32() self.LastThreadExitStatus = v_uint32() self.Peb = v_ptr32() self.PrefetchTrace = EX_FAST_REF() self.ReadOperationCount = LARGE_INTEGER() self.WriteOperationCount = LARGE_INTEGER() self.OtherOperationCount = LARGE_INTEGER() self.ReadTransferCount = LARGE_INTEGER() self.WriteTransferCount = LARGE_INTEGER() self.OtherTransferCount = LARGE_INTEGER() self.CommitChargeLimit = v_uint32() self.CommitChargePeak = v_uint32() self.AweInfo = v_ptr32() self.SeAuditProcessCreationInfo = SE_AUDIT_PROCESS_CREATION_INFO() self.Vm = MMSUPPORT() self.MmProcessLinks = LIST_ENTRY() self.HighestUserAddress = v_ptr32() self.ModifiedPageCount = v_uint32() self.Flags2 = v_uint32() self.Flags = v_uint32() self.ExitStatus = v_uint32() self.VadRoot = MM_AVL_TABLE() self.AlpcContext = ALPC_PROCESS_CONTEXT() self.TimerResolutionLink = LIST_ENTRY() self.RequestedTimerResolution = v_uint32() self.ActiveThreadsHighWatermark = v_uint32() self.SmallestTimerResolution = v_uint32() self.TimerResolutionStackRecord = v_ptr32() class TP_TASK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Callbacks = v_ptr32() self.NumaNode = v_uint32() self.IdealProcessor = v_uint8() self._pad000c = v_bytes(size=3) self.PostGuard = TP_NBQ_GUARD() self.NBQNode = v_ptr32() class TEB_ACTIVE_FRAME_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.FrameName = v_ptr32() class KTIMER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.DueTime = ULARGE_INTEGER() self.TimerListEntry = LIST_ENTRY() self.Dpc = v_ptr32() self.Period = v_uint32() class CM_PARTIAL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Flags = v_uint16() self.u = _unnamed_9547() class _unnamed_7890(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityContext = v_ptr32() self.Options = v_uint32() self.Reserved = v_uint16() self.ShareAccess = v_uint16() self.Parameters = v_ptr32() class OBJECT_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.RootDirectory = v_ptr32() self.ObjectName = v_ptr32() self.Attributes = v_uint32() self.SecurityDescriptor = v_ptr32() self.SecurityQualityOfService = v_ptr32() class CM_FULL_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.PartialResourceList = CM_PARTIAL_RESOURCE_LIST() class KTIMER_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TimerExpiry = v_bytes(size=64) # FIXME Unknown Array Type self.TimerEntries = v_bytes(size=64) # FIXME Unknown Array Type class FAST_IO_DISPATCH(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFastIoDispatch = v_uint32() self.FastIoCheckIfPossible = v_ptr32() self.FastIoRead = v_ptr32() self.FastIoWrite = v_ptr32() self.FastIoQueryBasicInfo = v_ptr32() self.FastIoQueryStandardInfo = v_ptr32() self.FastIoLock = v_ptr32() self.FastIoUnlockSingle = v_ptr32() self.FastIoUnlockAll = v_ptr32() self.FastIoUnlockAllByKey = v_ptr32() self.FastIoDeviceControl = v_ptr32() self.AcquireFileForNtCreateSection = v_ptr32() self.ReleaseFileForNtCreateSection = v_ptr32() self.FastIoDetachDevice = v_ptr32() self.FastIoQueryNetworkOpenInfo = v_ptr32() self.AcquireForModWrite = v_ptr32() self.MdlRead = v_ptr32() self.MdlReadComplete = v_ptr32() self.PrepareMdlWrite = v_ptr32() self.MdlWriteComplete = v_ptr32() self.FastIoReadCompressed = v_ptr32() self.FastIoWriteCompressed = v_ptr32() self.MdlReadCompleteCompressed = v_ptr32() self.MdlWriteCompleteCompressed = v_ptr32() self.FastIoQueryOpen = v_ptr32() self.ReleaseForModWrite = v_ptr32() self.AcquireForCcFlush = v_ptr32() self.ReleaseForCcFlush = v_ptr32() class _unnamed_8164(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InPath = v_uint8() self.Reserved = v_bytes(size=3) # FIXME Unknown Array Type self.Type = v_uint32() class _unnamed_9856(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SyncType = v_uint32() self.PageProtection = v_uint32() class RTL_DYNAMIC_HASH_TABLE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ChainHead = v_ptr32() self.PrevLinkage = v_ptr32() self.Signature = v_uint32() class MMWSL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class PROC_IDLE_STATE_ACCOUNTING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalTime = v_uint64() self.IdleTransitions = v_uint32() self.FailedTransitions = v_uint32() self.InvalidBucketIndex = v_uint32() self._pad0018 = v_bytes(size=4) self.MinTime = v_uint64() self.MaxTime = v_uint64() self.IdleTimeBuckets = v_uint64() class _unnamed_9067(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mca = _unnamed_9079() class KSPECIAL_REGISTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Cr0 = v_uint32() self.Cr2 = v_uint32() self.Cr3 = v_uint32() self.Cr4 = v_uint32() self.KernelDr0 = v_uint32() self.KernelDr1 = v_uint32() self.KernelDr2 = v_uint32() self.KernelDr3 = v_uint32() self.KernelDr6 = v_uint32() self.KernelDr7 = v_uint32() self.Gdtr = DESCRIPTOR() self.Idtr = DESCRIPTOR() self.Tr = v_uint16() self.Ldtr = v_uint16() self.Reserved = v_bytes(size=24) # FIXME Unknown Array Type class RTL_CRITICAL_SECTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DebugInfo = v_ptr32() self.LockCount = v_uint32() self.RecursionCount = v_uint32() self.OwningThread = v_ptr32() self.LockSemaphore = v_ptr32() self.SpinCount = v_uint32() class KSYSTEM_TIME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.High1Time = v_uint32() self.High2Time = v_uint32() class PROC_IDLE_STATE_BUCKET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalTime = v_uint64() self.MinTime = v_uint64() self.MaxTime = v_uint64() self.Count = v_uint32() class RTL_STD_LIST_HEAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Lock = RTL_STACK_DATABASE_LOCK() class FLOATING_SAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint32() self.StatusWord = v_uint32() self.TagWord = v_uint32() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint32() self.DataOffset = v_uint32() self.DataSelector = v_uint32() self.RegisterArea = v_bytes(size=80) # FIXME Unknown Array Type self.Cr0NpxState = v_uint32() class DPH_HEAP_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.pNextAlloc = v_ptr32() self._pad0010 = v_bytes(size=12) self.pUserAllocation = v_ptr32() self.pVirtualBlock = v_ptr32() self.nVirtualBlockSize = v_uint32() self.nVirtualAccessSize = v_uint32() self.nUserRequestedSize = v_uint32() self.nUserActualSize = v_uint32() self.UserValue = v_ptr32() self.UserFlags = v_uint32() self.StackTrace = v_ptr32() self.AdjacencyEntry = LIST_ENTRY() self.pVirtualRegion = v_ptr32() class KQUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.EntryListHead = LIST_ENTRY() self.CurrentCount = v_uint32() self.MaximumCount = v_uint32() self.ThreadListHead = LIST_ENTRY() class _unnamed_8017(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_ptr32() self.Key = v_uint32() self.ByteOffset = LARGE_INTEGER() class LUID_AND_ATTRIBUTES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Luid = LUID() self.Attributes = v_uint32() class _unnamed_8012(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OutputBufferLength = v_uint32() self.InputBufferLength = v_uint32() self.FsControlCode = v_uint32() self.Type3InputBuffer = v_ptr32() class HEAP_BUCKET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BlockUnits = v_uint16() self.SizeIndex = v_uint8() self.UseAffinity = v_uint8() class CM_PARTIAL_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.PartialDescriptors = v_uint32() class KTHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.CycleTime = v_uint64() self.HighCycleTime = v_uint32() self._pad0020 = v_bytes(size=4) self.QuantumTarget = v_uint64() self.InitialStack = v_ptr32() self.StackLimit = v_ptr32() self.KernelStack = v_ptr32() self.ThreadLock = v_uint32() self.WaitRegister = KWAIT_STATUS_REGISTER() self.Running = v_uint8() self.Alerted = v_bytes(size=2) # FIXME Unknown Array Type self.KernelStackResident = v_uint32() self.ApcState = KAPC_STATE() self.NextProcessor = v_uint32() self.DeferredProcessor = v_uint32() self.ApcQueueLock = v_uint32() self.ContextSwitches = v_uint32() self.State = v_uint8() self.NpxState = v_uint8() self.WaitIrql = v_uint8() self.WaitMode = v_uint8() self.WaitStatus = v_uint32() self.WaitBlockList = v_ptr32() self.WaitListEntry = LIST_ENTRY() self.Queue = v_ptr32() self.WaitTime = v_uint32() self.KernelApcDisable = v_uint16() self.SpecialApcDisable = v_uint16() self.Teb = v_ptr32() self._pad0090 = v_bytes(size=4) self.Timer = KTIMER() self.AutoAlignment = v_uint32() self.ServiceTable = v_ptr32() self.WaitBlock = v_ptr32() self.QueueListEntry = LIST_ENTRY() self.TrapFrame = v_ptr32() self.FirstArgument = v_ptr32() self.CallbackStack = v_ptr32() self.ApcStateIndex = v_uint8() self.BasePriority = v_uint8() self.PriorityDecrement = v_uint8() self.Preempted = v_uint8() self.AdjustReason = v_uint8() self.AdjustIncrement = v_uint8() self.PreviousMode = v_uint8() self.Saturation = v_uint8() self.SystemCallNumber = v_uint32() self.FreezeCount = v_uint32() self.UserAffinity = GROUP_AFFINITY() self.Process = v_ptr32() self.Affinity = GROUP_AFFINITY() self.IdealProcessor = v_uint32() self.UserIdealProcessor = v_uint32() self.ApcStatePointer = v_bytes(size=8) # FIXME Unknown Array Type self.SavedApcState = KAPC_STATE() self.SuspendCount = v_uint8() self.Spare1 = v_uint8() self.OtherPlatformFill = v_uint8() self._pad018c = v_bytes(size=1) self.Win32Thread = v_ptr32() self.StackBase = v_ptr32() self.SuspendApc = KAPC() self.UserTime = v_uint32() self.SuspendSemaphore = KSEMAPHORE() self.SListFaultCount = v_uint32() self.ThreadListEntry = LIST_ENTRY() self.MutantListHead = LIST_ENTRY() self.SListFaultAddress = v_ptr32() self.ThreadCounters = v_ptr32() self.XStateSave = v_ptr32() class CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFlags = v_uint32() self.Dr0 = v_uint32() self.Dr1 = v_uint32() self.Dr2 = v_uint32() self.Dr3 = v_uint32() self.Dr6 = v_uint32() self.Dr7 = v_uint32() self.FloatSave = FLOATING_SAVE_AREA() self.SegGs = v_uint32() self.SegFs = v_uint32() self.SegEs = v_uint32() self.SegDs = v_uint32() self.Edi = v_uint32() self.Esi = v_uint32() self.Ebx = v_uint32() self.Edx = v_uint32() self.Ecx = v_uint32() self.Eax = v_uint32() self.Ebp = v_uint32() self.Eip = v_uint32() self.SegCs = v_uint32() self.EFlags = v_uint32() self.Esp = v_uint32() self.SegSs = v_uint32() self.ExtendedRegisters = v_bytes(size=512) # FIXME Unknown Array Type class MCI_STATS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MciStats = _unnamed_9074() class _unnamed_9793(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DataSize = v_uint32() self.Reserved1 = v_uint32() self.Reserved2 = v_uint32() class _unnamed_9797(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length40 = v_uint32() class PROC_PERF_LOAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BusyPercentage = v_uint8() self.FrequencyPercentage = v_uint8() class AUX_ACCESS_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegesUsed = v_ptr32() self.GenericMapping = GENERIC_MAPPING() self.AccessesToAudit = v_uint32() self.MaximumAuditMask = v_uint32() self.TransactionId = GUID() self.NewSecurityDescriptor = v_ptr32() self.ExistingSecurityDescriptor = v_ptr32() self.ParentSecurityDescriptor = v_ptr32() self.DeRefSecurityDescriptor = v_ptr32() self.SDLock = v_ptr32() self.AccessReasons = ACCESS_REASONS() class _unnamed_10337(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length64 = v_uint32() self.Alignment64 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class HEAP_LOCAL_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeletedSubSegments = SLIST_HEADER() self.CrtZone = v_ptr32() self.LowFragHeap = v_ptr32() self.Sequence = v_uint32() self._pad0018 = v_bytes(size=4) self.SegmentInfo = v_uint32() class _unnamed_8680(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CriticalSection = RTL_CRITICAL_SECTION() class DPH_BLOCK_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StartStamp = v_uint32() self.Heap = v_ptr32() self.RequestedSize = v_uint32() self.ActualSize = v_uint32() self.FreeQueue = LIST_ENTRY() self.StackTrace = v_ptr32() self.EndStamp = v_uint32() class _unnamed_10308(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinimumVector = v_uint32() self.MaximumVector = v_uint32() self.AffinityPolicy = v_uint16() self.Group = v_uint16() self.PriorityPolicy = v_uint32() self.TargetedProcessors = v_uint32() class PF_KERNEL_GLOBALS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AccessBufferAgeThreshold = v_uint64() self.AccessBufferRef = EX_RUNDOWN_REF() self.AccessBufferExistsEvent = KEVENT() self.AccessBufferMax = v_uint32() self.AccessBufferList = SLIST_HEADER() self.StreamSequenceNumber = v_uint32() self.Flags = v_uint32() self.ScenarioPrefetchCount = v_uint32() class _unnamed_9086(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Address = v_uint64() self.Type = v_uint64() class _unnamed_7851(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceQueueEntry = KDEVICE_QUEUE_ENTRY() self.Thread = v_ptr32() self.AuxiliaryBuffer = v_ptr32() self.ListEntry = LIST_ENTRY() self.CurrentStackLocation = v_ptr32() self.OriginalFileObject = v_ptr32() class EVENT_DATA_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Ptr = v_uint64() self.Size = v_uint32() self.Reserved = v_uint32() class IO_DRIVER_CREATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self._pad0004 = v_bytes(size=2) self.ExtraCreateParameter = v_ptr32() self.DeviceObjectHint = v_ptr32() self.TxnParameters = v_ptr32() class EJOB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Event = KEVENT() self.JobLinks = LIST_ENTRY() self.ProcessListHead = LIST_ENTRY() self.JobLock = ERESOURCE() self.TotalUserTime = LARGE_INTEGER() self.TotalKernelTime = LARGE_INTEGER() self.ThisPeriodTotalUserTime = LARGE_INTEGER() self.ThisPeriodTotalKernelTime = LARGE_INTEGER() self.TotalPageFaultCount = v_uint32() self.TotalProcesses = v_uint32() self.ActiveProcesses = v_uint32() self.TotalTerminatedProcesses = v_uint32() self.PerProcessUserTimeLimit = LARGE_INTEGER() self.PerJobUserTimeLimit = LARGE_INTEGER() self.MinimumWorkingSetSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.LimitFlags = v_uint32() self.ActiveProcessLimit = v_uint32() self.Affinity = KAFFINITY_EX() self.PriorityClass = v_uint8() self._pad00c4 = v_bytes(size=3) self.AccessState = v_ptr32() self.UIRestrictionsClass = v_uint32() self.EndOfJobTimeAction = v_uint32() self.CompletionPort = v_ptr32() self.CompletionKey = v_ptr32() self.SessionId = v_uint32() self.SchedulingClass = v_uint32() self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.OtherOperationCount = v_uint64() self.ReadTransferCount = v_uint64() self.WriteTransferCount = v_uint64() self.OtherTransferCount = v_uint64() self.ProcessMemoryLimit = v_uint32() self.JobMemoryLimit = v_uint32() self.PeakProcessMemoryUsed = v_uint32() self.PeakJobMemoryUsed = v_uint32() self.CurrentJobMemoryUsed = v_uint64() self.MemoryLimitsLock = EX_PUSH_LOCK() self.JobSetLinks = LIST_ENTRY() self.MemberLevel = v_uint32() self.JobFlags = v_uint32() class HANDLE_TRACE_DEBUG_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.RefCount = v_uint32() self.TableSize = v_uint32() self.BitMaskFlags = v_uint32() self.CloseCompactionLock = FAST_MUTEX() self.CurrentStackIndex = v_uint32() self.TraceDb = v_uint32() class KPROCESSOR_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ContextFrame = CONTEXT() self.SpecialRegisters = KSPECIAL_REGISTERS() class KiIoAccessMap(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DirectionMap = v_bytes(size=32) # FIXME Unknown Array Type self.IoMap = v_bytes(size=8196) # FIXME Unknown Array Type class _unnamed_8209(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemContext = v_uint32() self.Type = v_uint32() self.State = POWER_STATE() self.ShutdownType = v_uint32() class KAPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.SpareByte0 = v_uint8() self.Size = v_uint8() self.SpareByte1 = v_uint8() self.SpareLong0 = v_uint32() self.Thread = v_ptr32() self.ApcListEntry = LIST_ENTRY() self.KernelRoutine = v_ptr32() self.RundownRoutine = v_ptr32() self.NormalRoutine = v_ptr32() self.NormalContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.ApcStateIndex = v_uint8() self.ApcMode = v_uint8() self.Inserted = v_uint8() class _unnamed_6579(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Bytes = _unnamed_9134() class RTL_STACK_DATABASE_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = RTL_SRWLOCK() class SID_IDENTIFIER_AUTHORITY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Value = v_bytes(size=6) # FIXME Unknown Array Type class XSTATE_FEATURE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint32() self.Size = v_uint32() class WHEA_TIMESTAMP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Seconds = v_uint64() class ACTIVATION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class RTL_CRITICAL_SECTION_DEBUG(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.CriticalSection = v_ptr32() self.ProcessLocksList = LIST_ENTRY() self.EntryCount = v_uint32() self.ContentionCount = v_uint32() self.Flags = v_uint32() self.CreatorBackTraceIndexHigh = v_uint16() self.SpareUSHORT = v_uint16() class DISPATCHER_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.TimerControlFlags = v_uint8() self.ThreadControlFlags = v_uint8() self.TimerMiscFlags = v_uint8() self.SignalState = v_uint32() self.WaitListHead = LIST_ENTRY() class ASSEMBLY_STORAGE_MAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class _unnamed_9134(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseMid = v_uint8() self.Flags1 = v_uint8() self.Flags2 = v_uint8() self.BaseHi = v_uint8() class PROCESSOR_POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdleStates = v_ptr32() self._pad0008 = v_bytes(size=4) self.IdleTimeLast = v_uint64() self.IdleTimeTotal = v_uint64() self.IdleTimeEntry = v_uint64() self.IdleAccounting = v_ptr32() self.Hypervisor = v_uint32() self.PerfHistoryTotal = v_uint32() self.ThermalConstraint = v_uint8() self.PerfHistoryCount = v_uint8() self.PerfHistorySlot = v_uint8() self.Reserved = v_uint8() self.LastSysTime = v_uint32() self.WmiDispatchPtr = v_uint32() self.WmiInterfaceEnabled = v_uint32() self._pad0040 = v_bytes(size=4) self.FFHThrottleStateInfo = PPM_FFH_THROTTLE_STATE_INFO() self.PerfActionDpc = KDPC() self.PerfActionMask = v_uint32() self._pad0088 = v_bytes(size=4) self.IdleCheck = PROC_IDLE_SNAP() self.PerfCheck = PROC_IDLE_SNAP() self.Domain = v_ptr32() self.PerfConstraint = v_ptr32() self.Load = v_ptr32() self.PerfHistory = v_ptr32() self.Utility = v_uint32() self.OverUtilizedHistory = v_uint32() self.AffinityCount = v_uint32() self.AffinityHistory = v_uint32() class _unnamed_8055(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.StartSid = v_ptr32() self.SidList = v_ptr32() self.SidListLength = v_uint32() class POWER_SEQUENCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SequenceD1 = v_uint32() self.SequenceD2 = v_uint32() self.SequenceD3 = v_uint32() class DPH_HEAP_ROOT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.HeapFlags = v_uint32() self.HeapCritSect = v_ptr32() self.nRemoteLockAcquired = v_uint32() self.pVirtualStorageListHead = v_ptr32() self.pVirtualStorageListTail = v_ptr32() self.nVirtualStorageRanges = v_uint32() self.nVirtualStorageBytes = v_uint32() self.BusyNodesTable = RTL_AVL_TABLE() self.NodeToAllocate = v_ptr32() self.nBusyAllocations = v_uint32() self.nBusyAllocationBytesCommitted = v_uint32() self.pFreeAllocationListHead = v_ptr32() self.pFreeAllocationListTail = v_ptr32() self.nFreeAllocations = v_uint32() self.nFreeAllocationBytesCommitted = v_uint32() self.AvailableAllocationHead = LIST_ENTRY() self.nAvailableAllocations = v_uint32() self.nAvailableAllocationBytesCommitted = v_uint32() self.pUnusedNodeListHead = v_ptr32() self.pUnusedNodeListTail = v_ptr32() self.nUnusedNodes = v_uint32() self.nBusyAllocationBytesAccessible = v_uint32() self.pNodePoolListHead = v_ptr32() self.pNodePoolListTail = v_ptr32() self.nNodePools = v_uint32() self.nNodePoolBytes = v_uint32() self.NextHeap = LIST_ENTRY() self.ExtraFlags = v_uint32() self.Seed = v_uint32() self.NormalHeap = v_ptr32() self.CreateStackTrace = v_ptr32() self.FirstThread = v_ptr32() class JOB_ACCESS_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class SECURITY_QUALITY_OF_SERVICE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.ImpersonationLevel = v_uint32() self.ContextTrackingMode = v_uint8() self.EffectiveOnly = v_uint8() class COMPRESSED_DATA_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CompressionFormatAndEngine = v_uint16() self.CompressionUnitShift = v_uint8() self.ChunkShift = v_uint8() self.ClusterShift = v_uint8() self.Reserved = v_uint8() self.NumberOfChunks = v_uint16() self.CompressedChunkSizes = v_bytes(size=4) # FIXME Unknown Array Type class WHEA_ERROR_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = WHEA_ERROR_RECORD_HEADER() self.SectionDescriptor = WHEA_ERROR_RECORD_HEADER() class PS_PER_CPU_QUOTA_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SortedListEntry = LIST_ENTRY() self.IdleOnlyListHead = LIST_ENTRY() self.CycleBaseAllowance = v_uint64() self.CyclesRemaining = v_uint64() self.CurrentGeneration = v_uint32() class PROC_PERF_CONSTRAINT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Prcb = v_ptr32() self.PerfContext = v_uint32() self.PercentageCap = v_uint32() self.ThermalCap = v_uint32() self.TargetFrequency = v_uint32() self.AcumulatedFullFrequency = v_uint32() self.AcumulatedZeroFrequency = v_uint32() self.FrequencyHistoryTotal = v_uint32() self.AverageFrequency = v_uint32() class LUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class CLIENT_ID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UniqueProcess = v_ptr32() self.UniqueThread = v_ptr32() class RTL_STACK_TRACE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashChain = RTL_STD_LIST_ENTRY() self.TraceCount = v_uint16() self.IndexHigh = v_uint16() self.Index = v_uint16() self.Depth = v_uint16() self.BackTrace = v_bytes(size=128) # FIXME Unknown Array Type class OBJECT_DUMP_CONTROL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Stream = v_ptr32() self.Detail = v_uint32() class HANDLE_TRACE_DB_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientId = CLIENT_ID() self.Handle = v_ptr32() self.Type = v_uint32() self.StackTrace = v_bytes(size=64) # FIXME Unknown Array Type class GENERAL_LOOKASIDE_POOL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.AllocateEx = v_ptr32() self.FreeEx = v_ptr32() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class HARDWARE_PTE_X86(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Valid = v_uint32() class RTL_SRWLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locked = v_uint32() class HEAP_TAG_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Allocs = v_uint32() self.Frees = v_uint32() self.Size = v_uint32() self.TagIndex = v_uint16() self.CreatorBackTraceIndex = v_uint16() self.TagName = v_bytes(size=48) # FIXME Unknown Array Type class STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class TP_POOL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class LIST_ENTRY32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint32() self.Blink = v_uint32() class SINGLE_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() class _unnamed_7812(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Create = _unnamed_7874() class PPM_FFH_THROTTLE_STATE_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EnableLogging = v_uint8() self._pad0004 = v_bytes(size=3) self.MismatchCount = v_uint32() self.Initialized = v_uint8() self._pad0010 = v_bytes(size=7) self.LastValue = v_uint64() self.LastLogTickCount = LARGE_INTEGER() class KDEVICE_QUEUE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceListEntry = LIST_ENTRY() self.SortKey = v_uint32() self.Inserted = v_uint8() class _unnamed_8027(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityInformation = v_uint32() self.Length = v_uint32() class CACHED_KSTACK_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SListHead = SLIST_HEADER() self.MinimumFree = v_uint32() self.Misses = v_uint32() self.MissesLast = v_uint32() self.Pad0 = v_uint32() class HEAP_FAILURE_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint32() self.StructureSize = v_uint32() self.FailureType = v_uint32() self.HeapAddress = v_ptr32() self.Address = v_ptr32() self.Param1 = v_ptr32() self.Param2 = v_ptr32() self.Param3 = v_ptr32() self.PreviousBlock = v_ptr32() self.NextBlock = v_ptr32() self.ExpectedEncodedEntry = HEAP_ENTRY() self.ExpectedDecodedEntry = HEAP_ENTRY() self.StackTrace = v_bytes(size=128) # FIXME Unknown Array Type class _unnamed_9370(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AsULONG = v_uint32() class EX_FAST_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Object = v_ptr32() class INTERLOCK_SEQ(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Depth = v_uint16() self.FreeEntryOffset = v_uint16() self.Sequence = v_uint32() class KSPIN_LOCK_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Lock = v_ptr32() class WHEA_ERROR_PACKET_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PreviousError = v_uint32() class FS_FILTER_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfFsFilterCallbacks = v_uint32() self.Reserved = v_uint32() self.PreAcquireForSectionSynchronization = v_ptr32() self.PostAcquireForSectionSynchronization = v_ptr32() self.PreReleaseForSectionSynchronization = v_ptr32() self.PostReleaseForSectionSynchronization = v_ptr32() self.PreAcquireForCcFlush = v_ptr32() self.PostAcquireForCcFlush = v_ptr32() self.PreReleaseForCcFlush = v_ptr32() self.PostReleaseForCcFlush = v_ptr32() self.PreAcquireForModifiedPageWriter = v_ptr32() self.PostAcquireForModifiedPageWriter = v_ptr32() self.PreReleaseForModifiedPageWriter = v_ptr32() self.PostReleaseForModifiedPageWriter = v_ptr32() class _unnamed_10298(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Alignment = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class MM_DRIVER_VERIFIER_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint32() self.RaiseIrqls = v_uint32() self.AcquireSpinLocks = v_uint32() self.SynchronizeExecutions = v_uint32() self.AllocationsAttempted = v_uint32() self.AllocationsSucceeded = v_uint32() self.AllocationsSucceededSpecialPool = v_uint32() self.AllocationsWithNoTag = v_uint32() self.TrimRequests = v_uint32() self.Trims = v_uint32() self.AllocationsFailed = v_uint32() self.AllocationsFailedDeliberately = v_uint32() self.Loads = v_uint32() self.Unloads = v_uint32() self.UnTrackedPool = v_uint32() self.UserTrims = v_uint32() self.CurrentPagedPoolAllocations = v_uint32() self.CurrentNonPagedPoolAllocations = v_uint32() self.PeakPagedPoolAllocations = v_uint32() self.PeakNonPagedPoolAllocations = v_uint32() self.PagedBytes = v_uint32() self.NonPagedBytes = v_uint32() self.PeakPagedBytes = v_uint32() self.PeakNonPagedBytes = v_uint32() self.BurstAllocationsFailedDeliberately = v_uint32() self.SessionTrims = v_uint32() self.OptionChanges = v_uint32() self.VerifyMode = v_uint32() self.PreviousBucketName = UNICODE_STRING() self.ActivityCounter = v_uint32() self.PreviousActivityCounter = v_uint32() self.WorkerTrimRequests = v_uint32() class IO_RESOURCE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Option = v_uint8() self.Type = v_uint8() self.ShareDisposition = v_uint8() self.Spare1 = v_uint8() self.Flags = v_uint16() self.Spare2 = v_uint16() self.u = _unnamed_9722() class EX_PUSH_LOCK_CACHE_AWARE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locks = v_bytes(size=128) # FIXME Unknown Array Type class RTL_TRACE_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint32() self.Count = v_uint32() self.Size = v_uint32() self.UserCount = v_uint32() self.UserSize = v_uint32() self.UserContext = v_ptr32() self.Next = v_ptr32() self.Trace = v_ptr32() class IMAGE_OPTIONAL_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Magic = v_uint16() self.MajorLinkerVersion = v_uint8() self.MinorLinkerVersion = v_uint8() self.SizeOfCode = v_uint32() self.SizeOfInitializedData = v_uint32() self.SizeOfUninitializedData = v_uint32() self.AddressOfEntryPoint = v_uint32() self.BaseOfCode = v_uint32() self.BaseOfData = v_uint32() self.ImageBase = v_uint32() self.SectionAlignment = v_uint32() self.FileAlignment = v_uint32() self.MajorOperatingSystemVersion = v_uint16() self.MinorOperatingSystemVersion = v_uint16() self.MajorImageVersion = v_uint16() self.MinorImageVersion = v_uint16() self.MajorSubsystemVersion = v_uint16() self.MinorSubsystemVersion = v_uint16() self.Win32VersionValue = v_uint32() self.SizeOfImage = v_uint32() self.SizeOfHeaders = v_uint32() self.CheckSum = v_uint32() self.Subsystem = v_uint16() self.DllCharacteristics = v_uint16() self.SizeOfStackReserve = v_uint32() self.SizeOfStackCommit = v_uint32() self.SizeOfHeapReserve = v_uint32() self.SizeOfHeapCommit = v_uint32() self.LoaderFlags = v_uint32() self.NumberOfRvaAndSizes = v_uint32() self.DataDirectory = v_uint32() class SCSI_REQUEST_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class ETHREAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Tcb = KTHREAD() self.CreateTime = LARGE_INTEGER() self.ExitTime = LARGE_INTEGER() self.ExitStatus = v_uint32() self.PostBlockList = LIST_ENTRY() self.TerminationPort = v_ptr32() self.ActiveTimerListLock = v_uint32() self.ActiveTimerListHead = LIST_ENTRY() self.Cid = CLIENT_ID() self.KeyedWaitSemaphore = KSEMAPHORE() self.ClientSecurity = PS_CLIENT_SECURITY_CONTEXT() self.IrpList = LIST_ENTRY() self.TopLevelIrp = v_uint32() self.DeviceToVerify = v_ptr32() self.CpuQuotaApc = v_ptr32() self.Win32StartAddress = v_ptr32() self.LegacyPowerObject = v_ptr32() self.ThreadListEntry = LIST_ENTRY() self.RundownProtect = EX_RUNDOWN_REF() self.ThreadLock = EX_PUSH_LOCK() self.ReadClusterSize = v_uint32() self.MmLockOrdering = v_uint32() self.CrossThreadFlags = v_uint32() self.SameThreadPassiveFlags = v_uint32() self.SameThreadApcFlags = v_uint32() self.CacheManagerActive = v_uint8() self.DisablePageFaultClustering = v_uint8() self.ActiveFaultCount = v_uint8() self.LockOrderState = v_uint8() self.AlpcMessageId = v_uint32() self.AlpcMessage = v_ptr32() self.AlpcWaitListEntry = LIST_ENTRY() self.CacheManagerCount = v_uint32() self.IoBoostCount = v_uint32() self.IrpListLock = v_uint32() self.ReservedForSynchTracking = v_ptr32() self.CmCallbackListHead = SINGLE_LIST_ENTRY() class FAST_MUTEX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Owner = v_ptr32() self.Contention = v_uint32() self.Event = KEVENT() self.OldIrql = v_uint32() class WHEA_ERROR_RECORD_HEADER_VALIDBITS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PlatformId = v_uint32() class KDEVICE_QUEUE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceListHead = LIST_ENTRY() self.Lock = v_uint32() self.Busy = v_uint8() class _unnamed_8156(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DeviceTextType = v_uint32() self.LocaleId = v_uint32() class _unnamed_8151(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IdType = v_uint32() class IO_SECURITY_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityQos = v_ptr32() self.AccessState = v_ptr32() self.DesiredAccess = v_uint32() self.FullCreateOptions = v_uint32() class TERMINATION_PORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Port = v_ptr32() class PROC_HISTORY_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Utility = v_uint16() self.Frequency = v_uint8() self.Reserved = v_uint8() class IO_CLIENT_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextExtension = v_ptr32() self.ClientIdentificationAddress = v_ptr32() class INITIAL_PRIVILEGE_SET(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PrivilegeCount = v_uint32() self.Control = v_uint32() self.Privilege = v_uint32() class WHEA_ERROR_RECORD_HEADER_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Recovered = v_uint32() class XSTATE_CONFIGURATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EnabledFeatures = v_uint64() self.Size = v_uint32() self.OptimizedSave = v_uint32() self.Features = v_uint32() class KWAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitListEntry = LIST_ENTRY() self.Thread = v_ptr32() self.Object = v_ptr32() self.NextWaitBlock = v_ptr32() self.WaitKey = v_uint16() self.WaitType = v_uint8() self.BlockState = v_uint8() class ACTIVATION_CONTEXT_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class FILE_NETWORK_OPEN_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.FileAttributes = v_uint32() class DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pad = v_uint16() self.Limit = v_uint16() self.Base = v_uint32() class _unnamed_8022(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.OutputBufferLength = v_uint32() self.InputBufferLength = v_uint32() self.IoControlCode = v_uint32() self.Type3InputBuffer = v_ptr32() class HEAP_USERDATA_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SFreeListEntry = SINGLE_LIST_ENTRY() self.Reserved = v_ptr32() self.SizeIndex = v_uint32() self.Signature = v_uint32() class RTL_DRIVE_LETTER_CURDIR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint16() self.Length = v_uint16() self.TimeStamp = v_uint32() self.DosPath = STRING() class CACHE_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Level = v_uint8() self.Associativity = v_uint8() self.LineSize = v_uint16() self.Size = v_uint32() self.Type = v_uint32() class ULARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class TEB_ACTIVE_FRAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.Previous = v_ptr32() self.Context = v_ptr32() class GENERAL_LOOKASIDE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListHead = SLIST_HEADER() self.Depth = v_uint16() self.MaximumDepth = v_uint16() self.TotalAllocates = v_uint32() self.AllocateMisses = v_uint32() self.TotalFrees = v_uint32() self.FreeMisses = v_uint32() self.Type = v_uint32() self.Tag = v_uint32() self.Size = v_uint32() self.AllocateEx = v_ptr32() self.FreeEx = v_ptr32() self.ListEntry = LIST_ENTRY() self.LastTotalAllocates = v_uint32() self.LastAllocateMisses = v_uint32() self.Future = v_bytes(size=8) # FIXME Unknown Array Type class _unnamed_7775(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AsynchronousParameters = _unnamed_7790() class KWAIT_STATUS_REGISTER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint8() class KGDTENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LimitLow = v_uint16() self.BaseLow = v_uint16() self.HighWord = _unnamed_6579() class NAMED_PIPE_CREATE_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NamedPipeType = v_uint32() self.ReadMode = v_uint32() self.CompletionMode = v_uint32() self.MaximumInstances = v_uint32() self.InboundQuota = v_uint32() self.OutboundQuota = v_uint32() self.DefaultTimeout = LARGE_INTEGER() self.TimeoutSpecified = v_uint8() class NT_TIB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionList = v_ptr32() self.StackBase = v_ptr32() self.StackLimit = v_ptr32() self.SubSystemTib = v_ptr32() self.FiberData = v_ptr32() self.ArbitraryUserPointer = v_ptr32() self.Self = v_ptr32() class _unnamed_10315(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinimumChannel = v_uint32() self.MaximumChannel = v_uint32() class RTL_STD_LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() class POWER_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemState = v_uint32() class UNICODE_STRING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.MaximumLength = v_uint16() self.Buffer = v_ptr32() class HEAP_LIST_LOOKUP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExtendedLookup = v_ptr32() self.ArraySize = v_uint32() self.ExtraItem = v_uint32() self.ItemCount = v_uint32() self.OutOfRangeItems = v_uint32() self.BaseIndex = v_uint32() self.ListHead = v_ptr32() self.ListsInUseUlong = v_ptr32() self.ListHints = v_ptr32() class _unnamed_5755(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class EPROCESS_QUOTA_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class _unnamed_10318(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.MinBusNumber = v_uint32() self.MaxBusNumber = v_uint32() self.Reserved = v_uint32() class HEAP_DEBUGGING_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterceptorFunction = v_ptr32() self.InterceptorValue = v_uint16() self._pad0008 = v_bytes(size=2) self.ExtendedOptions = v_uint32() self.StackTraceDepth = v_uint32() self.MinTotalBlockSize = v_uint32() self.MaxTotalBlockSize = v_uint32() self.HeapLeakEnumerationRoutine = v_ptr32() class ACCESS_REASONS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data = v_bytes(size=128) # FIXME Unknown Array Type class STACK_TRACE_DATABASE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved = v_bytes(size=56) # FIXME Unknown Array Type self.Reserved2 = v_ptr32() self.PeakHashCollisionListLength = v_uint32() self.LowerMemoryStart = v_ptr32() self.PreCommitted = v_uint8() self.DumpInProgress = v_uint8() self._pad0048 = v_bytes(size=2) self.CommitBase = v_ptr32() self.CurrentLowerCommitLimit = v_ptr32() self.CurrentUpperCommitLimit = v_ptr32() self.NextFreeLowerMemory = v_ptr32() self.NextFreeUpperMemory = v_ptr32() self.NumberOfEntriesLookedUp = v_uint32() self.NumberOfEntriesAdded = v_uint32() self.EntryIndexArray = v_ptr32() self.NumberOfEntriesAllocated = v_uint32() self.NumberOfEntriesAvailable = v_uint32() self.NumberOfAllocationFailures = v_uint32() self._pad0078 = v_bytes(size=4) self.FreeLists = v_uint32() self.NumberOfBuckets = v_uint32() self.Buckets = v_uint32() class _unnamed_9139(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BaseMid = v_uint32() class KDPC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint8() self.Importance = v_uint8() self.Number = v_uint16() self.DpcListEntry = LIST_ENTRY() self.DeferredRoutine = v_ptr32() self.DeferredContext = v_ptr32() self.SystemArgument1 = v_ptr32() self.SystemArgument2 = v_ptr32() self.DpcData = v_ptr32() class KEVENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class KSEMAPHORE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() self.Limit = v_uint32() class MM_PAGE_ACCESS_INFO_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Link = SINGLE_LIST_ENTRY() self.Type = v_uint32() self.EmptySequenceNumber = v_uint32() self._pad0010 = v_bytes(size=4) self.CreateTime = v_uint64() self.EmptyTime = v_uint64() self.PageEntry = v_ptr32() self.FileEntry = v_ptr32() self.FirstFileEntry = v_ptr32() self.Process = v_ptr32() self.SessionId = v_uint32() class OBJECT_TYPE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TypeList = LIST_ENTRY() self.Name = UNICODE_STRING() self.DefaultObject = v_ptr32() self.Index = v_uint8() self._pad0018 = v_bytes(size=3) self.TotalNumberOfObjects = v_uint32() self.TotalNumberOfHandles = v_uint32() self.HighWaterNumberOfObjects = v_uint32() self.HighWaterNumberOfHandles = v_uint32() self.TypeInfo = OBJECT_TYPE_INITIALIZER() self.TypeLock = EX_PUSH_LOCK() self.Key = v_uint32() self.CallbackList = LIST_ENTRY() class HANDLE_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TableCode = v_uint32() self.QuotaProcess = v_ptr32() self.UniqueProcessId = v_ptr32() self.HandleLock = EX_PUSH_LOCK() self.HandleTableList = LIST_ENTRY() self.HandleContentionEvent = EX_PUSH_LOCK() self.DebugInfo = v_ptr32() self.ExtraInfoPages = v_uint32() self.Flags = v_uint32() self.FirstFreeHandle = v_uint32() self.LastFreeHandleEntry = v_ptr32() self.HandleCount = v_uint32() self.NextHandleNeedingPool = v_uint32() self.HandleCountHighWatermark = v_uint32() class MMSUPPORT_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WorkingSetType = v_uint8() self.SessionMaster = v_uint8() self.MemoryPriority = v_uint8() self.WsleDeleted = v_uint8() class HEAP_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = _unnamed_8680() class EXCEPTION_REGISTRATION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Handler = v_ptr32() class FILE_BASIC_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CreationTime = LARGE_INTEGER() self.LastAccessTime = LARGE_INTEGER() self.LastWriteTime = LARGE_INTEGER() self.ChangeTime = LARGE_INTEGER() self.FileAttributes = v_uint32() class LIST_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_ptr32() self.Blink = v_ptr32() class M128A(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Low = v_uint64() self.High = v_uint64() class _unnamed_5801(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LongFunction = v_uint32() class RTL_DYNAMIC_HASH_TABLE_ENUMERATOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HashEntry = RTL_DYNAMIC_HASH_TABLE_ENTRY() self.ChainHead = v_ptr32() self.BucketIndex = v_uint32() class _unnamed_8069(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() class GUID(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data1 = v_uint32() self.Data2 = v_uint16() self.Data3 = v_uint16() self.Data4 = v_bytes(size=8) # FIXME Unknown Array Type class HEAP_UCR_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.SegmentEntry = LIST_ENTRY() self.Address = v_ptr32() self.Size = v_uint32() class MCA_EXCEPTION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VersionNumber = v_uint32() self.ExceptionType = v_uint32() self.TimeStamp = LARGE_INTEGER() self.ProcessorNumber = v_uint32() self.Reserved1 = v_uint32() self.u = _unnamed_9067() self.ExtCnt = v_uint32() self.Reserved3 = v_uint32() self.ExtReg = v_bytes(size=192) # FIXME Unknown Array Type class PSP_CPU_QUOTA_APC(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class KAPC_STATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ApcListHead = v_bytes(size=192) # FIXME Unknown Array Type self.Process = v_ptr32() self.KernelApcInProgress = v_uint8() self.KernelApcPending = v_uint8() self.UserApcPending = v_uint8() class COUNTER_READING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint32() self.Index = v_uint32() self.Start = v_uint64() self.Total = v_uint64() class KDPC_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DpcListHead = LIST_ENTRY() self.DpcLock = v_uint32() self.DpcQueueDepth = v_uint32() self.DpcCount = v_uint32() class KIDTENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Offset = v_uint16() self.Selector = v_uint16() self.Access = v_uint16() self.ExtendedOffset = v_uint16() class XSAVE_AREA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LegacyState = XSAVE_FORMAT() self.Header = XSAVE_AREA_HEADER() class GENERIC_MAPPING(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GenericRead = v_uint32() self.GenericWrite = v_uint32() self.GenericExecute = v_uint32() self.GenericAll = v_uint32() class IRP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.MdlAddress = v_ptr32() self.Flags = v_uint32() self.AssociatedIrp = _unnamed_7772() self.ThreadListEntry = LIST_ENTRY() self.IoStatus = IO_STATUS_BLOCK() self.RequestorMode = v_uint8() self.PendingReturned = v_uint8() self.StackCount = v_uint8() self.CurrentLocation = v_uint8() self.Cancel = v_uint8() self.CancelIrql = v_uint8() self.ApcEnvironment = v_uint8() self.AllocationFlags = v_uint8() self.UserIosb = v_ptr32() self.UserEvent = v_ptr32() self.Overlay = _unnamed_7775() self.CancelRoutine = v_ptr32() self.UserBuffer = v_ptr32() self.Tail = _unnamed_7778() class KTHREAD_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitReasonBitMap = v_uint64() self.UserData = v_ptr32() self.Flags = v_uint32() self.ContextSwitches = v_uint32() self._pad0018 = v_bytes(size=4) self.CycleTimeBias = v_uint64() self.HardwareCounters = v_uint64() self.HwCounter = v_uint64() class _unnamed_9767(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Start = LARGE_INTEGER() self.Length = v_uint32() class DRIVER_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Flags = v_uint32() self.DriverStart = v_ptr32() self.DriverSize = v_uint32() self.DriverSection = v_ptr32() self.DriverExtension = v_ptr32() self.DriverName = UNICODE_STRING() self.HardwareDatabase = v_ptr32() self.FastIoDispatch = v_ptr32() self.DriverInit = v_ptr32() self.DriverStartIo = v_ptr32() self.DriverUnload = v_ptr32() self.MajorFunction = v_bytes(size=112) # FIXME Unknown Array Type class FILE_GET_QUOTA_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NextEntryOffset = v_uint32() self.SidLength = v_uint32() self.Sid = SID() class KGATE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Header = DISPATCHER_HEADER() class IO_COMPLETION_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = v_ptr32() self.Key = v_ptr32() class DRIVER_EXTENSION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.DriverObject = v_ptr32() self.AddDevice = v_ptr32() self.Count = v_uint32() self.ServiceKeyName = UNICODE_STRING() self.ClientDriverExtension = v_ptr32() self.FsFilterCallbacks = v_ptr32() class TP_NBQ_GUARD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.GuardLinks = LIST_ENTRY() self.Guards = v_bytes(size=8) # FIXME Unknown Array Type class flags(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Removable = v_uint8() class MM_AVL_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BalancedRoot = MMADDRESS_NODE() self.DepthOfTree = v_uint32() self.NodeHint = v_ptr32() self.NodeFreeHint = v_ptr32() class WHEA_PERSISTENCE_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint64() class _unnamed_9547(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Generic = _unnamed_9767() class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FRUId = v_uint8() class EXCEPTION_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExceptionCode = v_uint32() self.ExceptionFlags = v_uint32() self.ExceptionRecord = v_ptr32() self.ExceptionAddress = v_ptr32() self.NumberParameters = v_uint32() self.ExceptionInformation = v_bytes(size=60) # FIXME Unknown Array Type class PROCESSOR_NUMBER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Group = v_uint16() self.Number = v_uint8() self.Reserved = v_uint8() class MM_PAGE_ACCESS_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = MM_PAGE_ACCESS_INFO_FLAGS() self.PointerProtoPte = v_ptr32() class _unnamed_7772(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MasterIrp = v_ptr32() class KPCR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.SelfPcr = v_ptr32() self.Prcb = v_ptr32() self.Irql = v_uint8() self._pad0028 = v_bytes(size=3) self.IRR = v_uint32() self.IrrActive = v_uint32() self.IDR = v_uint32() self.KdVersionBlock = v_ptr32() self.IDT = v_ptr32() self.GDT = v_ptr32() self.TSS = v_ptr32() self.MajorVersion = v_uint16() self.MinorVersion = v_uint16() self.SetMember = v_uint32() self.StallScaleFactor = v_uint32() self.SpareUnused = v_uint8() self.Number = v_uint8() self.Spare0 = v_uint8() self.SecondLevelCacheAssociativity = v_uint8() self.VdmAlert = v_uint32() self.KernelReserved = v_bytes(size=56) # FIXME Unknown Array Type self.SecondLevelCacheSize = v_uint32() self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.InterruptMode = v_uint32() self.Spare1 = v_uint8() self._pad00dc = v_bytes(size=3) self.KernelReserved2 = v_bytes(size=68) # FIXME Unknown Array Type self.PrcbData = KPRCB() class IMAGE_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Machine = v_uint16() self.NumberOfSections = v_uint16() self.TimeDateStamp = v_uint32() self.PointerToSymbolTable = v_uint32() self.NumberOfSymbols = v_uint32() self.SizeOfOptionalHeader = v_uint16() self.Characteristics = v_uint16() class LFH_BLOCK_ZONE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() self.FreePointer = v_ptr32() self.Limit = v_ptr32() class _unnamed_7778(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Overlay = _unnamed_7851() class FILE_STANDARD_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocationSize = LARGE_INTEGER() self.EndOfFile = LARGE_INTEGER() self.NumberOfLinks = v_uint32() self.DeletePending = v_uint8() self.Directory = v_uint8() class LFH_HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = RTL_CRITICAL_SECTION() self.SubSegmentZones = LIST_ENTRY() self.ZoneBlockSize = v_uint32() self.Heap = v_ptr32() self.SegmentChange = v_uint32() self.SegmentCreate = v_uint32() self.SegmentInsertInFree = v_uint32() self.SegmentDelete = v_uint32() self.CacheAllocs = v_uint32() self.CacheFrees = v_uint32() self.SizeInCache = v_uint32() self._pad0048 = v_bytes(size=4) self.RunInfo = HEAP_BUCKET_RUN_INFO() self.UserBlockCache = HEAP_BUCKET_RUN_INFO() self.Buckets = HEAP_BUCKET_RUN_INFO() self.LocalData = HEAP_BUCKET_RUN_INFO() class _unnamed_7982(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.FileInformationClass = v_uint32() self.FileObject = v_ptr32() self.ReplaceIfExists = v_uint8() self.AdvanceOnly = v_uint8() class HEAP_BUCKET_RUN_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Bucket = v_uint32() self.RunLength = v_uint32() class PEB_LDR_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.Initialized = v_uint8() self._pad0008 = v_bytes(size=3) self.SsHandle = v_ptr32() self.InLoadOrderModuleList = LIST_ENTRY() self.InMemoryOrderModuleList = LIST_ENTRY() self.InInitializationOrderModuleList = LIST_ENTRY() self.EntryInProgress = v_ptr32() self.ShutdownInProgress = v_uint8() self._pad002c = v_bytes(size=3) self.ShutdownThreadId = v_ptr32() class _unnamed_5768(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class HEAP_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Flags = v_uint8() self.SmallTagIndex = v_uint8() self.PreviousSize = v_uint16() self.SegmentOffset = v_uint8() self.UnusedBytes = v_uint8() class MM_PAGE_ACCESS_INFO_FLAGS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.File = _unnamed_8980() class SECURITY_SUBJECT_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ClientToken = v_ptr32() self.ImpersonationLevel = v_uint32() self.PrimaryToken = v_ptr32() self.ProcessAuditId = v_ptr32() class _unnamed_7979(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.FileInformationClass = v_uint32() class _unnamed_10323(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Priority = v_uint32() self.Reserved1 = v_uint32() self.Reserved2 = v_uint32() class _unnamed_10327(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length40 = v_uint32() self.Alignment40 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class _unnamed_7976(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.CompletionFilter = v_uint32() class _unnamed_7970(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint32() self.FileName = v_ptr32() self.FileInformationClass = v_uint32() self.FileIndex = v_uint32() class _unnamed_7874(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityContext = v_ptr32() self.Options = v_uint32() self.FileAttributes = v_uint16() self.ShareAccess = v_uint16() self.EaLength = v_uint32() class INTERFACE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Version = v_uint16() self.Context = v_ptr32() self.InterfaceReference = v_ptr32() self.InterfaceDereference = v_ptr32() class SLIST_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Alignment = v_uint64() class _unnamed_5798(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() class IMAGE_DATA_DIRECTORY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.VirtualAddress = v_uint32() self.Size = v_uint32() class FILE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.DeviceObject = v_ptr32() self.Vpb = v_ptr32() self.FsContext = v_ptr32() self.FsContext2 = v_ptr32() self.SectionObjectPointer = v_ptr32() self.PrivateCacheMap = v_ptr32() self.FinalStatus = v_uint32() self.RelatedFileObject = v_ptr32() self.LockOperation = v_uint8() self.DeletePending = v_uint8() self.ReadAccess = v_uint8() self.WriteAccess = v_uint8() self.DeleteAccess = v_uint8() self.SharedRead = v_uint8() self.SharedWrite = v_uint8() self.SharedDelete = v_uint8() self.Flags = v_uint32() self.FileName = UNICODE_STRING() self.CurrentByteOffset = LARGE_INTEGER() self.Waiters = v_uint32() self.Busy = v_uint32() self.LastLock = v_ptr32() self.Lock = KEVENT() self.Event = KEVENT() self.CompletionContext = v_ptr32() self.IrpListLock = v_uint32() self.IrpList = LIST_ENTRY() self.FileObjectExtension = v_ptr32() class PPM_IDLE_STATES(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.Flags = _unnamed_9370() self.TargetState = v_uint32() self.ActualState = v_uint32() self.OldState = v_uint32() self.NewlyUnparked = v_uint8() self._pad0018 = v_bytes(size=3) self.TargetProcessors = KAFFINITY_EX() self.State = KAFFINITY_EX() class _unnamed_8142(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Lock = v_uint8() class HEAP_SUBSEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LocalInfo = v_ptr32() self.UserBlocks = v_ptr32() self.AggregateExchg = INTERLOCK_SEQ() self.BlockSize = v_uint16() self.Flags = v_uint16() self.BlockCount = v_uint16() self.SizeIndex = v_uint8() self.AffinityIndex = v_uint8() self.SFreeListEntry = SINGLE_LIST_ENTRY() self.Lock = v_uint32() class ERESOURCE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SystemResourcesList = LIST_ENTRY() self.OwnerTable = v_ptr32() self.ActiveCount = v_uint16() self.Flag = v_uint16() self.SharedWaiters = v_ptr32() self.ExclusiveWaiters = v_ptr32() self.OwnerEntry = OWNER_ENTRY() self.ActiveEntries = v_uint32() self.ContentionCount = v_uint32() self.NumberOfSharedWaiters = v_uint32() self.NumberOfExclusiveWaiters = v_uint32() self.Address = v_ptr32() self.SpinLock = v_uint32() class _unnamed_8220(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AllocatedResources = v_ptr32() self.AllocatedResourcesTranslated = v_ptr32() class _unnamed_8224(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ProviderId = v_uint32() self.DataPath = v_ptr32() self.BufferSize = v_uint32() self.Buffer = v_ptr32() class _unnamed_8229(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Argument1 = v_ptr32() self.Argument2 = v_ptr32() self.Argument3 = v_ptr32() self.Argument4 = v_ptr32() class PEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InheritedAddressSpace = v_uint8() self.ReadImageFileExecOptions = v_uint8() self.BeingDebugged = v_uint8() self.BitField = v_uint8() self.Mutant = v_ptr32() self.ImageBaseAddress = v_ptr32() self.Ldr = v_ptr32() self.ProcessParameters = v_ptr32() self.SubSystemData = v_ptr32() self.ProcessHeap = v_ptr32() self.FastPebLock = v_ptr32() self.AtlThunkSListPtr = v_ptr32() self.IFEOKey = v_ptr32() self.CrossProcessFlags = v_uint32() self.KernelCallbackTable = v_ptr32() self.SystemReserved = v_bytes(size=4) # FIXME Unknown Array Type self.AtlThunkSListPtr32 = v_uint32() self.ApiSetMap = v_ptr32() self.TlsExpansionCounter = v_uint32() self.TlsBitmap = v_ptr32() self.TlsBitmapBits = v_bytes(size=8) # FIXME Unknown Array Type self.ReadOnlySharedMemoryBase = v_ptr32() self.HotpatchInformation = v_ptr32() self.ReadOnlyStaticServerData = v_ptr32() self.AnsiCodePageData = v_ptr32() self.OemCodePageData = v_ptr32() self.UnicodeCaseTableData = v_ptr32() self.NumberOfProcessors = v_uint32() self.NtGlobalFlag = v_uint32() self._pad0070 = v_bytes(size=4) self.CriticalSectionTimeout = LARGE_INTEGER() self.HeapSegmentReserve = v_uint32() self.HeapSegmentCommit = v_uint32() self.HeapDeCommitTotalFreeThreshold = v_uint32() self.HeapDeCommitFreeBlockThreshold = v_uint32() self.NumberOfHeaps = v_uint32() self.MaximumNumberOfHeaps = v_uint32() self.ProcessHeaps = v_ptr32() self.GdiSharedHandleTable = v_ptr32() self.ProcessStarterHelper = v_ptr32() self.GdiDCAttributeList = v_uint32() self.LoaderLock = v_ptr32() self.OSMajorVersion = v_uint32() self.OSMinorVersion = v_uint32() self.OSBuildNumber = v_uint16() self.OSCSDVersion = v_uint16() self.OSPlatformId = v_uint32() self.ImageSubsystem = v_uint32() self.ImageSubsystemMajorVersion = v_uint32() self.ImageSubsystemMinorVersion = v_uint32() self.ActiveProcessAffinityMask = v_uint32() self.GdiHandleBuffer = v_bytes(size=136) # FIXME Unknown Array Type self.PostProcessInitRoutine = v_ptr32() self.TlsExpansionBitmap = v_ptr32() self.TlsExpansionBitmapBits = v_bytes(size=128) # FIXME Unknown Array Type self.SessionId = v_uint32() self.AppCompatFlags = ULARGE_INTEGER() self.AppCompatFlagsUser = ULARGE_INTEGER() self.pShimData = v_ptr32() self.AppCompatInfo = v_ptr32() self.CSDVersion = UNICODE_STRING() self.ActivationContextData = v_ptr32() self.ProcessAssemblyStorageMap = v_ptr32() self.SystemDefaultActivationContextData = v_ptr32() self.SystemAssemblyStorageMap = v_ptr32() self.MinimumStackCommit = v_uint32() self.FlsCallback = v_ptr32() self.FlsListHead = LIST_ENTRY() self.FlsBitmap = v_ptr32() self.FlsBitmapBits = v_bytes(size=16) # FIXME Unknown Array Type self.FlsHighIndex = v_uint32() self.WerRegistrationData = v_ptr32() self.WerShipAssertPtr = v_ptr32() self.pContextData = v_ptr32() self.pImageHeaderHash = v_ptr32() self.TracingFlags = v_uint32() class TP_TASK_CALLBACKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ExecuteCallback = v_ptr32() self.Unposted = v_ptr32() class RTL_BALANCED_LINKS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Parent = v_ptr32() self.LeftChild = v_ptr32() self.RightChild = v_ptr32() self.Balance = v_uint8() self.Reserved = v_bytes(size=3) # FIXME Unknown Array Type class _unnamed_9722(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Port = _unnamed_10298() class EX_PUSH_LOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Locked = v_uint32() class XSTATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mask = v_uint64() self.Length = v_uint32() self.Reserved1 = v_uint32() self.Area = v_ptr32() self.Reserved2 = v_uint32() self.Buffer = v_ptr32() self.Reserved3 = v_uint32() class HEAP_FREE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Size = v_uint16() self.Flags = v_uint8() self.SmallTagIndex = v_uint8() self.PreviousSize = v_uint16() self.SegmentOffset = v_uint8() self.UnusedBytes = v_uint8() self.FreeList = LIST_ENTRY() class KSTACK_COUNT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Value = v_uint32() class _unnamed_8030(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityInformation = v_uint32() self.SecurityDescriptor = v_ptr32() class MDL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Next = v_ptr32() self.Size = v_uint16() self.MdlFlags = v_uint16() self.Process = v_ptr32() self.MappedSystemVa = v_ptr32() self.StartVa = v_ptr32() self.ByteCount = v_uint32() self.ByteOffset = v_uint32() class _unnamed_8134(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.IoResourceRequirementList = v_ptr32() class _unnamed_8137(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WhichSpace = v_uint32() self.Buffer = v_ptr32() self.Offset = v_uint32() self.Length = v_uint32() class HEAP_SEGMENT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.SegmentSignature = v_uint32() self.SegmentFlags = v_uint32() self.SegmentListEntry = LIST_ENTRY() self.Heap = v_ptr32() self.BaseAddress = v_ptr32() self.NumberOfPages = v_uint32() self.FirstEntry = v_ptr32() self.LastValidEntry = v_ptr32() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.SegmentAllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self.UCRSegmentList = LIST_ENTRY() class WHEA_ERROR_RECORD_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.Revision = WHEA_REVISION() self.SignatureEnd = v_uint32() self.SectionCount = v_uint16() self.Severity = v_uint32() self.ValidBits = WHEA_ERROR_RECORD_HEADER_VALIDBITS() self.Length = v_uint32() self.Timestamp = WHEA_TIMESTAMP() self.PlatformId = GUID() self.PartitionId = GUID() self.CreatorId = GUID() self.NotifyType = GUID() self.RecordId = v_uint64() self.Flags = WHEA_ERROR_RECORD_HEADER_FLAGS() self.PersistenceInfo = WHEA_PERSISTENCE_INFO() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type class EVENT_DESCRIPTOR(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Id = v_uint16() self.Version = v_uint8() self.Channel = v_uint8() self.Level = v_uint8() self.Opcode = v_uint8() self.Task = v_uint16() self.Keyword = v_uint64() class _unnamed_9855(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ResourceToRelease = v_ptr32() class _unnamed_9854(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.EndingOffset = v_ptr32() self.ResourceToRelease = v_ptr32() class _unnamed_9857(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NotificationType = v_uint32() self.SafeToRecurse = v_uint8() class MMSUPPORT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WorkingSetMutex = EX_PUSH_LOCK() self.ExitGate = v_ptr32() self.AccessLog = v_ptr32() self.WorkingSetExpansionLinks = LIST_ENTRY() self.AgeDistribution = v_bytes(size=28) # FIXME Unknown Array Type self.MinimumWorkingSetSize = v_uint32() self.WorkingSetSize = v_uint32() self.WorkingSetPrivateSize = v_uint32() self.MaximumWorkingSetSize = v_uint32() self.ChargedWslePages = v_uint32() self.ActualWslePages = v_uint32() self.WorkingSetSizeOverhead = v_uint32() self.PeakWorkingSetSize = v_uint32() self.HardFaultCount = v_uint32() self.VmWorkingSetList = v_ptr32() self.NextPageColor = v_uint16() self.LastTrimStamp = v_uint16() self.PageFaultCount = v_uint32() self.RepurposeCount = v_uint32() self.Spare = v_bytes(size=4) # FIXME Unknown Array Type self.Flags = MMSUPPORT_FLAGS() class _unnamed_9858(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Argument1 = v_ptr32() self.Argument2 = v_ptr32() self.Argument3 = v_ptr32() self.Argument4 = v_ptr32() self.Argument5 = v_ptr32() class FLS_CALLBACK_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) class ACL(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AclRevision = v_uint8() self.Sbz1 = v_uint8() self.AclSize = v_uint16() self.AceCount = v_uint16() self.Sbz2 = v_uint16() class LIST_ENTRY64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flink = v_uint64() self.Blink = v_uint64() class WAIT_CONTEXT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WaitQueueEntry = KDEVICE_QUEUE_ENTRY() self.DeviceRoutine = v_ptr32() self.DeviceContext = v_ptr32() self.NumberOfMapRegisters = v_uint32() self.DeviceObject = v_ptr32() self.CurrentIrp = v_ptr32() self.BufferChainingDpc = v_ptr32() class SE_AUDIT_PROCESS_CREATION_INFO(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ImageFileName = v_ptr32() class ACTIVATION_CONTEXT_STACK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ActiveFrame = v_ptr32() self.FrameListCache = LIST_ENTRY() self.Flags = v_uint32() self.NextCookieSequenceNumber = v_uint32() self.StackId = v_uint32() class LDR_DATA_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InLoadOrderLinks = LIST_ENTRY() self.InMemoryOrderLinks = LIST_ENTRY() self.InInitializationOrderLinks = LIST_ENTRY() self.DllBase = v_ptr32() self.EntryPoint = v_ptr32() self.SizeOfImage = v_uint32() self.FullDllName = UNICODE_STRING() self.BaseDllName = UNICODE_STRING() self.Flags = v_uint32() self.LoadCount = v_uint16() self.TlsIndex = v_uint16() self.HashLinks = LIST_ENTRY() self.TimeDateStamp = v_uint32() self.EntryPointActivationContext = v_ptr32() self.PatchInformation = v_ptr32() self.ForwarderLinks = LIST_ENTRY() self.ServiceTagLinks = LIST_ENTRY() self.StaticLinks = LIST_ENTRY() self.ContextInformation = v_ptr32() self.OriginalBase = v_uint32() self.LoadTime = LARGE_INTEGER() class LOOKASIDE_LIST_EX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE_POOL() class TEB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.NtTib = NT_TIB() self.EnvironmentPointer = v_ptr32() self.ClientId = CLIENT_ID() self.ActiveRpcHandle = v_ptr32() self.ThreadLocalStoragePointer = v_ptr32() self.ProcessEnvironmentBlock = v_ptr32() self.LastErrorValue = v_uint32() self.CountOfOwnedCriticalSections = v_uint32() self.CsrClientThread = v_ptr32() self.Win32ThreadInfo = v_ptr32() self.User32Reserved = v_bytes(size=104) # FIXME Unknown Array Type self.UserReserved = v_bytes(size=20) # FIXME Unknown Array Type self.WOW32Reserved = v_ptr32() self.CurrentLocale = v_uint32() self.FpSoftwareStatusRegister = v_uint32() self.SystemReserved1 = v_bytes(size=216) # FIXME Unknown Array Type self.ExceptionCode = v_uint32() self.ActivationContextStackPointer = v_ptr32() self.SpareBytes = v_bytes(size=36) # FIXME Unknown Array Type self.TxFsContext = v_uint32() self.GdiTebBatch = GDI_TEB_BATCH() self.RealClientId = CLIENT_ID() self.GdiCachedProcessHandle = v_ptr32() self.GdiClientPID = v_uint32() self.GdiClientTID = v_uint32() self.GdiThreadLocalInfo = v_ptr32() self.Win32ClientInfo = v_bytes(size=248) # FIXME Unknown Array Type self.glDispatchTable = v_bytes(size=932) # FIXME Unknown Array Type self.glReserved1 = v_bytes(size=116) # FIXME Unknown Array Type self.glReserved2 = v_ptr32() self.glSectionInfo = v_ptr32() self.glSection = v_ptr32() self.glTable = v_ptr32() self.glCurrentRC = v_ptr32() self.glContext = v_ptr32() self.LastStatusValue = v_uint32() self.StaticUnicodeString = UNICODE_STRING() self.StaticUnicodeBuffer = v_bytes(size=522) # FIXME Unknown Array Type self._pad0e0c = v_bytes(size=2) self.DeallocationStack = v_ptr32() self.TlsSlots = v_bytes(size=256) # FIXME Unknown Array Type self.TlsLinks = LIST_ENTRY() self.Vdm = v_ptr32() self.ReservedForNtRpc = v_ptr32() self.DbgSsReserved = v_bytes(size=8) # FIXME Unknown Array Type self.HardErrorMode = v_uint32() self.Instrumentation = v_bytes(size=36) # FIXME Unknown Array Type self.ActivityId = GUID() self.SubProcessTag = v_ptr32() self.EtwLocalData = v_ptr32() self.EtwTraceData = v_ptr32() self.WinSockData = v_ptr32() self.GdiBatchCount = v_uint32() self.CurrentIdealProcessor = PROCESSOR_NUMBER() self.GuaranteedStackBytes = v_uint32() self.ReservedForPerf = v_ptr32() self.ReservedForOle = v_ptr32() self.WaitingOnLoaderLock = v_uint32() self.SavedPriorityState = v_ptr32() self.SoftPatchPtr1 = v_uint32() self.ThreadPoolData = v_ptr32() self.TlsExpansionSlots = v_ptr32() self.MuiGeneration = v_uint32() self.IsImpersonating = v_uint32() self.NlsCache = v_ptr32() self.pShimData = v_ptr32() self.HeapVirtualAffinity = v_uint32() self.CurrentTransactionHandle = v_ptr32() self.ActiveFrame = v_ptr32() self.FlsData = v_ptr32() self.PreferredLanguages = v_ptr32() self.UserPrefLanguages = v_ptr32() self.MergedPrefLanguages = v_ptr32() self.MuiImpersonation = v_uint32() self.CrossTebFlags = v_uint16() self.SameTebFlags = v_uint16() self.TxnScopeEnterCallback = v_ptr32() self.TxnScopeExitCallback = v_ptr32() self.TxnScopeContext = v_ptr32() self.LockCount = v_uint32() self.SpareUlong0 = v_uint32() self.ResourceRetValue = v_ptr32() class EX_RUNDOWN_REF(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() class XSAVE_FORMAT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ControlWord = v_uint16() self.StatusWord = v_uint16() self.TagWord = v_uint8() self.Reserved1 = v_uint8() self.ErrorOpcode = v_uint16() self.ErrorOffset = v_uint32() self.ErrorSelector = v_uint16() self.Reserved2 = v_uint16() self.DataOffset = v_uint32() self.DataSelector = v_uint16() self.Reserved3 = v_uint16() self.MxCsr = v_uint32() self.MxCsr_Mask = v_uint32() self.FloatRegisters = v_uint32() self.XmmRegisters = v_uint32() self.Reserved4 = v_bytes(size=192) # FIXME Unknown Array Type self.StackControl = v_bytes(size=28) # FIXME Unknown Array Type self.Cr0NpxState = v_uint32() class PO_DIAG_STACK_RECORD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.StackDepth = v_uint32() self.Stack = v_bytes(size=4) # FIXME Unknown Array Type class IMAGE_DOS_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.e_magic = v_uint16() self.e_cblp = v_uint16() self.e_cp = v_uint16() self.e_crlc = v_uint16() self.e_cparhdr = v_uint16() self.e_minalloc = v_uint16() self.e_maxalloc = v_uint16() self.e_ss = v_uint16() self.e_sp = v_uint16() self.e_csum = v_uint16() self.e_ip = v_uint16() self.e_cs = v_uint16() self.e_lfarlc = v_uint16() self.e_ovno = v_uint16() self.e_res = v_bytes(size=8) # FIXME Unknown Array Type self.e_oemid = v_uint16() self.e_oeminfo = v_uint16() self.e_res2 = v_bytes(size=20) # FIXME Unknown Array Type self.e_lfanew = v_uint32() class RTL_DYNAMIC_HASH_TABLE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Linkage = LIST_ENTRY() self.Signature = v_uint32() class MMADDRESS_NODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.u1 = _unnamed_9563() self.LeftChild = v_ptr32() self.RightChild = v_ptr32() self.StartingVpn = v_uint32() self.EndingVpn = v_uint32() class _unnamed_7372(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListEntry = LIST_ENTRY() class TXN_PARAMETER_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length = v_uint16() self.TxFsContext = v_uint16() self.TransactionObject = v_ptr32() class _unnamed_8980(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FilePointerIndex = v_uint32() class _unnamed_8981(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.FilePointerIndex = v_uint32() class QUAD(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UseThisFieldToCopy = v_uint64() class HEAP_TUNING_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CommittThresholdShift = v_uint32() self.MaxPreCommittThreshold = v_uint32() class KPRCB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MinorVersion = v_uint16() self.MajorVersion = v_uint16() self.CurrentThread = v_ptr32() self.NextThread = v_ptr32() self.IdleThread = v_ptr32() self.LegacyNumber = v_uint8() self.NestingLevel = v_uint8() self.BuildType = v_uint16() self.CpuType = v_uint8() self.CpuID = v_uint8() self.CpuStep = v_uint16() self.ProcessorState = KPROCESSOR_STATE() self.KernelReserved = v_bytes(size=64) # FIXME Unknown Array Type self.HalReserved = v_bytes(size=64) # FIXME Unknown Array Type self.CFlushSize = v_uint32() self.CoresPerPhysicalProcessor = v_uint8() self.LogicalProcessorsPerCore = v_uint8() self.PrcbPad0 = v_bytes(size=2) # FIXME Unknown Array Type self.MHz = v_uint32() self.CpuVendor = v_uint8() self.GroupIndex = v_uint8() self.Group = v_uint16() self.GroupSetMember = v_uint32() self.Number = v_uint32() self.PrcbPad1 = v_bytes(size=72) # FIXME Unknown Array Type self.LockQueue = v_bytes(size=72) # FIXME Unknown Array Type self.NpxThread = v_ptr32() self.InterruptCount = v_uint32() self.KernelTime = v_uint32() self.UserTime = v_uint32() self.DpcTime = v_uint32() self.DpcTimeCount = v_uint32() self.InterruptTime = v_uint32() self.AdjustDpcThreshold = v_uint32() self.PageColor = v_uint32() self.DebuggerSavedIRQL = v_uint8() self.NodeColor = v_uint8() self.PrcbPad20 = v_bytes(size=2) # FIXME Unknown Array Type self.NodeShiftedColor = v_uint32() self.ParentNode = v_ptr32() self.SecondaryColorMask = v_uint32() self.DpcTimeLimit = v_uint32() self.PrcbPad21 = v_bytes(size=8) # FIXME Unknown Array Type self.CcFastReadNoWait = v_uint32() self.CcFastReadWait = v_uint32() self.CcFastReadNotPossible = v_uint32() self.CcCopyReadNoWait = v_uint32() self.CcCopyReadWait = v_uint32() self.CcCopyReadNoWaitMiss = v_uint32() self.MmSpinLockOrdering = v_uint32() self.IoReadOperationCount = v_uint32() self.IoWriteOperationCount = v_uint32() self.IoOtherOperationCount = v_uint32() self.IoReadTransferCount = LARGE_INTEGER() self.IoWriteTransferCount = LARGE_INTEGER() self.IoOtherTransferCount = LARGE_INTEGER() self.CcFastMdlReadNoWait = v_uint32() self.CcFastMdlReadWait = v_uint32() self.CcFastMdlReadNotPossible = v_uint32() self.CcMapDataNoWait = v_uint32() self.CcMapDataWait = v_uint32() self.CcPinMappedDataCount = v_uint32() self.CcPinReadNoWait = v_uint32() self.CcPinReadWait = v_uint32() self.CcMdlReadNoWait = v_uint32() self.CcMdlReadWait = v_uint32() self.CcLazyWriteHotSpots = v_uint32() self.CcLazyWriteIos = v_uint32() self.CcLazyWritePages = v_uint32() self.CcDataFlushes = v_uint32() self.CcDataPages = v_uint32() self.CcLostDelayedWrites = v_uint32() self.CcFastReadResourceMiss = v_uint32() self.CcCopyReadWaitMiss = v_uint32() self.CcFastMdlReadResourceMiss = v_uint32() self.CcMapDataNoWaitMiss = v_uint32() self.CcMapDataWaitMiss = v_uint32() self.CcPinReadNoWaitMiss = v_uint32() self.CcPinReadWaitMiss = v_uint32() self.CcMdlReadNoWaitMiss = v_uint32() self.CcMdlReadWaitMiss = v_uint32() self.CcReadAheadIos = v_uint32() self.KeAlignmentFixupCount = v_uint32() self.KeExceptionDispatchCount = v_uint32() self.KeSystemCalls = v_uint32() self.AvailableTime = v_uint32() self.PrcbPad22 = v_bytes(size=8) # FIXME Unknown Array Type self.PPLookasideList = v_bytes(size=8) # FIXME Unknown Array Type self.PPNPagedLookasideList = v_bytes(size=8) # FIXME Unknown Array Type self.PPPagedLookasideList = v_bytes(size=8) # FIXME Unknown Array Type self.PacketBarrier = v_uint32() self.ReverseStall = v_uint32() self.IpiFrame = v_ptr32() self.PrcbPad3 = v_bytes(size=52) # FIXME Unknown Array Type self.CurrentPacket = v_bytes(size=12) # FIXME Unknown Array Type self.TargetSet = v_uint32() self.WorkerRoutine = v_ptr32() self.IpiFrozen = v_uint32() self.PrcbPad4 = v_bytes(size=40) # FIXME Unknown Array Type self.RequestSummary = v_uint32() self.SignalDone = v_ptr32() self.PrcbPad50 = v_bytes(size=56) # FIXME Unknown Array Type self.DpcData = v_bytes(size=56) # FIXME Unknown Array Type self.DpcStack = v_ptr32() self.MaximumDpcQueueDepth = v_uint32() self.DpcRequestRate = v_uint32() self.MinimumDpcRate = v_uint32() self.DpcLastCount = v_uint32() self.PrcbLock = v_uint32() self.DpcGate = KGATE() self.ThreadDpcEnable = v_uint8() self.QuantumEnd = v_uint8() self.DpcRoutineActive = v_uint8() self.IdleSchedule = v_uint8() self.DpcRequestSummary = v_uint32() self.TimerHand = v_uint32() self.LastTick = v_uint32() self.MasterOffset = v_uint32() self.PrcbPad41 = v_bytes(size=8) # FIXME Unknown Array Type self.PeriodicCount = v_uint32() self.PeriodicBias = v_uint32() self._pad1958 = v_bytes(size=4) self.TickOffset = v_uint64() self.TimerTable = KTIMER_TABLE() self.CallDpc = KDPC() self.ClockKeepAlive = v_uint32() self.ClockCheckSlot = v_uint8() self.ClockPollCycle = v_uint8() self.PrcbPad6 = v_bytes(size=2) # FIXME Unknown Array Type self.DpcWatchdogPeriod = v_uint32() self.DpcWatchdogCount = v_uint32() self.ThreadWatchdogPeriod = v_uint32() self.ThreadWatchdogCount = v_uint32() self.KeSpinLockOrdering = v_uint32() self.PrcbPad70 = v_bytes(size=4) # FIXME Unknown Array Type self.WaitListHead = LIST_ENTRY() self.WaitLock = v_uint32() self.ReadySummary = v_uint32() self.QueueIndex = v_uint32() self.DeferredReadyListHead = SINGLE_LIST_ENTRY() self.StartCycles = v_uint64() self.CycleTime = v_uint64() self.HighCycleTime = v_uint32() self.PrcbPad71 = v_uint32() self.PrcbPad72 = v_bytes(size=16) # FIXME Unknown Array Type self.DispatcherReadyListHead = v_bytes(size=16) # FIXME Unknown Array Type self.ChainedInterruptList = v_ptr32() self.LookasideIrpFloat = v_uint32() self.MmPageFaultCount = v_uint32() self.MmCopyOnWriteCount = v_uint32() self.MmTransitionCount = v_uint32() self.MmCacheTransitionCount = v_uint32() self.MmDemandZeroCount = v_uint32() self.MmPageReadCount = v_uint32() self.MmPageReadIoCount = v_uint32() self.MmCacheReadCount = v_uint32() self.MmCacheIoCount = v_uint32() self.MmDirtyPagesWriteCount = v_uint32() self.MmDirtyWriteIoCount = v_uint32() self.MmMappedPagesWriteCount = v_uint32() self.MmMappedWriteIoCount = v_uint32() self.CachedCommit = v_uint32() self.CachedResidentAvailable = v_uint32() self.HyperPte = v_ptr32() self.PrcbPad8 = v_bytes(size=4) # FIXME Unknown Array Type self.VendorString = v_bytes(size=13) # FIXME Unknown Array Type self.InitialApicId = v_uint8() self.LogicalProcessorsPerPhysicalProcessor = v_uint8() self.PrcbPad9 = v_bytes(size=5) # FIXME Unknown Array Type self.FeatureBits = v_uint32() self._pad3388 = v_bytes(size=4) self.UpdateSignature = LARGE_INTEGER() self.IsrTime = v_uint64() self.RuntimeAccumulation = v_uint64() self.PowerState = PROCESSOR_POWER_STATE() self.DpcWatchdogDpc = KDPC() self.DpcWatchdogTimer = KTIMER() self.WheaInfo = v_ptr32() self.EtwSupport = v_ptr32() self.InterruptObjectPool = SLIST_HEADER() self.HypercallPageList = SLIST_HEADER() self.HypercallPageVirtual = v_ptr32() self.VirtualApicAssist = v_ptr32() self.StatisticsPage = v_ptr32() self.RateControl = v_ptr32() self.Cache = v_ptr32() self.CacheCount = v_uint32() self.CacheProcessorMask = v_bytes(size=20) # FIXME Unknown Array Type self.PackageProcessorSet = KAFFINITY_EX() self.PrcbPad91 = v_bytes(size=56) # FIXME Unknown Array Type self.CoreProcessorSet = v_uint32() self.TimerExpirationDpc = KDPC() self.SpinLockAcquireCount = v_uint32() self.SpinLockContentionCount = v_uint32() self.SpinLockSpinCount = v_uint32() self.IpiSendRequestBroadcastCount = v_uint32() self.IpiSendRequestRoutineCount = v_uint32() self.IpiSendSoftwareInterruptCount = v_uint32() self.ExInitializeResourceCount = v_uint32() self.ExReInitializeResourceCount = v_uint32() self.ExDeleteResourceCount = v_uint32() self.ExecutiveResourceAcquiresCount = v_uint32() self.ExecutiveResourceContentionsCount = v_uint32() self.ExecutiveResourceReleaseExclusiveCount = v_uint32() self.ExecutiveResourceReleaseSharedCount = v_uint32() self.ExecutiveResourceConvertsCount = v_uint32() self.ExAcqResExclusiveAttempts = v_uint32() self.ExAcqResExclusiveAcquiresExclusive = v_uint32() self.ExAcqResExclusiveAcquiresExclusiveRecursive = v_uint32() self.ExAcqResExclusiveWaits = v_uint32() self.ExAcqResExclusiveNotAcquires = v_uint32() self.ExAcqResSharedAttempts = v_uint32() self.ExAcqResSharedAcquiresExclusive = v_uint32() self.ExAcqResSharedAcquiresShared = v_uint32() self.ExAcqResSharedAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedWaits = v_uint32() self.ExAcqResSharedNotAcquires = v_uint32() self.ExAcqResSharedStarveExclusiveAttempts = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresExclusive = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresShared = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedStarveExclusiveWaits = v_uint32() self.ExAcqResSharedStarveExclusiveNotAcquires = v_uint32() self.ExAcqResSharedWaitForExclusiveAttempts = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresExclusive = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresShared = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedWaitForExclusiveWaits = v_uint32() self.ExAcqResSharedWaitForExclusiveNotAcquires = v_uint32() self.ExSetResOwnerPointerExclusive = v_uint32() self.ExSetResOwnerPointerSharedNew = v_uint32() self.ExSetResOwnerPointerSharedOld = v_uint32() self.ExTryToAcqExclusiveAttempts = v_uint32() self.ExTryToAcqExclusiveAcquires = v_uint32() self.ExBoostExclusiveOwner = v_uint32() self.ExBoostSharedOwners = v_uint32() self.ExEtwSynchTrackingNotificationsCount = v_uint32() self.ExEtwSynchTrackingNotificationsAccountedCount = v_uint32() self.Context = v_ptr32() self.ContextFlags = v_uint32() self.ExtendedState = v_ptr32() class RTL_DYNAMIC_HASH_TABLE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Flags = v_uint32() self.Shift = v_uint32() self.TableSize = v_uint32() self.Pivot = v_uint32() self.DivisorMask = v_uint32() self.NumEntries = v_uint32() self.NonEmptyBuckets = v_uint32() self.NumEnumerators = v_uint32() self.Directory = v_ptr32() class KAFFINITY_EX(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint16() self.Size = v_uint16() self.Reserved = v_uint32() self.Bitmap = v_bytes(size=16) # FIXME Unknown Array Type class DEVICE_OBJECT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.ReferenceCount = v_uint32() self.DriverObject = v_ptr32() self.NextDevice = v_ptr32() self.AttachedDevice = v_ptr32() self.CurrentIrp = v_ptr32() self.Timer = v_ptr32() self.Flags = v_uint32() self.Characteristics = v_uint32() self.Vpb = v_ptr32() self.DeviceExtension = v_ptr32() self.DeviceType = v_uint32() self.StackSize = v_uint8() self._pad0034 = v_bytes(size=3) self.Queue = _unnamed_7372() self.AlignmentRequirement = v_uint32() self.DeviceQueue = KDEVICE_QUEUE() self.Dpc = KDPC() self.ActiveThreadCount = v_uint32() self.SecurityDescriptor = v_ptr32() self.DeviceLock = KEVENT() self.SectorSize = v_uint16() self.Spare1 = v_uint16() self.DeviceObjectExtension = v_ptr32() self.Reserved = v_ptr32() class USER_MEMORY_CACHE_ENTRY(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UserBlocks = SLIST_HEADER() self.AvailableBlocks = v_uint32() class EX_PUSH_LOCK_WAIT_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.WakeEvent = KEVENT() self.Next = v_ptr32() self.Last = v_ptr32() self.Previous = v_ptr32() self.ShareCount = v_uint32() self.Flags = v_uint32() class _unnamed_8182(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PowerSequence = v_ptr32() class _unnamed_9780(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Raw = _unnamed_9775() class IMAGE_NT_HEADERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Signature = v_uint32() self.FileHeader = IMAGE_FILE_HEADER() self.OptionalHeader = IMAGE_OPTIONAL_HEADER() class IO_STACK_LOCATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MajorFunction = v_uint8() self.MinorFunction = v_uint8() self.Flags = v_uint8() self.Control = v_uint8() self.Parameters = _unnamed_7812() self.DeviceObject = v_ptr32() self.FileObject = v_ptr32() self.CompletionRoutine = v_ptr32() self.Context = v_ptr32() class KNODE(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PagedPoolSListHead = SLIST_HEADER() self.NonPagedPoolSListHead = SLIST_HEADER() self.Affinity = GROUP_AFFINITY() self.ProximityId = v_uint32() self.NodeNumber = v_uint16() self.PrimaryNodeNumber = v_uint16() self.MaximumProcessors = v_uint8() self.Color = v_uint8() self.Flags = flags() self.NodePad0 = v_uint8() self.Seed = v_uint32() self.MmShiftedColor = v_uint32() self.FreeCount = v_bytes(size=8) # FIXME Unknown Array Type self.CachedKernelStacks = CACHED_KSTACK_LIST() self.ParkLock = v_uint32() self.NodePad1 = v_uint32() class _unnamed_8078(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_ptr32() self.Size = v_uint16() self.Version = v_uint16() self.Interface = v_ptr32() self.InterfaceSpecificData = v_ptr32() class XSAVE_AREA_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Mask = v_uint64() self.Reserved = v_bytes(size=56) # FIXME Unknown Array Type class PSP_CPU_SHARE_CAPTURED_WEIGHT_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CapturedCpuShareWeight = v_uint32() self.CapturedTotalWeight = v_uint32() class RTL_USER_PROCESS_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.MaximumLength = v_uint32() self.Length = v_uint32() self.Flags = v_uint32() self.DebugFlags = v_uint32() self.ConsoleHandle = v_ptr32() self.ConsoleFlags = v_uint32() self.StandardInput = v_ptr32() self.StandardOutput = v_ptr32() self.StandardError = v_ptr32() self.CurrentDirectory = CURDIR() self.DllPath = UNICODE_STRING() self.ImagePathName = UNICODE_STRING() self.CommandLine = UNICODE_STRING() self.Environment = v_ptr32() self.StartingX = v_uint32() self.StartingY = v_uint32() self.CountX = v_uint32() self.CountY = v_uint32() self.CountCharsX = v_uint32() self.CountCharsY = v_uint32() self.FillAttribute = v_uint32() self.WindowFlags = v_uint32() self.ShowWindowFlags = v_uint32() self.WindowTitle = UNICODE_STRING() self.DesktopInfo = UNICODE_STRING() self.ShellInfo = UNICODE_STRING() self.RuntimeData = UNICODE_STRING() self.CurrentDirectores = UNICODE_STRING() self.EnvironmentSize = v_uint32() self.EnvironmentVersion = v_uint32() class _unnamed_8176(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.PowerState = v_uint32() class IO_RESOURCE_REQUIREMENTS_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.ListSize = v_uint32() self.InterfaceType = v_uint32() self.BusNumber = v_uint32() self.SlotNumber = v_uint32() self.Reserved = v_bytes(size=12) # FIXME Unknown Array Type self.AlternativeLists = v_uint32() self.List = v_uint32() class HEAP_BUCKET_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TotalBlocks = v_uint32() self.SubSegmentCounts = v_uint32()
Python
''' The pre-made windows structure defs (extracted from pdb syms) ''' import envi import ctypes import platform def isSysWow64(): k32 = ctypes.windll.kernel32 if not hasattr(k32, 'IsWow64Process'): return False ret = ctypes.c_ulong(0) myproc = ctypes.c_size_t(-1) if not k32.IsWow64Process(myproc, ctypes.addressof(ret)): return False return bool(ret.value) def getCurrentDef(normname): bname, wver, stuff, whichkern = platform.win32_ver() wvertup = wver.split('.') arch = envi.getCurrentArch() if isSysWow64(): arch = 'wow64' modname = 'vstruct.defs.windows.win_%s_%s_%s.%s' % (wvertup[0], wvertup[1], arch, normname) try: mod = __import__(modname, {}, {}, 1) except ImportError, e: mod = None return mod if __name__ == '__main__': print getCurrentDef('ntdll')
Python
""" Initial module with supporting structures for windows kernel serial debugging. """ import vstruct from vstruct.primitives import * # Main packet magic bytes and such BREAKIN_PACKET = 0x62626262 BREAKIN_PACKET_BYTE = 0x62 PACKET_LEADER = 0x30303030 PACKET_LEADER_BYTE = 0x30 CONTROL_PACKET_LEADER = 0x69696969 CONTROL_PACKET_LEADER_BYTE = 0x69 PACKET_TRAILING_BYTE = 0xAA pkt_magic_names = { BREAKIN_PACKET:"Break Packet", PACKET_LEADER:"Packet", CONTROL_PACKET_LEADER:"Control Packet", } # Primary "packet types" PACKET_TYPE_UNUSED = 0 PACKET_TYPE_KD_STATE_CHANGE32 = 1 PACKET_TYPE_KD_STATE_MANIPULATE = 2 PACKET_TYPE_KD_DEBUG_IO = 3 PACKET_TYPE_KD_ACKNOWLEDGE = 4 PACKET_TYPE_KD_RESEND = 5 PACKET_TYPE_KD_RESET = 6 PACKET_TYPE_KD_STATE_CHANGE64 = 7 PACKET_TYPE_KD_POLL_BREAKIN = 8 PACKET_TYPE_KD_TRACE_IO = 9 PACKET_TYPE_KD_CONTROL_REQUEST = 10 PACKET_TYPE_KD_FILE_IO = 11 PACKET_TYPE_MAX = 12 pkt_type_names = { PACKET_TYPE_UNUSED:"Unused", PACKET_TYPE_KD_STATE_CHANGE32:"State Change32", PACKET_TYPE_KD_STATE_MANIPULATE:"Manipulate", PACKET_TYPE_KD_DEBUG_IO:"Debug IO", PACKET_TYPE_KD_ACKNOWLEDGE:"Ack", PACKET_TYPE_KD_RESEND:"Resend", PACKET_TYPE_KD_RESET:"Reset", PACKET_TYPE_KD_STATE_CHANGE64:"State Change64", PACKET_TYPE_KD_POLL_BREAKIN:"Breakin", PACKET_TYPE_KD_TRACE_IO:"Trace IO", PACKET_TYPE_KD_CONTROL_REQUEST:"Control Request", PACKET_TYPE_KD_FILE_IO:"File IO", PACKET_TYPE_MAX:"Max", } # Wait State Change Types DbgKdMinimumStateChange = 0x00003030 DbgKdExceptionStateChange = 0x00003030 DbgKdLoadSymbolsStateChange = 0x00003031 DbgKdCommandStringStateChange = 0x00003032 DbgKdMaximumStateChange = 0x00003033 pkt_sub_wait_state_change = { DbgKdMinimumStateChange:"DbgKdMinimumStateChange", DbgKdExceptionStateChange:"DbgKdExceptionStateChange", DbgKdLoadSymbolsStateChange:"DbgKdLoadSymbolsStateChange", DbgKdCommandStringStateChange:"DbgKdCommandStringStateChange", DbgKdMaximumStateChange:"DbgKdMaximumStateChange", } # Manipulate Types DbgKdMinimumManipulate = 0x00003130 DbgKdReadVirtualMemoryApi = 0x00003130 DbgKdWriteVirtualMemoryApi = 0x00003131 DbgKdGetContextApi = 0x00003132 DbgKdSetContextApi = 0x00003133 DbgKdWriteBreakPointApi = 0x00003134 DbgKdRestoreBreakPointApi = 0x00003135 DbgKdContinueApi = 0x00003136 DbgKdReadControlSpaceApi = 0x00003137 DbgKdWriteControlSpaceApi = 0x00003138 DbgKdReadIoSpaceApi = 0x00003139 DbgKdWriteIoSpaceApi = 0x0000313A DbgKdRebootApi = 0x0000313B DbgKdContinueApi2 = 0x0000313C DbgKdReadPhysicalMemoryApi = 0x0000313D DbgKdWritePhysicalMemoryApi = 0x0000313E DbgKdQuerySpecialCallsApi = 0x0000313F DbgKdSetSpecialCallApi = 0x00003140 DbgKdClearSpecialCallsApi = 0x00003141 DbgKdSetInternalBreakPointApi = 0x00003142 DbgKdGetInternalBreakPointApi = 0x00003143 DbgKdReadIoSpaceExtendedApi = 0x00003144 DbgKdWriteIoSpaceExtendedApi = 0x00003145 DbgKdGetVersionApi = 0x00003146 DbgKdWriteBreakPointExApi = 0x00003147 DbgKdRestoreBreakPointExApi = 0x00003148 DbgKdCauseBugCheckApi = 0x00003149 DbgKdSwitchProcessor = 0x00003150 DbgKdPageInApi = 0x00003151 DbgKdReadMachineSpecificRegister = 0x00003152 DbgKdWriteMachineSpecificRegister = 0x00003153 OldVlm1 = 0x00003154 OldVlm2 = 0x00003155 DbgKdSearchMemoryApi = 0x00003156 DbgKdGetBusDataApi = 0x00003157 DbgKdSetBusDataApi = 0x00003158 DbgKdCheckLowMemoryApi = 0x00003159 DbgKdClearAllInternalBreakpointsApi = 0x0000315A DbgKdFillMemoryApi = 0x0000315B DbgKdQueryMemoryApi = 0x0000315C DbgKdSwitchPartition = 0x0000315D DbgKdMaximumManipulate = 0x0000315E pkt_sub_manipulate = { DbgKdMinimumManipulate:"DbgKdMinimumManipulate", DbgKdReadVirtualMemoryApi:"DbgKdReadVirtualMemoryApi", DbgKdWriteVirtualMemoryApi:"DbgKdWriteVirtualMemoryApi", DbgKdGetContextApi:"DbgKdGetContextApi", DbgKdSetContextApi:"DbgKdSetContextApi", DbgKdWriteBreakPointApi:"DbgKdWriteBreakPointApi", DbgKdRestoreBreakPointApi:"DbgKdRestoreBreakPointApi", DbgKdContinueApi:"DbgKdContinueApi", DbgKdReadControlSpaceApi:"DbgKdReadControlSpaceApi", DbgKdWriteControlSpaceApi:"DbgKdWriteControlSpaceApi", DbgKdReadIoSpaceApi:"DbgKdReadIoSpaceApi", DbgKdWriteIoSpaceApi:"DbgKdWriteIoSpaceApi", DbgKdRebootApi:"DbgKdRebootApi", DbgKdContinueApi2:"DbgKdContinueApi2", DbgKdReadPhysicalMemoryApi:"DbgKdReadPhysicalMemoryApi", DbgKdWritePhysicalMemoryApi:"DbgKdWritePhysicalMemoryApi", DbgKdQuerySpecialCallsApi:"DbgKdQuerySpecialCallsApi", DbgKdSetSpecialCallApi:"DbgKdSetSpecialCallApi", DbgKdClearSpecialCallsApi:"DbgKdClearSpecialCallsApi", DbgKdSetInternalBreakPointApi:"DbgKdSetInternalBreakPointApi", DbgKdGetInternalBreakPointApi:"DbgKdGetInternalBreakPointApi", DbgKdReadIoSpaceExtendedApi:"DbgKdReadIoSpaceExtendedApi", DbgKdWriteIoSpaceExtendedApi:"DbgKdWriteIoSpaceExtendedApi", DbgKdGetVersionApi:"DbgKdGetVersionApi", DbgKdWriteBreakPointExApi:"DbgKdWriteBreakPointExApi", DbgKdRestoreBreakPointExApi:"DbgKdRestoreBreakPointExApi", DbgKdCauseBugCheckApi:"DbgKdCauseBugCheckApi", DbgKdSwitchProcessor:"DbgKdSwitchProcessor", DbgKdPageInApi:"DbgKdPageInApi", DbgKdReadMachineSpecificRegister:"DbgKdReadMachineSpecificRegister", DbgKdWriteMachineSpecificRegister:"DbgKdWriteMachineSpecificRegister", OldVlm1:"OldVlm1", OldVlm2:"OldVlm2", DbgKdSearchMemoryApi:"DbgKdSearchMemoryApi", DbgKdGetBusDataApi:"DbgKdGetBusDataApi", DbgKdSetBusDataApi:"DbgKdSetBusDataApi", DbgKdCheckLowMemoryApi:"DbgKdCheckLowMemoryApi", DbgKdClearAllInternalBreakpointsApi:"DbgKdClearAllInternalBreakpointsApi", DbgKdFillMemoryApi:"DbgKdFillMemoryApi", DbgKdQueryMemoryApi:"DbgKdQueryMemoryApi", DbgKdSwitchPartition:"DbgKdSwitchPartition", DbgKdMaximumManipulate:"DbgKdMaximumManipulate", } # Debug I/O Types DbgKdPrintStringApi = 0x00003230 DbgKdGetStringApi = 0x00003231 # Control Report Flags REPORT_INCLUDES_SEGS = 0x0001 REPORT_INCLUDES_CS = 0x0002 # Protocol Versions DBGKD_64BIT_PROTOCOL_VERSION1 = 5 DBGKD_64BIT_PROTOCOL_VERSION2 = 6 # Query Memory Address Spaces DBGKD_QUERY_MEMORY_VIRTUAL = 0 DBGKD_QUERY_MEMORY_PROCESS = 0 DBGKD_QUERY_MEMORY_SESSION = 1 DBGKD_QUERY_MEMORY_KERNEL = 2 # Query Memory Flags DBGKD_QUERY_MEMORY_READ = 0x01 DBGKD_QUERY_MEMORY_WRITE = 0x02 DBGKD_QUERY_MEMORY_EXECUTE = 0x04 DBGKD_QUERY_MEMORY_FIXED = 0x08 ULONG = v_uint32 ULONG64 = v_uint64 BOOLEAN = v_uint32 class DBGKD_LOAD_SYMBOLS64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self._vs_field_align = True self.PathNameLength = v_uint32() self.BaseOfDll = v_uint64() self.ProcessId = v_uint64() self.CheckSum = v_uint32() self.SizeOfImage = v_uint32() #self.UnloadSymbols = v_uint8() self.UnloadSymbols = v_uint32() # HACK must be 32 bit aligned class DBGKD_WAIT_STATE_CHANGE64(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self._vs_field_align = True self.NewState = v_uint32() self.ProcessorLevel = v_uint16() self.Processor = v_uint16() self.NumberProcessors = v_uint32() self.Thread = v_uint64() self.ProgramCounter = v_uint64()
Python
# Import all local structure modules import elf import pe import win32
Python
#!/usr/bin/python import sys sn_header = """// Serial number 10, // bLength USB_DESC_STRING, // bDescriptorType """ try: ser = int(file(".serial", 'rb').read()) + 1 except IOError: ser = 0 print("[--- new serial number: %.4d ---]" % ser) file(".serial", 'wb').write("%.4d" % ser) sertxt = "%.4d" % ser sf = file("chipcon_usb.c", 'r+') sfile = sf.read() idx = sfile.find('// Serial number') eos = sfile.find('// END OF STRINGS') sf.seek(idx) sf.write(sn_header) for c in sertxt: sf.write(" '%s', 0,\n" % c) sf.write(" "*(eos-sf.tell()-1)) sf.write('\n') sf.close()
Python
#!/usr/bin/env ipython import sys, threading, time, struct, select import usb import bits from chipcondefs import * EP_TIMEOUT_IDLE = 400 EP_TIMEOUT_ACTIVE = 10 USB_RX_WAIT = 100 USB_TX_WAIT = 10000 USB_BM_REQTYPE_TGTMASK =0x1f USB_BM_REQTYPE_TGT_DEV =0x00 USB_BM_REQTYPE_TGT_INTF =0x01 USB_BM_REQTYPE_TGT_EP =0x02 USB_BM_REQTYPE_TYPEMASK =0x60 USB_BM_REQTYPE_TYPE_STD =0x00 USB_BM_REQTYPE_TYPE_CLASS =0x20 USB_BM_REQTYPE_TYPE_VENDOR =0x40 USB_BM_REQTYPE_TYPE_RESERVED =0x60 USB_BM_REQTYPE_DIRMASK =0x80 USB_BM_REQTYPE_DIR_OUT =0x00 USB_BM_REQTYPE_DIR_IN =0x80 USB_GET_STATUS =0x00 USB_CLEAR_FEATURE =0x01 USB_SET_FEATURE =0x03 USB_SET_ADDRESS =0x05 USB_GET_DESCRIPTOR =0x06 USB_SET_DESCRIPTOR =0x07 USB_GET_CONFIGURATION =0x08 USB_SET_CONFIGURATION =0x09 USB_GET_INTERFACE =0x0a USB_SET_INTERFACE =0x11 USB_SYNCH_FRAME =0x12 APP_GENERIC = 0x01 APP_DEBUG = 0xfe APP_SYSTEM = 0xff SYS_CMD_PEEK = 0x80 SYS_CMD_POKE = 0x81 SYS_CMD_PING = 0x82 SYS_CMD_STATUS = 0x83 SYS_CMD_POKE_REG = 0x84 SYS_CMD_GET_CLOCK = 0x85 SYS_CMD_BUILDTYPE = 0x86 SYS_CMD_RESET = 0x8f EP0_CMD_GET_DEBUG_CODES = 0x00 EP0_CMD_GET_ADDRESS = 0x01 EP0_CMD_POKEX = 0x01 EP0_CMD_PEEKX = 0x02 EP0_CMD_PING0 = 0x03 EP0_CMD_PING1 = 0x04 EP0_CMD_RESET = 0xfe DEBUG_CMD_STRING = 0xf0 DEBUG_CMD_HEX = 0xf1 DEBUG_CMD_HEX16 = 0xf2 DEBUG_CMD_HEX32 = 0xf3 DEBUG_CMD_INT = 0xf4 EP5OUT_MAX_PACKET_SIZE = 64 EP5IN_MAX_PACKET_SIZE = 64 # EP5OUT_BUFFER_SIZE must match firmware/include/chipcon_usb.h definition EP5OUT_BUFFER_SIZE = 1030 #EP5OUT_BUFFER_SIZE = 2054 SYNCM_NONE = 0 SYNCM_15_of_16 = 1 SYNCM_16_of_16 = 2 SYNCM_30_of_32 = 3 SYNCM_CARRIER = 4 SYNCM_CARRIER_15_of_16 = 5 SYNCM_CARRIER_16_of_16 = 6 SYNCM_CARRIER_30_of_32 = 7 RF_STATE_RX = 1 RF_STATE_TX = 2 RF_STATE_IDLE = 3 RF_SUCCESS = 0 RF_MAX_TX_BLOCK = 255 # RF_MAX_BLOCK must match BUFFER_SIZE definition in firmware/include/cc1111rf.h RF_MAX_RX_BLOCK = 512 MODES = {} lcls = locals() for lcl in lcls.keys(): if lcl.startswith("MARC_STATE_"): MODES[lcl] = lcls[lcl] MODES[lcls[lcl]] = lcl """ MODULATIONS Note that MSK is only supported for data rates above 26 kBaud and GFSK, ASK , and OOK is only supported for data rate up until 250 kBaud. MSK cannot be used if Manchester encoding/decoding is enabled. """ MOD_2FSK = 0x00 MOD_GFSK = 0x10 MOD_ASK_OOK = 0x30 MOD_MSK = 0x70 MANCHESTER = 0x08 MODULATIONS = { MOD_2FSK : "2FSK", MOD_GFSK : "GFSK", MOD_ASK_OOK : "ASK/OOK", MOD_MSK : "MSK", MOD_2FSK | MANCHESTER : "2FSK/Manchester encoding", MOD_GFSK | MANCHESTER : "GFSK/Manchester encoding", MOD_ASK_OOK | MANCHESTER : "ASK/OOK/Manchester encoding", MOD_MSK | MANCHESTER : "MSK/Manchester encoding", } SYNCMODES = { SYNCM_NONE: "None", SYNCM_15_of_16: "15 of 16 bits must match", SYNCM_16_of_16: "16 of 16 bits must match", SYNCM_30_of_32: "30 of 32 sync bits must match", SYNCM_CARRIER: "Carrier Detect", SYNCM_CARRIER_15_of_16: "Carrier Detect and 15 of 16 sync bits must match", SYNCM_CARRIER_16_of_16: "Carrier Detect and 16 of 16 sync bits must match", SYNCM_CARRIER_30_of_32: "Carrier Detect and 30 of 32 sync bits must match", } BSLIMITS = { BSCFG_BS_LIMIT_0: "No data rate offset compensation performed", BSCFG_BS_LIMIT_3: "+/- 3.125% data rate offset", BSCFG_BS_LIMIT_6: "+/- 6.25% data rate offset", BSCFG_BS_LIMIT_12: "+/- 12.5% data rate offset", } NUM_PREAMBLE = [2, 3, 4, 6, 8, 12, 16, 24 ] ADR_CHK_TYPES = [ "No address check", "Address Check, No Broadcast", "Address Check, 0x00 is broadcast", "Address Check, 0x00 and 0xff are broadcast", ] PKT_FORMATS = [ "Normal mode", "reserved...", "Random TX mode", "reserved", ] LENGTH_CONFIGS = [ "Fixed Packet Mode", "Variable Packet Mode (len=first byte after sync word)", "reserved", "reserved", ] LC_USB_INITUSB = 0x2 LC_MAIN_RFIF = 0xd LC_USB_DATA_RESET_RESUME = 0xa LC_USB_RESET = 0xb LC_USB_EP5OUT = 0xc LC_RF_VECTOR = 0x10 LC_RFTXRX_VECTOR = 0x11 LCE_USB_EP5_TX_WHILE_INBUF_WRITTEN = 0x1 LCE_USB_EP0_SENT_STALL = 0x4 LCE_USB_EP5_OUT_WHILE_OUTBUF_WRITTEN = 0x5 LCE_USB_EP5_LEN_TOO_BIG = 0x6 LCE_USB_EP5_GOT_CRAP = 0x7 LCE_USB_EP5_STALL = 0x8 LCE_USB_DATA_LEFTOVER_FLAGS = 0x9 LCE_RF_RXOVF = 0x10 LCE_RF_TXUNF = 0x11 LCS = {} LCES = {} lcls = locals() for lcl in lcls.keys(): if lcl.startswith("LCE_"): LCES[lcl] = lcls[lcl] LCES[lcls[lcl]] = lcl if lcl.startswith("LC_"): LCS[lcl] = lcls[lcl] LCS[lcls[lcl]] = lcl def keystop(): return len(select.select([sys.stdin],[],[],0)[0]) class ChipconUsbTimeoutException(Exception): def __str__(self): return "Timeout waiting for USB response." direct=False class USBDongle: ######## INITIALIZATION ######## def __init__(self, idx=0, debug=False, copyDongle=None): self.rsema = None self.xsema = None self._do = None self.idx = idx self.cleanup() self._debug = debug self._threadGo = False self._recv_time = 0 self.radiocfg = RadioConfig() self.recv_thread = threading.Thread(target=self.runEP5) self.recv_thread.setDaemon(True) self.recv_thread.start() self.resetup(copyDongle=copyDongle) self.max_packet_size = RF_MAX_RX_BLOCK def cleanup(self): self._usberrorcnt = 0; self.recv_queue = '' self.recv_mbox = {} self.xmit_queue = [] self.trash = [] def setup(self, console=True, copyDongle=None): global dongles if copyDongle is not None: self.devnum = copyDongle.devnum self._d = copyDongle._d self._do = copyDongle._do self._usbmaxi = copyDongle._usbmaxi self._usbmaxo = copyDongle._usbmaxo self._usbcfg = copyDongle._usbcfg self._usbintf = copyDongle._usbintf self._usbeps = copyDongle._usbeps self._threadGo = True self.ep5timeout = EP_TIMEOUT_ACTIVE copyDongle._threadGo = False # we're taking over from here. self.rsema = copyDongle.rsema self.xsema = copyDongle.xsema return dongles = [] self.ep5timeout = EP_TIMEOUT_ACTIVE for bus in usb.busses(): for dev in bus.devices: if dev.idProduct == 0x4715: if self._debug: print >>sys.stderr,(dev) do = dev.open() iSN = do.getDescriptor(1,0,50)[16] devnum = dev.devnum dongles.append((devnum, dev, do)) dongles.sort() if len(dongles) == 0: raise(Exception("No Dongle Found. Please insert a RFCAT dongle.")) self.rsema = threading.Lock() self.xsema = threading.Lock() # claim that interface! do = dongles[self.idx][2] try: do.claimInterface(0) except Exception,e: if console or self._debug: print >>sys.stderr,("Error claiming usb interface:" + repr(e)) self.devnum, self._d, self._do = dongles[self.idx] self._usbmaxi, self._usbmaxo = (EP5IN_MAX_PACKET_SIZE, EP5OUT_MAX_PACKET_SIZE) self._usbcfg = self._d.configurations[0] self._usbintf = self._usbcfg.interfaces[0][0] self._usbeps = self._usbintf.endpoints for ep in self._usbeps: if ep.address & 0x80: self._usbmaxi = ep.maxPacketSize else: self._usbmaxo = ep.maxPacketSize self._threadGo = True def resetup(self, console=True, copyDongle=None): self._do=None #self._threadGo = True if self._debug: print >>sys.stderr,("waiting (resetup) %x" % self.idx) while (self._do==None): try: self.setup(console, copyDongle) if copyDongle is None: self._clear_buffers(False) except Exception, e: if console: sys.stderr.write('.') if console or self._debug: print >>sys.stderr,("Error in resetup():" + repr(e)) time.sleep(1) ######## BASE FOUNDATIONAL "HIDDEN" CALLS ######## def _sendEP0(self, request=0, buf=None, value=0x200, index=0, timeout=1000): if buf == None: buf = 'HELLO THERE' #return self._do.controlMsg(USB_BM_REQTYPE_TGT_EP|USB_BM_REQTYPE_TYPE_VENDOR|USB_BM_REQTYPE_DIR_OUT, request, "\x00\x00\x00\x00\x00\x00\x00\x00"+buf, value, index, timeout), buf return self._do.controlMsg(USB_BM_REQTYPE_TGT_EP|USB_BM_REQTYPE_TYPE_VENDOR|USB_BM_REQTYPE_DIR_OUT, request, buf, value, index, timeout), buf def _recvEP0(self, request=0, length=64, value=0, index=0, timeout=100): retary = ["%c"%x for x in self._do.controlMsg(USB_BM_REQTYPE_TGT_EP|USB_BM_REQTYPE_TYPE_VENDOR|USB_BM_REQTYPE_DIR_IN, request, length, value, index, timeout)] if len(retary): return ''.join(retary) return "" def _sendEP5(self, buf=None, timeout=1000): global direct if (buf==None): buf = "\xff\x82\x07\x00ABCDEFG" if direct: self._do.bulkWrite(5, buf, timeout) return while (len(buf)>0): drain = buf[:self._usbmaxo] buf = buf[self._usbmaxo:] if self._debug: print >>sys.stderr,"XMIT:"+repr(drain) try: self._do.bulkWrite(5, drain, timeout) except Exception, e: if self._debug: print >>sys.stderr,"requeuing on error '%s' (%s)" % (repr(drain), e) self.xsema.acquire() msg = self.xmit_queue.insert(0, drain) self.xsema.release() if self._debug: print >>sys.stderr, repr(self.xmit_queue) ''' drain = buf[:self._usbmaxo] buf = buf[self._usbmaxo:] if len(buf): if self._debug: print >>sys.stderr,"requeuing '%s'" % repr(buf) self.xsema.acquire() msg = self.xmit_queue.insert(0, buf) self.xsema.release() if self._debug: print >>sys.stderr, repr(self.xmit_queue) if self._debug: print >>sys.stderr,"XMIT:"+repr(drain) try: self._do.bulkWrite(5, drain, timeout) except Exception, e: if self._debug: print >>sys.stderr,"requeuing on error '%s' (%s)" % (repr(drain), e) self.xsema.acquire() msg = self.xmit_queue.insert(0, drain) self.xsema.release() if self._debug: print >>sys.stderr, repr(self.xmit_queue) --- while (len(buf)>0): drain = buf[:self._usbmaxo] buf = buf[self._usbmaxo:] if self._debug: print >>sys.stderr,"XMIT:"+repr(drain) self._do.bulkWrite(5, drain, timeout) time.sleep(1) --- if (len(buf) > self._usbmaxo): drain = buf[:self._usbmaxo] buf = buf[self._usbmaxo:] self.xsema.acquire() msg = self.xmit_queue.insert(0, buf) self.xsema.release() else: drain = buf[:] if self._debug: print >>sys.stderr,"XMIT:"+repr(drain) self._do.bulkWrite(5, drain, timeout) --- while (len(buf)>0): if (len(buf) > self._usbmaxo): drain = buf[:self._usbmaxo] buf = buf[self._usbmaxo:] else: drain = buf[:] if self._debug: print >>sys.stderr,"XMIT:"+repr(drain) self._do.bulkWrite(5, drain, timeout) time.sleep(1) ''' def _recvEP5(self, timeout=100): retary = ["%c"%x for x in self._do.bulkRead(0x85, 500, timeout)] if self._debug: print >>sys.stderr,"RECV:"+repr(retary) if len(retary): return ''.join(retary) #return retary return '' def _clear_buffers(self, clear_recv_mbox=False): threadGo = self._threadGo self._threadGo = False if self._debug: print >>sys.stderr,("_clear_buffers()") if clear_recv_mbox: for key in self.recv_mbox.keys(): self.trash.extend(self.recvAll(key)) self.trash.append((time.time(),self.recv_queue)) self.recv_queue = '' # self.xmit_queue = [] # do we want to keep this? self._threadGo = threadGo ######## TRANSMIT/RECEIVE THREADING ######## def runEP5(self): msg = '' self.threadcounter = 0 while True: if (self._do is None or not self._threadGo): time.sleep(.04) continue self.threadcounter = (self.threadcounter + 1) & 0xffffffff #### transmit stuff. if any exists in the xmit_queue msgsent = False msgrecv = False try: if len(self.xmit_queue): self.xsema.acquire() msg = self.xmit_queue.pop(0) self.xsema.release() self._sendEP5(msg) msgsent = True else: if self._debug>3: sys.stderr.write("NoMsgToSend ") #except IndexError: #if self._debug==3: sys.stderr.write("NoMsgToSend ") #pass except: sys.excepthook(*sys.exc_info()) #### handle debug application try: q = None b = self.recv_mbox.get(APP_DEBUG, None) if (b != None): for cmd in b.keys(): q = b[cmd] if len(q): buf,timestamp = q.pop(0) #cmd = ord(buf[1]) if self._debug > 1: print >>sys.stderr,("buf length: %x\t\t cmd: %x\t\t(%s)"%(len(buf), cmd, repr(buf))) if (cmd == DEBUG_CMD_STRING): if (len(buf) < 4): if (len(q)): buf2 = q.pop(0) buf += buf2 q.insert(0,buf) if self._debug: sys.stderr.write('*') else: length, = struct.unpack("<H", buf[2:4]) if self._debug >1: print >>sys.stderr,("len=%d"%length) if (len(buf) < 4+length): if (len(q)): buf2 = q.pop(0) buf += buf2 q.insert(0,buf) if self._debug: sys.stderr.write('&') else: printbuf = buf[4:4+length] requeuebuf = buf[4+length:] if len(requeuebuf): if self._debug>1: print >>sys.stderr,(" - DEBUG..requeuing %s"%repr(requeuebuf)) q.insert(0,requeuebuf) print >>sys.stderr,("DEBUG: (%.3f) %s" % (timestamp, repr(printbuf))) elif (cmd == DEBUG_CMD_HEX): #print >>sys.stderr, repr(buf) print >>sys.stderr, "DEBUG: (%.3f) %x"%(timestamp, struct.unpack("B", buf[4:5])[0]) elif (cmd == DEBUG_CMD_HEX16): #print >>sys.stderr, repr(buf) print >>sys.stderr, "DEBUG: (%.3f) %x"%(timestamp, struct.unpack("<H", buf[4:6])[0]) elif (cmd == DEBUG_CMD_HEX32): #print >>sys.stderr, repr(buf) print >>sys.stderr, "DEBUG: (%.3f) %x"%(timestamp, struct.unpack("<L", buf[4:8])[0]) elif (cmd == DEBUG_CMD_INT): print >>sys.stderr, "DEBUG: (%.3f) %d"%(timestamp, struct.unpack("<L", buf[4:8])[0]) else: print >>sys.stderr,('DEBUG COMMAND UNKNOWN: %x (buf=%s)'%(cmd,repr(buf))) except: sys.excepthook(*sys.exc_info()) #### receive stuff. try: #### first we populate the queue msg = self._recvEP5(timeout=self.ep5timeout) if len(msg) > 0: self.recv_queue += msg msgrecv = True except usb.USBError, e: #sys.stderr.write(repr(self.recv_queue)) #sys.stderr.write(repr(e)) errstr = repr(e) if self._debug>4: print >>sys.stderr,repr(sys.exc_info()) if ('No error' in errstr): pass elif ('Operation timed out' in errstr): pass else: if ('could not release intf' in errstr): pass elif ('No such device' in errstr): self._threadGo = False self.resetup(False) else: if self._debug: print "Error in runEP5() (receiving): %s" % errstr if self._debug>2: sys.excepthook(*sys.exc_info()) self._usberrorcnt += 1 pass #### parse, sort, and deliver the mail. try: # FIXME: is this robust? or just overcomplex? if len(self.recv_queue): idx = self.recv_queue.find('@') if (idx==-1): if self._debug > 3: sys.stderr.write('@') else: if (idx>0): if self._debug: print >>sys.stderr,("runEP5(): idx>0?") self.trash.append(self.recv_queue[:idx]) self.recv_queue = self.recv_queue[idx:] # recv_queue is vulnerable here, but it's ok because we only modify it earlier in this same thread # DON'T CHANGE recv_queue from other threads! msg = self.recv_queue msglen = len(msg) while (msglen>=5): # if not enough to parse length... we'll wait. if not self._recv_time: # should be 0 to start and when done with a packet self._recv_time = time.time() app = ord(msg[1]) cmd = ord(msg[2]) length, = struct.unpack("<H", msg[3:5]) if self._debug>1: print>>sys.stderr,("app=%x cmd=%x len=%x"%(app,cmd,length)) if (msglen >= length+5): #### if the queue has enough characters to handle the next message... chop it and put it in the appropriate recv_mbox msg = self.recv_queue[1:length+5] # drop the initial '@' and chop out the right number of chars self.recv_queue = self.recv_queue[length+5:] # chop it out of the queue b = self.recv_mbox.get(app,None) if self.rsema.acquire(): # THREAD SAFETY DANCE #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],0 try: if (b == None): b = {} self.recv_mbox[app] = b except: sys.excepthook(*sys.exc_info()) finally: self.rsema.release() # THREAD SAFETY DANCE COMPLETE #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],0 q = b.get(cmd) if self.rsema.acquire(): # THREAD SAFETY DANCE #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],1 try: if (q is None): q = [] b[cmd] = q q.append((msg, self._recv_time)) self._recv_time = 0 # we've delivered the current message except: sys.excepthook(*sys.exc_info()) finally: self.rsema.release() # THREAD SAFETY DANCE COMPLETE #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],1 else: if self._debug>1: sys.stderr.write('=') msg = self.recv_queue msglen = len(msg) # end of while loop #else: # if self._debug: sys.stderr.write('.') except: sys.excepthook(*sys.exc_info()) if not (msgsent or msgrecv or len(msg)) : #time.sleep(.1) self.ep5timeout = EP_TIMEOUT_IDLE else: self.ep5timeout = EP_TIMEOUT_ACTIVE if self._debug > 5: sys.stderr.write(" %s:%s:%d .-P."%(msgsent,msgrecv,len(msg))) ######## APPLICATION API ######## def recv(self, app, cmd=None, wait=USB_RX_WAIT): for x in xrange(wait+1): try: b = self.recv_mbox.get(app) if cmd is None: keys = b.keys() if len(keys): cmd = b.keys()[-1] if b is not None: q = b.get(cmd) #print >>sys.stderr,"debug(recv) q='%s'"%repr(q) if q is not None and self.rsema.acquire(False): #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],2 try: resp, rt = q.pop(0) self.rsema.release() #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],2 return resp[4:], rt except IndexError: pass #sys.excepthook(*sys.exc_info()) except AttributeError: sys.excepthook(*sys.exc_info()) pass self.rsema.release() #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],2 except: sys.excepthook(*sys.exc_info()) time.sleep(.0001) # only hits here if we don't have something in queue raise(ChipconUsbTimeoutException()) def recvAll(self, app, cmd=None): retval = self.recv_mbox.get(app,None) if retval is not None: if cmd is not None: b = retval if self.rsema.acquire(): #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],3 try: retval = b.get(cmd) b[cmd]=[] if len(retval): retval = [ (d[4:],t) for d,t in retval ] except: sys.excepthook(*sys.exc_info()) finally: self.rsema.release() #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],3 else: if self.rsema.acquire(): #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],4 try: self.recv_mbox[app]={} finally: self.rsema.release() #if self._debug: print ("rsema.UNlocked", "rsema.locked")[self.rsema.locked()],4 return retval def send(self, app, cmd, buf, wait=USB_TX_WAIT): msg = "%c%c%s%s"%(app,cmd, struct.pack("<H",len(buf)),buf) self.xsema.acquire() self.xmit_queue.append(msg) self.xsema.release() return self.recv(app, cmd, wait) def getDebugCodes(self, timeout=100): x = self._recvEP0(timeout=timeout) if (x != None and len(x)==2): return struct.unpack("BB", x) else: return x def ep0GetAddr(self): addr = self._recvEP0(request=EP0_CMD_GET_ADDRESS) return addr def ep0Reset(self): x = self._recvEP0(request=0xfe, value=0x5352, index=0x4e54) return x def ep0Peek(self, addr, length, timeout=100): x = self._recvEP0(request=EP0_CMD_PEEKX, value=addr, length=length, timeout=timeout) return x#x[3:] def ep0Poke(self, addr, buf='\x00', timeout=100): x = self._sendEP0(request=EP0_CMD_POKEX, buf=buf, value=addr, timeout=timeout) return x def ep0Ping(self, count=10): good=0 bad=0 for x in range(count): #r = self._recvEP0(3, 10) r = self._recvEP0(request=2, value=count, length=count, timeout=1000) print "PING: %d bytes received: %s"%(len(r), repr(r)) if r==None: bad+=1 else: good+=1 return (good,bad) def debug(self): while True: """ try: print >>sys.stderr, ("DONGLE RESPONDING: mode :%x, last error# %d"%(self.getDebugCodes())) except: pass print >>sys.stderr,('recv_queue:\t\t (%d bytes) "%s"'%(len(self.recv_queue),repr(self.recv_queue)[:len(self.recv_queue)%39+20])) print >>sys.stderr,('trash: \t\t (%d bytes) "%s"'%(len(self.trash),repr(self.trash)[:len(self.trash)%39+20])) print >>sys.stderr,('recv_mbox \t\t (%d keys) "%s"'%(len(self.recv_mbox),repr(self.recv_mbox)[:len(repr(self.recv_mbox))%79])) for x in self.recv_mbox.keys(): print >>sys.stderr,(' recv_mbox %d\t (%d records) "%s"'%(x,len(self.recv_mbox[x]),repr(self.recv_mbox[x])[:len(repr(self.recv_mbox[x]))%79])) """ print self.reprRadioState() print self.reprClientState() x,y,z = select.select([sys.stdin],[],[],1) if sys.stdin in x: sys.stdin.read(1) break def ping(self, count=10, buf="ABCDEFGHIJKLMNOPQRSTUVWXYZ", wait=3000): good=0 bad=0 start = time.time() for x in range(count): istart = time.time() try: r = self.send(APP_SYSTEM, SYS_CMD_PING, buf, wait) except ChipconUsbTimeoutException, e: r = None pass #print e r,rt = r istop = time.time() print "PING: %d bytes transmitted, received: %s (%f seconds)"%(len(buf), repr(r), istop-istart) if r==None: bad+=1 else: good+=1 stop = time.time() return (good,bad,stop-start) def RESET(self): try: r = self.send(APP_SYSTEM, SYS_CMD_RESET, "RESET_NOW\x00") except ChipconUsbTimeoutException: pass def peek(self, addr, bytecount=1): r, t = self.send(APP_SYSTEM, SYS_CMD_PEEK, struct.pack("<HH", bytecount, addr)) return r def poke(self, addr, data): r, t = self.send(APP_SYSTEM, SYS_CMD_POKE, struct.pack("<H", addr) + data) return r def pokeReg(self, addr, data): r, t = self.send(APP_SYSTEM, SYS_CMD_POKE_REG, struct.pack("<H", addr) + data) return r def getBuildInfo(self): r, t = self.send(APP_SYSTEM, SYS_CMD_BUILDTYPE, '') return r def getInterruptRegisters(self): regs = {} # IEN0,1,2 regs['IEN0'] = self.peek(IEN0,1) regs['IEN1'] = self.peek(IEN1,1) regs['IEN2'] = self.peek(IEN2,1) # TCON regs['TCON'] = self.peek(TCON,1) # S0CON regs['S0CON'] = self.peek(S0CON,1) # IRCON regs['IRCON'] = self.peek(IRCON,1) # IRCON2 regs['IRCON2'] = self.peek(IRCON2,1) # S1CON regs['S1CON'] = self.peek(S1CON,1) # RFIF regs['RFIF'] = self.peek(RFIF,1) # DMAIE regs['DMAIE'] = self.peek(DMAIE,1) # DMAIF regs['DMAIF'] = self.peek(DMAIF,1) # DMAIRQ regs['DMAIRQ'] = self.peek(DMAIRQ,1) return regs ######## RADIO METHODS ######### ### radio recv def getMARCSTATE(self, radiocfg=None): if radiocfg is None: self.getRadioConfig() radiocfg=self.radiocfg mode = self.radiocfg.marcstate return (MODES[mode], mode) def setModeTX(self): self.poke(X_RFST, "%c"%RFST_STX) def setModeRX(self): self.poke(X_RFST, "%c"%RFST_SRX) def setModeIDLE(self): self.poke(X_RFST, "%c"%RFST_SIDLE) def setModeFSTXON(self): self.poke(X_RFST, "%c"%RFST_SFSTXON) def setModeCAL(self): self.poke(X_RFST, "%c"%RFST_SCAL) def setRFRegister(self, regaddr, value): marcstate = self.radiocfg.marcstate self.setModeIDLE() self.poke(regaddr, chr(value)) if (marcstate == MARC_STATE_RX): self.setModeRX() elif (marcstate == MARC_STATE_TX): self.setModeTX() # if other than these, we can stay in IDLE ### radio config def getRadioConfig(self): bytedef = self.peek(0xdf00, 0x3e) self.radiocfg.vsParse(bytedef) return bytedef def setRadioConfig(self, bytedef = None): if bytedef is None: bytedef = self.radiocfg.vsEmit() statestr, marcstate = self.getMARCSTATE() self.setModeIDLE() self.poke(0xdf00, bytedef) if (marcstate == MARC_STATE_RX): self.setModeRX() elif (marcstate == MARC_STATE_TX): self.setModeTX() return bytedef def setFreq(self, freq=902000000, mhz=24, radiocfg=None): freqmult = (0x10000 / 1000000.0) / mhz num = int(freq * freqmult) self.radiocfg.freq2 = num >> 16 self.radiocfg.freq1 = (num>>8) & 0xff self.radiocfg.freq0 = num & 0xff self.setModeIDLE() self.poke(FREQ2, struct.pack("3B", self.radiocfg.freq2, self.radiocfg.freq1, self.radiocfg.freq0)) #self.setModeRX() def getFreq(self, mhz=24, radiocfg=None): freqmult = (0x10000 / 1000000.0) / mhz if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg num = (self.radiocfg.freq2<<16) + (self.radiocfg.freq1<<8) + self.radiocfg.freq0 freq = num / freqmult return freq, hex(num) # set 'standard' power - for more complex power shaping this will need to be done manually def setPower(self, power=None, radiocfg=None, invert=False): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg mod= self.getMdmModulation(radiocfg=radiocfg) # we may be only changing PA_POWER, not power levels if power is not None: if mod == MOD_ASK_OOK and not invert: self.radiocfg.pa_table0= 0x00 self.radiocfg.pa_table1= power else: self.radiocfg.pa_table0= power self.radiocfg.pa_table1= 0x00 self.setRFRegister(PA_TABLE0, radiocfg.pa_table0) self.setRFRegister(PA_TABLE1, radiocfg.pa_table1) self.radiocfg.frend0 &= ~FREND0_PA_POWER if mod == MOD_ASK_OOK: self.radiocfg.frend0 |= 0x01 self.setRFRegister(FREND0, radiocfg.frend0) # max power settings are frequency dependent, so set frequency before calling def setMaxPower(self, radiocfg=None, invert=False): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg freq= self.getFreq(radiocfg=radiocfg)[0] if freq <= 400000000: power= 0xC2 elif freq <= 464000000: power= 0xC0 elif freq <= 900000000: power= 0xC2 else: power= 0xC0 self.setPower(power, radiocfg=radiocfg, invert=invert) def setMdmModulation(self, mod, radiocfg=None, invert=False): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg if (mod) & 0x8f: raise(Exception("Please use constants MOD_FORMAT_* to specify modulation and ")) radiocfg.mdmcfg2 &= 0x8f radiocfg.mdmcfg2 |= (mod) power= None # ASK_OOK needs to flip power table if mod == MOD_ASK_OOK and not invert: if radiocfg.pa_table1 == 0x00 and radiocfg.pa_table0 != 0x00: power= radiocfg.pa_table0 else: if radiocfg.pa_table0 == 0x00 and radiocfg.pa_table1 != 0x00: power= radiocfg.pa_table1 self.setRFRegister(MDMCFG2, radiocfg.mdmcfg2) self.setPower(power, radiocfg=radiocfg, invert=invert) def getMdmModulation(self, radiocfg=None): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg mdmcfg2 = radiocfg.mdmcfg2 mod = (mdmcfg2) & 0x70 return mod def reprRadioConfig(self, mhz=24, radiocfg=None): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg output = [] output.append( "Frequency Configuration") output.append( self.reprFreqConfig(mhz, radiocfg)) output.append( "\nModem Configuration") output.append( self.reprModemConfig(mhz, radiocfg)) output.append( "\nPacket Configuration") output.append( self.reprPacketConfig(radiocfg)) output.append( "\nRadio Test Signal Configuration") output.append( self.reprRadioTestSignalConfig(radiocfg)) output.append( "\nRadio State") output.append( self.reprRadioState(radiocfg)) output.append("\nClient State") output.append( self.reprClientState()) return "\n".join(output) def reprMdmModulation(self, radiocfg=None): mod = self.getMdmModulation(radiocfg) return ("Modulation: %s" % MODULATIONS[mod]) def getMdmChanSpc(self, mhz=24, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg chanspc_m = radiocfg.mdmcfg0 chanspc_e = radiocfg.mdmcfg1 & 3 chanspc = 1000000.0 * mhz/pow(2,18) * (256 + chanspc_m) * pow(2, chanspc_e) #print "chanspc_e: %x chanspc_m: %x chanspc: %f hz" % (chanspc_e, chanspc_m, chanspc) return (chanspc) def setMdmChanSpc(self, chanspc=None, chanspc_m=None, chanspc_e=None, mhz=24, radiocfg=None): ''' calculates the appropriate exponent and mantissa and updates the correct registers chanspc is in kHz. if you prefer, you may set the chanspc_m and chanspc_e settings directly. only use one or the other: * chanspc * chanspc_m and chanspc_e ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg if (chanspc != None): for e in range(4): m = int(((chanspc * pow(2,18) / (1000000.0 * mhz * pow(2,e)))-256) +.5) # rounded evenly if m < 256: chanspc_e = e chanspc_m = m break if chanspc_e is None or chanspc_m is None: raise(Exception("ChanSpc does not translate into acceptable parameters. Should you be changing this?")) #chanspc = 1000000.0 * mhz/pow(2,18) * (256 + chanspc_m) * pow(2, chanspc_e) #print "chanspc_e: %x chanspc_m: %x chanspc: %f hz" % (chanspc_e, chanspc_m, chanspc) radiocfg.mdmcfg1 &= 0xfc # clear out old exponent value radiocfg.mdmcfg1 |= chanspc_e radiocfg.mdmcfg0 = chanspc_m self.setRFRegister(MDMCFG1, (radiocfg.mdmcfg1)) self.setRFRegister(MDMCFG0, (radiocfg.mdmcfg0)) def makePktVLEN(self, maxlen=RF_MAX_TX_BLOCK, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg if maxlen > RF_MAX_TX_BLOCK: raise(Exception("Packet too large (%d bytes). Maximum variable length packet is %d bytes." % (maxlen, RF_MAX_TX_BLOCK))) self.radiocfg.pktctrl0 &= 0xfc self.radiocfg.pktctrl0 |= 1 self.radiocfg.pktlen = maxlen self.setRFRegister(PKTCTRL0, (self.radiocfg.pktctrl0)) self.setRFRegister(PKTLEN, (self.radiocfg.pktlen)) def makePktFLEN(self, flen=RF_MAX_TX_BLOCK, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg if flen > EP5OUT_BUFFER_SIZE - 6: raise(Exception("Packet too large (%d bytes). Maximum fixed length packet is %d bytes." % (flen, EP5OUT_BUFFER_SIZE - 6))) self.radiocfg.pktctrl0 &= 0xfc # if we're sending a large block, pktlen is dealt with by the chip # using 'infinite' mode if flen > RF_MAX_TX_BLOCK: self.radiocfg.pktlen = 0x00 else: self.radiocfg.pktlen = flen self.setRFRegister(PKTCTRL0, (self.radiocfg.pktctrl0)) self.setRFRegister(PKTLEN, (self.radiocfg.pktlen)) def setEnablePktCRC(self, enable=True, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg crcE = (0,1)[enable]<<2 crcM = ~(1<<2) self.radiocfg.pktctrl0 &= crcM self.radiocfg.pktctrl0 |= crcE self.setRFRegister(PKTCTRL0, (self.radiocfg.pktctrl0)) def getEnablePktCRC(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg return (radiocfg.pktctrl0 >>2) & 0x1 def setEnablePktDataWhitening(self, enable=True, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg dwEnable = (0,1)[enable]<<6 dwMask = ~(1<<6) self.radiocfg.pktctrl0 &= dwMask self.radiocfg.pktctrl0 |= dwEnable self.setRFRegister(PKTCTRL0, (self.radiocfg.pktctrl0)) def getEnablePktDataWhitening(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg return (radiocfg.pktctrl0 >>6) & 0x1 def setPktPQT(self, num=3, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg num &= 7 num <<= 5 numM = ~(7<<5) radiocfg.pktctrl1 &= numM radiocfg.pktctrl1 |= num self.setRFRegister(PKTCTRL1, (radiocfg.pktctrl1)) def getPktPQT(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg return (radiocfg.pktctrl1 >> 5) & 7 def setEnableMdmManchester(self, enable=True, radiocfg=None): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg radiocfg.mdmcfg2 &= 0xf7 radiocfg.mdmcfg2 |= (enable<<3) self.setRFRegister(MDMCFG2, radiocfg.mdmcfg2) def getEnableMdmManchester(self, radiocfg=None): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg mdmcfg2 = radiocfg.mdmcfg2 mchstr = (mdmcfg2>>3) & 0x01 return mchstr def setEnableMdmFEC(self, enable=True, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg fecEnable = (0,1)[enable]<<7 fecMask = ~(1<<7) self.radiocfg.mdmcfg1 &= fecMask self.radiocfg.mdmcfg1 |= fecEnable self.setRFRegister(MDMCFG1, (self.radiocfg.mdmcfg1)) def getEnableMdmFEC(self, radiocfg=None): if radiocfg == None: self.getRadioConfig() radiocfg = self.radiocfg mdmcfg1 = radiocfg.mdmcfg1 fecEnable = (mdmcfg1>>7) & 0x01 return fecEnable def setEnableMdmDCFilter(self, enable=True, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg dcfEnable = (0,1)[enable]<<7 dcfMask = ~(1<<7) radiocfg.mdmcfg2 &= dcfMask radiocfg.mdmcfg2 |= dcfEnable self.setRFRegister(MDMCFG2, radiocfg.mdmcfg2) def getEnableMdmDCFilter(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg dcfEnable = (radiocfg.mdmcfg2>>7) & 0x1 return dcfEnable def setFsIF(self, freq_if, mhz=24, radiocfg=None): ''' Note that the SmartRF Studio software automatically calculates the optimum register setting based on channel spacing and channel filter bandwidth. (from cc1110f32.pdf) ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg ifBits = freq_if * pow(2,10) / (1000000.0 * mhz) ifBits = int(ifBits + .5) # rounded evenly if ifBits >0x1f: raise(Exception("FAIL: freq_if is too high? freqbits: %x (must be <0x1f)" % ifBits)) self.radiocfg.fsctrl1 &= ~(0x1f) self.radiocfg.fsctrl1 |= int(ifBits) self.setRFRegister(FSCTRL1, (self.radiocfg.fsctrl1)) def getFsIF(self, mhz=24, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg freq_if = (radiocfg.fsctrl1&0x1f) * (1000000.0 * mhz / pow(2,10)) return freq_if def setFsOffset(self, if_off, mhz=24, radiocfg=None): ''' Note that the SmartRF Studio software automatically calculates the optimum register setting based on channel spacing and channel filter bandwidth. (from cc1110f32.pdf) ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg self.radiocfg.fsctrl0 = if_off self.setRFRegister(FSCTRL0, (self.radiocfg.fsctrl0)) def getFsOffset(self, mhz=24, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg freqoff = radiocfg.fsctrl0 return freqoff def getChannel(self): self.getRadioConfig() return self.radiocfg.channr def setChannel(self, channr): self.radiocfg.channr = channr self.setRFRegister(CHANNR, (self.radiocfg.channr)) def setMdmChanBW(self, bw, mhz=24, radiocfg=None): ''' For best performance, the channel filter bandwidth should be selected so that the signal bandwidth occupies at most 80% of the channel filter bandwidth. The channel centre tolerance due to crystal accuracy should also be subtracted from the signal bandwidth. The following example illustrates this: With the channel filter bandwidth set to 500 kHz, the signal should stay within 80% of 500 kHz, which is 400 kHz. Assuming 915 MHz frequency and +/-20 ppm frequency uncertainty for both the transmitting device and the receiving device, the total frequency uncertainty is +/-40 ppm of 915 MHz, which is +/-37 kHz. If the whole transmitted signal bandwidth is to be received within 400 kHz, the transmitted signal bandwidth should be maximum 400 kHz - 2*37 kHz, which is 326 kHz. DR:1.2kb Dev:5.1khz Mod:GFSK RXBW:63kHz sensitive fsctrl1:06 mdmcfg:e5 a3 13 23 11 dev:16 foc/bscfg:17/6c agctrl:03 40 91 frend:56 10 DR:1.2kb Dev:5.1khz Mod:GFSK RXBW:63kHz lowpower fsctrl1:06 mdmcfg:e5 a3 93 23 11 dev:16 foc/bscfg:17/6c agctrl:03 40 91 frend:56 10 (DEM_DCFILT_OFF) DR:2.4kb Dev:5.1khz Mod:GFSK RXBW:63kHz sensitive fsctrl1:06 mdmcfg:e6 a3 13 23 11 dev:16 foc/bscfg:17/6c agctrl:03 40 91 frend:56 10 DR:2.4kb Dev:5.1khz Mod:GFSK RXBW:63kHz lowpower fsctrl1:06 mdmcfg:e6 a3 93 23 11 dev:16 foc/bscfg:17/6c agctrl:03 40 91 frend:56 10 (DEM_DCFILT_OFF) DR:38.4kb Dev:20khz Mod:GFSK RXBW:94kHz sensitive fsctrl1:08 mdmcfg:ca a3 13 23 11 dev:36 foc/bscfg:16/6c agctrl:43 40 91 frend:56 10 (IF changes, Deviation) DR:38.4kb Dev:20khz Mod:GFSK RXBW:94kHz lowpower fsctrl1:08 mdmcfg:ca a3 93 23 11 dev:36 foc/bscfg:16/6c agctrl:43 40 91 frend:56 10 (.. DEM_DCFILT_OFF) DR:250kb Dev:129khz Mod:GFSK RXBW:600kHz sensitive fsctrl1:0c mdmcfg:1d 55 13 23 11 dev:63 foc/bscfg:1d/1c agctrl:c7 00 b0 frend:b6 10 (IF_changes, Deviation) DR:500kb Mod:MSK RXBW:750kHz sensitive fsctrl1:0e mdmcfg:0e 55 73 43 11 dev:00 foc/bscfg:1d/1c agctrl:c7 00 b0 frend:b6 10 (IF_changes, Modulation of course, Deviation has different meaning with MSK) ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg chanbw_e = None chanbw_m = None for e in range(4): m = int(((mhz*1000000.0 / (bw *pow(2,e) * 8.0 )) - 4) + .5) # rounded evenly if m < 4: chanbw_e = e chanbw_m = m break if chanbw_e is None: raise(Exception("ChanBW does not translate into acceptable parameters. Should you be changing this?")) bw = 1000.0*mhz / (8.0*(4+chanbw_m) * pow(2,chanbw_e)) #print "chanbw_e: %x chanbw_m: %x chanbw: %f kHz" % (e, m, bw) self.radiocfg.mdmcfg4 &= 0x0f self.radiocfg.mdmcfg4 |= ((chanbw_e<<6) | (chanbw_m<<4)) self.setRFRegister(MDMCFG4, (self.radiocfg.mdmcfg4)) def getMdmChanBW(self, mhz=24, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg chanbw_e = (self.radiocfg.mdmcfg4 >> 6) & 0x3 chanbw_m = (self.radiocfg.mdmcfg4 >> 4) & 0x3 bw = 1000000.0*mhz / (8.0*(4+chanbw_m) * pow(2,chanbw_e)) #print "chanbw_e: %x chanbw_m: %x chanbw: %f hz" % (chanbw_e, chanbw_m, bw) return bw def setMdmDRate(self, drate, mhz=24, radiocfg=None): ''' set the baud of data being modulated through the radio ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg drate_e = None drate_m = None for e in range(16): m = int((drate * pow(2,28) / (pow(2,e)* (mhz*1000000.0))-256) + .5) # rounded evenly if m < 256: drate_e = e drate_m = m break if drate_e is None: raise(Exception("DRate does not translate into acceptable parameters. Should you be changing this?")) drate = 1000000.0 * mhz * (256+drate_m) * pow(2,drate_e) / pow(2,28) if self._debug: print "drate_e: %x drate_m: %x drate: %f Hz" % (drate_e, drate_m, drate) radiocfg.mdmcfg3 = drate_m radiocfg.mdmcfg4 &= 0xf0 radiocfg.mdmcfg4 |= drate_e self.setRFRegister(MDMCFG3, (radiocfg.mdmcfg3)) self.setRFRegister(MDMCFG4, (radiocfg.mdmcfg4)) def getMdmDRate(self, mhz=24, radiocfg=None): ''' get the baud of data being modulated through the radio ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg drate_e = radiocfg.mdmcfg4 & 0xf drate_m = radiocfg.mdmcfg3 drate = 1000000.0 * mhz * (256+drate_m) * pow(2,drate_e) / pow(2,28) #print "drate_e: %x drate_m: %x drate: %f hz" % (drate_e, drate_m, drate) return drate def setMdmDeviatn(self, deviatn, mhz=24, radiocfg=None): ''' configure the deviation settings for the given modulation scheme ''' if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg dev_e = None dev_m = None for e in range(8): m = int((deviatn * pow(2,17) / (pow(2,e)* (mhz*1000000.0))-8) + .5) # rounded evenly if m < 8: dev_e = e dev_m = m break if dev_e is None: raise(Exception("Deviation does not translate into acceptable parameters. Should you be changing this?")) dev = 1000000.0 * mhz * (8+dev_m) * pow(2,dev_e) / pow(2,17) #print "dev_e: %x dev_m: %x deviatn: %f Hz" % (e, m, dev) self.radiocfg.deviatn = (dev_e << 4) | dev_m self.setRFRegister(DEVIATN, self.radiocfg.deviatn) def getMdmDeviatn(self, mhz=24, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg dev_e = radiocfg.deviatn >> 4 dev_m = radiocfg.deviatn & 0x7 dev = 1000000.0 * mhz * (8+dev_m) * pow(2,dev_e) / pow(2,17) return dev def setMdmSyncWord(self, word, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg radiocfg.sync1 = word >> 8 radiocfg.sync0 = word & 0xff self.setRFRegister(SYNC1, (self.radiocfg.sync1)) self.setRFRegister(SYNC0, (self.radiocfg.sync0)) def getMdmSyncMode(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg return radiocfg.mdmcfg2&0x07 def setMdmSyncMode(self, syncmode=SYNCM_15_of_16, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg radiocfg.mdmcfg2 &= 0xf8 radiocfg.mdmcfg2 |= syncmode self.setRFRegister(MDMCFG2, (self.radiocfg.mdmcfg2)) def getBSLimit(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg return radiocfg.bscfg&BSCFG_BS_LIMIT def setBSLimit(self, bslimit, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg radiocfg.bscfg &= ~BSCFG_BS_LIMIT radiocfg.bscfg |= bslimit self.setRFRegister(BSCFG, (self.radiocfg.bscfg)) def calculateMdmDeviatn(self, mhz=24, radiocfg=None): ''' calculates the optimal DEVIATN setting for the current freq/baud * totally experimental * from Smart RF Studio: 1.2 kbaud 5.1khz dev 2.4 kbaud 5.1khz dev 38.4 kbaud 20khz dev 250 kbaud 129khz dev ''' baud = self.getMdmDRate(mhz, radiocfg) if baud <= 2400: deviatn = 5100 elif baud <= 38400: deviatn = 20000 * ((baud-2400)/36000) else: deviatn = 129000 * ((baud-38400)/211600) self.setMdmDeviatn(deviatn) def calculatePktChanBW(self, mhz=24, radiocfg=None): ''' calculates the optimal ChanBW setting for the current freq/baud * totally experimental * from Smart RF Studio: 1.2 kbaud BW: 63khz 2.4 kbaud BW: 63khz 38.4kbaud BW: 94khz 250 kbaud BW: 600khz ''' freq, freqhex = self.getFreq() center_freq = freq + 14000000 freq_uncertainty = 20e-6 * freq # +-20ppm freq_uncertainty *= 2 # both xmitter and receiver #minbw = (2 * freq_uncertainty) + self.getMdmDRate() # uncertainty for both sender/receiver minbw = (self.getMdmDRate() + freq_uncertainty) possibles = [ 53e3,63e3,75e3,93e3,107e3,125e3,150e3,188e3,214e3,250e3,300e3,375e3,428e3,500e3,600e3,750e3, ] for bw in possibles: #if (.8 * bw) > minbw: # can't occupy more the 80% of BW if (bw) > minbw: break self.setMdmChanBW(bw, mhz, radiocfg) def calculateFsIF(self, mhz=24, radiocfg=None): ''' calculates the optimal IF setting for the current freq/baud * totally experimental * 1.2 kbaud IF: 140khz 2.4 kbaud IF: 140khz 38.4kbaud IF: 164khz (140khz for "sensitive" version) 250 kbaud IF: 281khz 500 kbaud IF: 328khz ''' pass def calculateFsOffset(self, mhz=24, radiocfg=None): ''' calculates the optimal FreqOffset setting for the current freq/baud * totally experimental * ''' pass def reprModemConfig(self, mhz=24, radiocfg=None): output = [] if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg reprMdmModulation = self.reprMdmModulation(radiocfg) syncmode = self.getMdmSyncMode(radiocfg) bw = self.getMdmChanBW(mhz, radiocfg) output.append("ChanBW: %f hz"%bw) drate = self.getMdmDRate(mhz, radiocfg) output.append("DRate: %f hz"%drate) bslimit = self.radiocfg.bscfg & BSCFG_BS_LIMIT output.append("BSLimit: %s"%BSLIMITS[bslimit]) output.append("DC Filter: %s" % (("enabled", "disabled")[self.getEnableMdmDCFilter(radiocfg)])) output.append(reprMdmModulation) output.append("DEVIATION: %f hz" % self.getMdmDeviatn(mhz, radiocfg)) output.append("Sync Mode: %s" % SYNCMODES[syncmode]) mchstr = self.getEnableMdmManchester(radiocfg) output.append("Manchester Encoding: %s" % (("disabled","enabled")[mchstr])) fec = self.getEnableMdmFEC(radiocfg) output.append("Fwd Err Correct: %s" % (("disabled","enabled")[fec])) num_preamble = (radiocfg.mdmcfg1>>4)&7 output.append("Min TX Preamble: %d bytes" % (NUM_PREAMBLE[num_preamble]) ) chanspc = self.getMdmChanSpc(mhz, radiocfg) output.append("Chan Spacing: %f hz" % chanspc) return "\n".join(output) def getRSSI(self): rssi = self.peek(RSSI) return rssi def getLQI(self): lqi = self.peek(LQI) return lqi def reprRadioTestSignalConfig(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg output = [] #output.append("GDO2_INV: %s" % ("do not Invert Output", "Invert output")[(radiocfg.iocfg2>>6)&1]) #output.append("GDO2CFG: 0x%x" % (radiocfg.iocfg2&0x3f)) #output.append("GDO_DS: %s" % (("minimum drive (>2.6vdd","Maximum drive (<2.6vdd)")[radiocfg.iocfg1>>7])) #output.append("GDO1_INV: %s" % ("do not Invert Output", "Invert output")[(radiocfg.iocfg1>>6)&1]) #output.append("GDO1CFG: 0x%x"%(radiocfg.iocfg1&0x3f)) #output.append("GDO0_INV: %s" % ("do not Invert Output", "Invert output")[(radiocfg.iocfg0>>6)&1]) #output.append("GDO0CFG: 0x%x"%(radiocfg.iocfg0&0x3f)) output.append("TEST2: 0x%x"%radiocfg.test2) output.append("TEST1: 0x%x"%radiocfg.test1) output.append("TEST0: 0x%x"%(radiocfg.test0&0xfd)) output.append("VCO_SEL_CAL_EN: 0x%x"%((radiocfg.test2>>1)&1)) return "\n".join(output) def reprFreqConfig(self, mhz=24, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg output = [] freq,num = self.getFreq(mhz, radiocfg) output.append("Frequency: %f hz (%s)" % (freq,num)) output.append("Channel: %d" % radiocfg.channr) freq_if = self.getFsIF(mhz, radiocfg) freqoff = self.getFsOffset(mhz, radiocfg) output.append("Intermediate freq: %d hz" % freq_if) output.append("Frequency Offset: %d +/-" % freqoff) return "\n".join(output) def reprPacketConfig(self, radiocfg=None): if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg output = [] output.append("Sync Bytes: %.2x %.2x" % (radiocfg.sync1, radiocfg.sync0)) output.append("Packet Length: %d" % radiocfg.pktlen) output.append("Configured Address: 0x%x" % radiocfg.addr) pqt = self.getPktPQT(radiocfg) output.append("Preamble Quality Threshold: 4 * %d" % pqt) append = (radiocfg.pktctrl1>>2) & 1 output.append("Append Status: %s" % ("No","Yes")[append]) adr_chk = radiocfg.pktctrl1&3 output.append("Rcvd Packet Check: %s" % ADR_CHK_TYPES[adr_chk]) whitedata = self.getEnablePktDataWhitening(radiocfg) output.append("Data Whitening: %s" % ("off", "ON (but only with cc2400_en==0)")[whitedata]) pkt_format = (radiocfg.pktctrl0>>5)&3 output.append("Packet Format: %s" % PKT_FORMATS[pkt_format]) crc = self.getEnablePktCRC(radiocfg) output.append("CRC: %s" % ("disabled", "ENABLED")[crc]) length_config = radiocfg.pktctrl0&3 output.append("Length Config: %s" % LENGTH_CONFIGS[length_config]) return "\n".join(output) """ SYNC1 = 0xa9; SYNC0 = 0x47; PKTLEN = 0xff; PKTCTRL1 = 0x04; // APPEND_STATUS PKTCTRL0 = 0x01; // VARIABLE LENGTH, no crc, no whitening ADDR = 0x00; CHANNR = 0x00; FSCTRL1 = 0x0c; // IF FSCTRL0 = 0x00; FREQ2 = 0x25; FREQ1 = 0x95; FREQ0 = 0x55; MDMCFG4 = 0x1d; // chan_bw and drate_e MDMCFG3 = 0x55; // drate_m MDMCFG2 = 0x13; // gfsk, 30/32+carrier sense sync MDMCFG1 = 0x23; // 4-preamble-bytes, chanspc_e MDMCFG0 = 0x11; // chanspc_m DEVIATN = 0x63; MCSM2 = 0x07; // RX_TIMEOUT MCSM1 = 0x30; // CCA_MODE RSSI below threshold unless currently recvg pkt MCSM0 = 0x18; // fsautosync when going from idle to rx/tx/fstxon FOCCFG = 0x1d; BSCFG = 0x1c; // bit sync config AGCCTRL2 = 0xc7; AGCCTRL1 = 0x00; AGCCTRL0 = 0xb0; FREND1 = 0xb6; FREND0 = 0x10; FSCAL3 = 0xea; FSCAL2 = 0x2a; FSCAL1 = 0x00; FSCAL0 = 0x1f; TEST2 = 0x88; TEST1 = 0x31; TEST0 = 0x09; PA_TABLE0 = 0x83; """ def reprRadioState(self, radiocfg=None): output = [] try: if radiocfg==None: self.getRadioConfig() radiocfg = self.radiocfg output.append(" MARCSTATE: %s (%x)" % (self.getMARCSTATE(radiocfg))) output.append(" DONGLE RESPONDING: mode :%x, last error# %d"%(self.getDebugCodes())) except: output.append(repr(sys.exc_info())) output.append(" DONGLE *not* RESPONDING") return "\n".join(output) def reprClientState(self): output = [] output.append(' client thread cycles: %d' % self.threadcounter) output.append(' client errored cycles: %d' % self._usberrorcnt) output.append(' recv_queue:\t\t (%d bytes) "%s"'%(len(self.recv_queue),repr(self.recv_queue)[:len(self.recv_queue)%39+20])) output.append(' trash: \t\t (%d bytes) "%s"'%(len(self.trash),repr(self.trash)[:min(len(self.trash),39)+20])) output.append(' recv_mbox \t\t (%d keys) "%s"'%(len(self.recv_mbox),repr(self.recv_mbox)[:min(len(repr(self.recv_mbox)),79)])) for app in self.recv_mbox.keys(): appbox = self.recv_mbox[app] output.append(' app 0x%x\t (%d records) "%s"'%(app,len(appbox),repr(appbox)[:min(len(repr(appbox)),79)])) for cmd in appbox.keys(): strlen = min(len(repr(appbox[cmd])),79) output.append(' [0x%x]\t (%d records) "%s"'%(cmd, len(appbox[cmd]), repr(appbox[cmd])[:strlen])) return "\n".join(output) ######## APPLICATION METHODS ######## def setup900MHz(self): self.getRadioConfig() rc = self.radiocfg rc.iocfg0 = 0x06 rc.sync1 = 0x0b rc.sync0 = 0x0b rc.pktlen = 0xff rc.pktctrl1 = 0xe5 rc.pktctrl0 = 0x04 rc.fsctrl1 = 0x12 rc.fsctrl0 = 0x00 rc.addr = 0x00 rc.channr = 0x00 rc.mdmcfg4 = 0x3e rc.mdmcfg3 = 0x55 rc.mdmcfg2 = 0x73 rc.mdmcfg1 = 0x23 rc.mdmcfg0 = 0x55 rc.mcsm2 = 0x07 rc.mcsm1 = 0x30 rc.mcsm0 = 0x00 rc.deviatn = 0x16 rc.foccfg = 0x17 rc.bscfg = 0x6c rc.agcctrl2 |= AGCCTRL2_MAX_DVGA_GAIN rc.agcctrl2 = 0x03 rc.agcctrl1 = 0x40 rc.agcctrl0 = 0x91 rc.frend1 = 0x56 rc.frend0 = 0x10 rc.fscal3 = 0xEA rc.fscal2 = 0x2A rc.fscal1 = 0x00 rc.fscal0 = 0x1F rc.test2 = 0x88 rc.test1 = 0x31 rc.test0 = 0x09 rc.pa_table0 = 0xc0 self.setRadioConfig() def setup900MHzHopTrans(self): self.getRadioConfig() rc = self.radiocfg rc.iocfg0 = 0x06 rc.sync1 = 0x0b rc.sync0 = 0x0b rc.pktlen = 0xff rc.pktctrl1 = 0x04 rc.pktctrl0 = 0x05 rc.addr = 0x00 rc.channr = 0x00 rc.fsctrl1 = 0x06 rc.fsctrl0 = 0x00 rc.mdmcfg4 = 0xee rc.mdmcfg3 = 0x55 rc.mdmcfg2 = 0x73 rc.mdmcfg1 = 0x23 rc.mdmcfg0 = 0x55 rc.mcsm2 = 0x07 rc.mcsm1 = 0x30 rc.mcsm0 = 0x18 rc.deviatn = 0x16 rc.foccfg = 0x17 rc.bscfg = 0x6c rc.agcctrl2 = 0x03 rc.agcctrl1 = 0x40 rc.agcctrl0 = 0x91 rc.frend1 = 0x56 rc.frend0 = 0x10 rc.fscal3 = 0xEA rc.fscal2 = 0x2A rc.fscal1 = 0x00 rc.fscal0 = 0x1F rc.test2 = 0x88 rc.test1 = 0x31 rc.test0 = 0x09 rc.pa_table0 = 0xc0 self.setRadioConfig() def setup900MHzContTrans(self): self.getRadioConfig() rc = self.radiocfg rc.iocfg0 = 0x06 rc.sync1 = 0x0b rc.sync0 = 0x0b rc.pktlen = 0xff rc.pktctrl1 = 0x04 rc.pktctrl0 = 0x05 rc.addr = 0x00 rc.channr = 0x00 rc.fsctrl1 = 0x06 rc.fsctrl0 = 0x00 rc.freq2 = 0x26 rc.freq1 = 0x55 rc.freq0 = 0x55 rc.mdmcfg4 = 0xee rc.mdmcfg3 = 0x55 rc.mdmcfg2 = 0x73 rc.mdmcfg1 = 0x23 rc.mdmcfg0 = 0x55 rc.mcsm2 = 0x07 rc.mcsm1 = 0x30 rc.mcsm0 = 0x18 rc.deviatn = 0x16 rc.foccfg = 0x17 rc.bscfg = 0x6c rc.agcctrl2 = 0x03 rc.agcctrl1 = 0x40 rc.agcctrl0 = 0x91 rc.frend1 = 0x56 rc.frend0 = 0x10 rc.fscal3 = 0xEA rc.fscal2 = 0x2A rc.fscal1 = 0x00 rc.fscal0 = 0x1F rc.test2 = 0x88 rc.test1 = 0x31 rc.test0 = 0x09 rc.pa_table0 = 0xc0 self.setRadioConfig() def setup_rfstudio_902PktTx(self): self.getRadioConfig() rc = self.radiocfg rc.iocfg2 = 0x00 rc.iocfg1 = 0x00 rc.iocfg0 = 0x06 rc.sync1 = 0x0b rc.sync0 = 0x0b rc.pktlen = 0xff rc.pktctrl1 = 0x04 rc.pktctrl0 = 0x05 rc.addr = 0x00 rc.channr = 0x00 rc.fsctrl1 = 0x0c rc.fsctrl0 = 0x00 rc.freq2 = 0x25 rc.freq1 = 0x95 rc.freq0 = 0x55 rc.mdmcfg4 = 0x1d rc.mdmcfg3 = 0x55 rc.mdmcfg2 = 0x13 rc.mdmcfg1 = 0x23 rc.mdmcfg0 = 0x11 rc.mcsm2 = 0x07 rc.mcsm1 = 0x30 rc.mcsm0 = 0x18 rc.deviatn = 0x63 rc.foccfg = 0x1d rc.bscfg = 0x1c rc.agcctrl2 = 0xc7 rc.agcctrl1 = 0x00 rc.agcctrl0 = 0xb0 rc.frend1 = 0xb6 rc.frend0 = 0x10 rc.fscal3 = 0xEA rc.fscal2 = 0x2A rc.fscal1 = 0x00 rc.fscal0 = 0x1F rc.test2 = 0x88 rc.test1 = 0x31 rc.test0 = 0x09 rc.pa_table7 = 0x00 rc.pa_table6 = 0x00 rc.pa_table5 = 0x00 rc.pa_table4 = 0x00 rc.pa_table3 = 0x00 rc.pa_table2 = 0x00 rc.pa_table1 = 0x00 #rc.pa_table0 = 0x8e rc.pa_table0 = 0xc0 self.setRadioConfig() def testTX(self, data="XYZABCDEFGHIJKL"): while (sys.stdin not in select.select([sys.stdin],[],[],0)[0]): time.sleep(.4) print "transmitting %s" % repr(data) self.RFxmit(data) sys.stdin.read(1) def lowball(self, level=1, sync=0xaaaa, length=250, pqt=0, crc=False, fec=False, datawhite=False): ''' this configures the radio to the lowest possible level of filtering, potentially allowing complete radio noise to come through as data. very useful in some circumstances. level == 0 changes the Sync Mode to SYNCM_NONE (wayyy more garbage) level == 1 (default) sets the Sync Mode to SYNCM_CARRIER (requires a valid carrier detection for the data to be considered a packet) level == 2 sets the Sync Mode to SYNCM_CARRIER_15_of_16 (requires a valid carrier detection and 15 of 16 bits of SYNC WORD match for the data to be considered a packet) level == 3 sets the Sync Mode to SYNCM_CARRIER_16_of_16 (requires a valid carrier detection and 16 of 16 bits of SYNC WORD match for the data to be considered a packet) ''' if hasattr(self, '_last_radiocfg') and len(self._last_radiocfg): print('not saving radio state. already have one saved. use lowballRestore() to restore the saved config and the next time you run lowball() the radio config will be saved.') else: self._last_radiocfg = self.getRadioConfig() self.makePktFLEN(length) self.setEnablePktCRC(crc) self.setEnableMdmFEC(fec) self.setEnablePktDataWhitening(datawhite) self.setMdmSyncWord(sync) self.setPktPQT(pqt) if (level == 3): self.setMdmSyncMode(SYNCM_CARRIER_16_of_16) elif (level == 2): self.setMdmSyncMode(SYNCM_15_of_16) elif (level == 1): self.setMdmSyncMode(SYNCM_CARRIER) else: self.setMdmSyncMode(SYNCM_NONE) def lowballRestore(self): if not hasattr(self, '_last_radiocfg'): raise(Exception("lowballRestore requires that lowball have been executed first (it saves radio config state!)")) self.setRadioConfig(self._last_radiocfg) self._last_radiocfg = '' def checkRepr(self, matchstr, checkval, maxdiff=0): starry = self.reprRadioConfig().split('\n') line,val = getValueFromReprString(starry, matchstr) try: f = checkval.__class__(val.split(" ")[0]) if abs(f-checkval) <= maxdiff: print " passed: reprRadioConfig test: %s %s" % (repr(val), checkval) else: print " *FAILED* reprRadioConfig test: %s %s %s" % (repr(line), repr(val), checkval) except ValueError, e: print " ERROR checking repr: %s" % e def unittest(self, mhz=24): print "\nTesting USB ping()" self.ping(3) print "\nTesting USB ep0Ping()" self.ep0Ping() print "\nTesting USB enumeration" print "getString(0,100): %s" % repr(self._do.getString(0,100)) print "\nTesting USB EP MAX_PACKET_SIZE handling (ep0Peek(0xf000, 100))" print repr(self.ep0Peek(0xf000, 100)) print "\nTesting USB EP MAX_PACKET_SIZE handling (peek(0xf000, 300))" print repr(self.peek(0xf000, 400)) print "\nTesting USB poke/peek" data = "".join([chr(c) for c in xrange(120)]) where = 0xf300 self.poke(where, data) ndata = self.peek(where, len(data)) if ndata != data: print " *FAILED*\n '%s'\n '%s'" % (data.encode("hex"), ndata.encode("hex")) raise(Exception(" *FAILED*\n '%s'\n '%s'" % (data.encode("hex"), ndata.encode("hex")))) else: print " passed '%s'" % (ndata.encode("hex")) print "\nTesting getValueFromReprString()" starry = self.reprRadioConfig().split('\n') print repr(getValueFromReprString(starry, 'hz')) print "\nTesting reprRadioConfig()" print self.reprRadioConfig() print "\nTesting Frequency Get/Setters" # FREQ freq0,freq0str = self.getFreq() testfreq = 902000000 self.setFreq(testfreq) freq,freqstr = self.getFreq() if abs(testfreq - freq) < 1024: print " passed: %d : %f (diff: %f)" % (testfreq, freq, testfreq-freq) else: print " *FAILED* %d : %f (diff: %f)" % (testfreq, freq, testfreq-freq) testfreq = 868000000 self.setFreq(testfreq) freq,freqstr = self.getFreq() if abs(testfreq - freq) < 1024: print " passed: %d : %f (diff: %f)" % (testfreq, freq, testfreq-freq) else: print " *FAILED* %d : %f (diff: %f)" % (testfreq, freq, testfreq-freq) testfreq = 433000000 self.setFreq(testfreq) freq,freqstr = self.getFreq() if abs(testfreq - freq) < 1024: print " passed: %d : %f (diff: %f)" % (testfreq, freq, testfreq-freq) else: print " *FAILED* %d : %f (diff: %f)" % (testfreq, freq, testfreq-freq) self.checkRepr("Frequency:", float(testfreq), 1024) self.setFreq(freq0) # CHANNR channr0 = self.getChannel() for x in range(15): self.setChannel(x) channr = self.getChannel() if channr != x: print " *FAILED* get/setChannel(): %d : %d" % (x, channr) else: print " passed: get/setChannel(): %d : %d" % (x, channr) self.checkRepr("Channel:", channr) self.setChannel(channr0) # IF and FREQ_OFF freq_if = self.getFsIF() freqoff = self.getFsOffset() for fif, foff in ((164062,1),(140625,2),(187500,3)): self.setFsIF(fif) self.setFsOffset(foff) nfif = self.getFsIF() nfoff = self.getFsOffset() if abs(nfif - fif) > 5: print " *FAILED* get/setFsIFandOffset(): %d : %f (diff: %f)" % (fif,nfif,nfif-fif) else: print " passed: get/setFsIFandOffset(): %d : %f (diff: %f)" % (fif,nfif,nfif-fif) if foff != nfoff: print " *FAILED* get/setFsIFandOffset(): %d : %d (diff: %d)" % (foff,nfoff,nfoff-foff) else: print " passed: get/setFsIFandOffset(): %d : %d (diff: %d)" % (foff,nfoff,nfoff-foff) self.checkRepr("Intermediate freq:", fif, 11720) self.checkRepr("Frequency Offset:", foff) self.setFsIF(freq_if) self.setFsOffset(freqoff) ### continuing with more simple tests. add completeness later? # Modem tests mod = self.getMdmModulation(self.radiocfg) self.setMdmModulation(mod, self.radiocfg) modcheck = self.getMdmModulation(self.radiocfg) if mod != modcheck: print " *FAILED* get/setMdmModulation(): %d : %d " % (mod, modcheck) else: print " passed: get/setMdmModulation(): %d : %d " % (mod, modcheck) chanspc = self.getMdmChanSpc(mhz, self.radiocfg) self.setMdmChanSpc(chanspc, mhz, self.radiocfg) chanspc_check = self.getMdmChanSpc(mhz, self.radiocfg) if chanspc != chanspc_check: print " *FAILED* get/setMdmChanSpc(): %d : %d" % (chanspc, chanspc_check) else: print " passed: get/setMdmChanSpc(): %d : %d" % (chanspc, chanspc_check) chanbw = self.getMdmChanBW(mhz, self.radiocfg) self.setMdmChanBW(chanbw, mhz, self.radiocfg) chanbw_check = self.getMdmChanBW(mhz, self.radiocfg) if chanbw != chanbw_check: print " *FAILED* get/setMdmChanBW(): %d : %d" % (chanbw, chanbw_check) else: print " passed: get/setMdmChanBW(): %d : %d" % (chanbw, chanbw_check) drate = self.getMdmDRate(mhz, self.radiocfg) self.setMdmDRate(drate, mhz, self.radiocfg) drate_check = self.getMdmDRate(mhz, self.radiocfg) if drate != drate_check: print " *FAILED* get/setMdmDRate(): %d : %d" % (drate, drate_check) else: print " passed: get/setMdmDRate(): %d : %d" % (drate, drate_check) deviatn = self.getMdmDeviatn(mhz, self.radiocfg) self.setMdmDeviatn(deviatn, mhz, self.radiocfg) deviatn_check = self.getMdmDeviatn(mhz, self.radiocfg) if deviatn != deviatn_check: print " *FAILED* get/setMdmdeviatn(): %d : %d" % (deviatn, deviatn_check) else: print " passed: get/setMdmdeviatn(): %d : %d" % (deviatn, deviatn_check) syncm = self.getMdmSyncMode(self.radiocfg) self.setMdmSyncMode(syncm, self.radiocfg) syncm_check = self.getMdmSyncMode(self.radiocfg) if syncm != syncm_check: print " *FAILED* get/setMdmSyncMode(): %d : %d" % (syncm, syncm_check) else: print " passed: get/setMdmSyncMode(): %d : %d" % (syncm, syncm_check) mchstr = self.getEnableMdmManchester(self.radiocfg) self.setEnableMdmManchester(mchstr, self.radiocfg) mchstr_check = self.getEnableMdmManchester(self.radiocfg) if mchstr != mchstr_check: print " *FAILED* get/setMdmManchester(): %d : %d" % (mchstr, mchstr_check) else: print " passed: get/setMdmManchester(): %d : %d" % (mchstr, mchstr_check) fec = self.getEnableMdmFEC(self.radiocfg) self.setEnableMdmFEC(fec, self.radiocfg) fec_check = self.getEnableMdmFEC(self.radiocfg) if fec != fec_check: print " *FAILED* get/setEnableMdmFEC(): %d : %d" % (fec, fec_check) else: print " passed: get/setEnableMdmFEC(): %d : %d" % (fec, fec_check) dcf = self.getEnableMdmDCFilter(self.radiocfg) self.setEnableMdmDCFilter(dcf, self.radiocfg) dcf_check = self.getEnableMdmDCFilter(self.radiocfg) if dcf != dcf_check: print " *FAILED* get/setEnableMdmDCFilter(): %d : %d" % (dcf, dcf_check) else: print " passed: get/setEnableMdmDCFilter(): %d : %d" % (dcf, dcf_check) # Pkt tests pqt = self.getPktPQT(self.radiocfg) self.setPktPQT(pqt, self.radiocfg) pqt_check = self.getPktPQT(self.radiocfg) if pqt != pqt_check: print " *FAILED* get/setEnableMdmFEC(): %d : %d" % (pqt, pqt_check) else: print " passed: get/setEnableMdmFEC(): %d : %d" % (pqt, pqt_check) def getValueFromReprString(stringarray, line_text): for string in stringarray: if line_text in string: idx = string.find(":") val = string[idx+1:].strip() return (string,val) def mkFreq(freq=902000000, mhz=24): freqmult = (0x10000 / 1000000.0) / mhz num = int(freq * freqmult) freq2 = num >> 16 freq1 = (num>>8) & 0xff freq0 = num & 0xff return (num, freq2,freq1,freq0) if __name__ == "__main__": idx = 0 if len(sys.argv) > 1: idx = int(sys.argv.pop()) d = USBDongle(idx=idx)
Python
#!/usr/bin/python import sys, serial port = "ACM0" if len(sys.argv) > 1: port = sys.argv.pop() dport = "/dev/tty" + port print "Opening serial port %s for listening..." % dport s=serial.Serial(dport, 115200) counter = 0 while True: print ("%d: %s" % (counter, repr(s.read(12)))) counter += 1 #sys.stdout.write(s.read(1)) #sys.stdout.flush()
Python
import struct def shiftString(string, bits): carry = 0 news = [] for x in xrange(len(string)-1): newc = ((ord(string[x]) << bits) + (ord(string[x+1]) >> (8-bits))) & 0xff news.append("%c"%newc) newc = (ord(string[-1])<<bits) & 0xff news.append("%c"%newc) return "".join(news) def findDword(byts, inverted=False): possDwords = [] # find the preamble (if any) bitoff = 0 while True: sbyts = byts pidx = byts.find("\xaa\xaa") if pidx == -1: pidx = byts.find("\x55\x55") bitoff = 1 if pidx == -1: return possDwords # chop off the nonsense before the preamble sbyts = byts[pidx:] #print "sbyts: %s" % repr(sbyts) # find the definite end of the preamble (ie. it may be sooner, but we know this is the end) while (sbyts[0] == ('\xaa', '\x55')[bitoff] and len(sbyts)>2): sbyts = sbyts[1:] #print "sbyts: %s" % repr(sbyts) # now we look at the next 16 bits to narrow the possibilities to 8 # at this point we have no hints at bit-alignment aside from 0xaa vs 0x55 dwbits, = struct.unpack(">H", sbyts[:2]) if len(sbyts)>=3: bitcnt = 0 # bits1 = aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb # bits2 = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bits1, = struct.unpack(">H", sbyts[:2]) bits1 = bits1 | (ord(('\xaa','\x55')[bitoff]) << 16) bits1 = bits1 | (ord(('\xaa','\x55')[bitoff]) << 24) bits1 <<= 8 bits1 |= (ord(sbyts[2]) ) bits1 >>= bitoff # now we should be aligned correctly #print "bits: %x" % (bits1) bit = (5 * 8) - 2 # bytes times bits/byte #FIXME: MAGIC NUMBERS!? while (bits1 & (3<<bit) == (2<<bit)): bit -= 2 print "bit = %d" % bit bits1 >>= (bit-16) #while (bits1 & 0x30000 != 0x20000): # now we align the end of the 101010 pattern with the beginning of the dword # bits1 >>= 2 #print "bits: %x" % (bits1) for frontbits in xrange((0,1)[inverted], 17, 2): poss = (bits1 >> frontbits) & 0xffff if not poss in possDwords: possDwords.append(poss) byts = byts[pidx+1:] return possDwords def findDwordDoubled(byts): possDwords = [] # find the preamble (if any) bitoff = 0 pidx = byts.find("\xaa\xaa") if pidx == -1: pidx = byts.find("\55\x55") bitoff = 1 if pidx == -1: return [] # chop off the nonsense before the preamble byts = byts[pidx:] # find the definite end of the preamble (ie. it may be sooner, but we know this is the end) while (byts[0] == ('\xaa', '\x55')[bitoff] and len(byts)>2): byts = byts[1:] # now we look at the next 16 bits to narrow the possibilities to 8 # at this point we have no hints at bit-alignment dwbits, = struct.unpack(">H", byts[:2]) if len(byts)>=5: bitcnt = 0 # bits1 = aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb # bits2 = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bits1, = struct.unpack(">H", byts[:2]) bits1 = bits1 | (ord(('\xaa','\x55')[bitoff]) << 16) bits1 = bits1 | (ord(('\xaa','\x55')[bitoff]) << 24) bits1 <<= 8 bits1 |= (ord(byts[2]) ) bits1 >>= bitoff bits2, = struct.unpack(">L", byts[:4]) bits2 <<= 8 bits2 |= (ord(byts[4]) ) bits2 >>= bitoff frontbits = 0 for frontbits in xrange(16, 40, 2): #FIXME: if this doesn't work, try 16, then 18+frontbits dwb1 = (bits1 >> (frontbits)) & 3 dwb2 = (bits2 >> (frontbits)) & 3 print "\tfrontbits: %d \t\t dwb1: %s dwb2: %s" % (frontbits, bin(bits1 >> (frontbits)), bin(bits2 >> (frontbits))) if dwb2 != dwb1: break # frontbits now represents our unknowns... let's go from the other side now for tailbits in xrange(16, -1, -2): dwb1 = (bits1 >> (tailbits)) & 3 dwb2 = (bits2 >> (tailbits)) & 3 print "\ttailbits: %d\t\t dwb1: %s dwb2: %s" % (tailbits, bin(bits1 >> (tailbits)), bin(bits2 >> (tailbits))) if dwb2 != dwb1: tailbits += 2 break # now, if we have a double syncword, iinm, tailbits + frontbits >= 16 print "frontbits: %d\t\t tailbits: %d, bits: %s " % (frontbits, tailbits, bin((bits2>>tailbits & 0xffffffff))) if (frontbits + tailbits >= 16): tbits = bits2 >> (tailbits&0xffff) tbits &= (0xffffffff) print "tbits: %x" % tbits poss = tbits&0xffffffff if poss not in possDwords: possDwords.append(poss) else: pass # FIXME: what if we *don't* have a double-sync word? then we stop at AAblah or 55blah and take the next word? possDwords.reverse() return possDwords #def test(): def visBits(data): pass def getBit(data, bit): idx = bit / 8 bidx = bit % 8 char = data[idx] return (ord(char)>>(7-bidx)) & 1 def detectRepeatPatterns(data, size=64, minEntropy=.07): c1 = 0 c2 = 0 d1 = 0 p1 = 0 mask = (1<<size) - 1 bitlen = 8*len(data) while p1 < (bitlen-size-8): d1 <<= 1 d1 |= getBit(data, p1) d1 &= mask #print bin(d1) if c1 < (size): p1 += 1 c1 += 1 continue d2 = 0 p2 = p1+size while p2 < (bitlen): d2 <<= 1 d2 |= getBit(data, p2) d2 &= mask #print bin(d2) if c2 < (size): p2 += 1 c2 += 1 continue if d1 == d2 and d1 > 0: s1 = p1 - size s2 = p2 - size print "s1: %d\t p1: %d\t " % (s1, p1) print "s2: %d\t p2: %d\t " % (s2, p2) # complete the pattern until the numbers differ or meet while True: p1 += 1 p2 += 1 #print "s1: %d\t p1: %d\t " % (s1, p1) #print "s2: %d\t p2: %d\t " % (s2, p2) if p2 >= bitlen: break b1 = getBit(data,p1) b2 = getBit(data,p2) if p1 == s2 or b1 != b2: break length = p1 - s1 c2 = 0 p2 -= size bitSection, ent = bitSectString(data, s1, s1+length) if ent > minEntropy: print "success:" print " * bit idx1: %4d (%4d bits) - '%s' %s" % (s1, length, bin(d1), bitSection.encode("hex")) print " * bit idx2: %4d (%4d bits) - '%s'" % (s2, length, bin(d2)) #else: # print " * idx1: %d - '%s' * idx2: %d - '%s'" % (p1, d1, p2, d2) p2 += 1 p1 += 1 def bitSectString(string, startbit, endbit): ''' bitsects a string... ie. chops out the bits from the middle of the string returns the new string and the entropy (ratio of 0:1) ''' ones = 0 zeros = 0 entropy = [zeros, ones] s = '' bit = startbit Bidx = bit / 8 bidx = (bit % 8) while bit < endbit: byte1 = ord( string[Bidx] ) try: byte2 = ord( string[Bidx+1] ) except IndexError: byte2 = 0 byte = (byte1 << bidx) & 0xff byte |= (byte2 >> (8-bidx)) #calculate entropy over the byte for bi in range(8): b = (byte>>bi) & 1 entropy[b] += 1 bit += 8 Bidx += 1 if bit > endbit: diff = bit-endbit mask = ~ ( (1<<diff) - 1 ) byte &= mask s += chr(byte) ent = (min(entropy)+1.0) / (max(entropy)+1) #print "entropy: %f" % ent return (s, ent) def genBitArray(string, startbit, endbit): ''' bitsects a string... ie. chops out the bits from the middle of the string returns the new string and the entropy (ratio of 0:1) ''' binStr, ent = bitSectString(string, startbit, endbit) s = [] for byte in binStr: for bitx in range(7, -1, -1): bit = (byte>>bitx) & 1 s.append(chr(0x30|bit)) return (s, ent) chars_top = [ " ", #000 " ", #001 "^", #010 "/", #011 " ", #100 " ", #101 "\\",#110 "-", #111 ] chars_mid = [ " ", #000 "|", #001 "#", #010 " ", #011 "|", #100 "#", #101 " ", #110 " ", #110 ] chars_bot = [ "-", #000 "/", #001 " ", #010 " ", #011 "\\",#100 "V", #101 " ", #110 " ", #110 ] def reprBitArray(bitAry, width=194): top = [] mid = [] bot = [] # top line for bindex in xrange(width): aryidx = int((1.0 * bindex / width) * len(bitAry)) bits = 0 for bitx in range(3): bits += bitAry[aryidix + bitx] top.append( chars_top[ bits ] ) mid.append( chars_mid[ bits ] ) bot.append( chars_bot[ bits ] ) tops = "".join(top) mids = "".join(mid) bots = "".join(bot) return "\n".join([tops, mids, bots])
Python
#!/usr/bin/env python """ #include<compiler.h> /* ------------------------------------------------------------------------------------------------ * Interrupt Vectors * ------------------------------------------------------------------------------------------------ */ #define RFTXRX_VECTOR 0 /* RF TX done / RX ready */ #define ADC_VECTOR 1 /* ADC End of Conversion */ #define URX0_VECTOR 2 /* USART0 RX Complete */ #define URX1_VECTOR 3 /* USART1 RX Complete */ #define ENC_VECTOR 4 /* AES Encryption/Decryption Complete */ #define ST_VECTOR 5 /* Sleep Timer Compare */ #define P2INT_VECTOR 6 /* Port 2 Inputs */ #define UTX0_VECTOR 7 /* USART0 TX Complete */ #define DMA_VECTOR 8 /* DMA Transfer Complete */ #define T1_VECTOR 9 /* Timer 1 (16-bit) Capture/Compare/Overflow */ #define T2_VECTOR 10 /* Timer 2 (MAC Timer) Overflow */ #define T3_VECTOR 11 /* Timer 3 (8-bit) Capture/Compare/Overflow */ #define T4_VECTOR 12 /* Timer 4 (8-bit) Capture/Compare/Overflow */ #define P0INT_VECTOR 13 /* Port 0 Inputs */ #define UTX1_VECTOR 14 /* USART1 TX Complete */ #define P1INT_VECTOR 15 /* Port 1 Inputs */ #define RF_VECTOR 16 /* RF General Interrupts */ #define WDT_VECTOR 17 /* Watchdog Overflow in Timer Mode */ SFR(P0, 0x80); // Port 0 SBIT(P0_0, 0x80, 0); // Port 0 bit 0 SBIT(P0_1, 0x80, 1); // Port 0 bit 1 SBIT(P0_2, 0x80, 2); // Port 0 bit 2 SBIT(P0_3, 0x80, 3); // Port 0 bit 3 SBIT(P0_4, 0x80, 4); // Port 0 bit 4 SBIT(P0_5, 0x80, 5); // Port 0 bit 5 SBIT(P0_6, 0x80, 6); // Port 0 bit 6 SBIT(P0_7, 0x80, 7); // Port 0 bit 7 SFR(SP, 0x81); // Stack Pointer SFR(DPL0, 0x82); // Data Pointer 0 Low Byte SFR(DPH0, 0x83); // Data Pointer 0 High Byte SFR(DPL1, 0x84); // Data Pointer 1 Low Byte SFR(DPH1, 0x85); // Data Pointer 1 High Byte """ import sys def parseLines(lines): defs = {} incomment = False for line in lines: # find single-line comments slc = line.find("//") if (slc > -1): line = line[:slc] + "#" + line[slc+2:] # find /* */ comments mlcs = line.find("/*") mlce = line.find("*/") if (mlcs>-1): if (mlce>-1): # both are in this line if (mlce>mlcs): # they are "together" if (mlce >= len(line.strip())-3): line = line[:mlcs] + '#' + line[mlcs+2:mlce] else: line = line[:mlcs] + '"""' + line[mlcs+2:mlce] + '"""' + line[mlce+2:] else: # they are *not* together line = line[mlce+2:mlcs] else: # only the beginning is in this line, treat like a single-line comment for now line = line[:mlcs] incomment = True elif incomment: # no mlc-starter found... are we incomment? then ignore until the end of comment if (mlce>-1): line = line[mlce+2:] incomment = False else: line = '' if incomment: # if we're still incomment, this whole line is comment continue # chop initial and trailing whitespace line = line.strip() # now we can actually parse the line if (line.startswith("#define ")): line = line[8:].strip() # peel off any additional spaces after the #define pieces = line.split(" ", 1) if len(pieces)<2: continue name, value = pieces if "(" in name: print >>sys.stderr,("SKIPPING: %s"%(line)) continue # skip adding "function" defines defs[name.strip()] = value.strip() elif (line.startswith("SFR(")): endparen = line.find(")") if (endparen == -1): print >>sys.stderr,("ERROR: SFR without end parens: '%s'"%(line)) continue line = line[4:endparen].strip() name, value = line.split(",", 1) defs[name.strip()] = value.strip() elif (line.startswith("SFRX(")): endparen = line.find(")") if (endparen == -1): print >>sys.stderr,("ERROR: SFRX without end parens: '%s'"%(line)) continue line = line[5:endparen].strip() name, value = line.split(",", 1) defs[name.strip()] = value.strip() elif (line.startswith("SBIT")): endparen = line.find(")") if (endparen == -1): print >>sys.stderr,("ERROR: SBIT without end parens: '%s'"%(line)) continue line = line[5:endparen].strip() name, val1, val2 = line.split(",", 2) defs[name.strip()] = 1 << (int(val2.strip())) return defs if __name__ == '__main__': defs = {} defs.update(parseLines(file('../includes/cc1110-ext.h'))) defs.update(parseLines(file('../includes/cc1111.h'))) defs.update(parseLines(file('/usr/share/sdcc/include/mcs51/cc1110.h'))) skeys = defs.keys() skeys.sort() out = ["%-30s = %s"%(key,defs[key]) for key in skeys] trueout = [] for x in out: try: compile(x,'stdin','exec') trueout.append(x) print(x) except: sys.excepthook(*sys.exc_info())
Python
#!/usr/bin/env ipython from chipcon_nic import * class RfCat(FHSSNIC): def RFdump(self, msg="Receiving", maxnum=100, timeoutms=1000): try: for x in xrange(maxnum): y, t = self.RFrecv(timeoutms) print "(%5.3f) %s: %s" % (t, msg, y.encode('hex')) except ChipconUsbTimeoutException: pass def scan(self, basefreq=902e6, inc=250e3, count=104, delaysec=2, drate=38400, lowball=1): ''' scan for signal over a range of frequencies ''' self.RFdump("Clearing") self.lowball(lowball) self.setMdmDRate(drate) print "Scanning range: " while not keystop(): try: print for freq in xrange(int(basefreq), int(basefreq+(inc*count)), int(inc)): print "Scanning for frequency %d..." % freq self.setFreq(freq) self.RFdump(timeoutms=delaysec*1000) if keystop(): break except KeyboardInterrupt: print "Please press <enter> to stop" sys.stdin.read(1) self.lowballRestore() def rf_configure(*args, **k2args): pass def rf_redirection(self, fdtup): if len(fdtup)>1: fd0i, fd0o = fdtup else: fd0i, = fdtup fd0o, = fdtup fdsock = False # socket or fileio? if hasattr(fd0i, 'recv'): fdsock = True while True: x,y,z = select.select([fd0i ], [], [], .1) #if self._pause: # continue if fd0i in x: if fdsock: data = fd0i.recv(self.max_packet_size) else: data = fd0i.read(self.max_packet_size) if not len(data): # terminated socket break self.RFxmit(data) try: data = self.RFrecv(0) if fdsock: fd0o.sendall(data) else: fd0o.write(data) except ChipconUsbTimeoutException: pass def interactive(idx=0, DongleClass=RfCat, intro=''): import rflib.chipcon_nic as rfnic d = DongleClass(idx=idx) gbls = globals() lcls = locals() try: import IPython.Shell ipsh = IPython.Shell.IPShell(argv=sys.argv, user_ns=lcls, user_global_ns=gbls) print intro ipsh.mainloop(intro) except ImportError, e: try: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! ipsh.mainloop(intro) except ImportError, e: print e shell = code.InteractiveConsole(gbls) shell.interact(intro) if __name__ == "__main__": idx = 0 if len(sys.argv) > 1: idx = int(sys.argv.pop()) interactive(idx)
Python
#!/usr/bin/env ipython import sys import usb import code import time import struct import threading #from chipcondefs import * from cc1111client import * APP_NIC = 0x42 NIC_RECV = 0x1 NIC_XMIT = 0x2 NIC_SET_ID = 0x3 NIC_RFMODE = 0x4 NIC_SET_RECV_LARGE = 0x5 FHSS_SET_CHANNELS = 0x10 FHSS_NEXT_CHANNEL = 0x11 FHSS_CHANGE_CHANNEL = 0x12 FHSS_SET_MAC_THRESHOLD = 0x13 FHSS_GET_MAC_THRESHOLD = 0x14 FHSS_SET_MAC_DATA = 0x15 FHSS_GET_MAC_DATA = 0x16 FHSS_XMIT = 0x17 FHSS_SET_STATE = 0x20 FHSS_GET_STATE = 0x21 FHSS_START_SYNC = 0x22 FHSS_START_HOPPING = 0x23 FHSS_STOP_HOPPING = 0x24 FHSS_STATE_NONHOPPING = 0 FHSS_STATE_DISCOVERY = 1 FHSS_STATE_SYNCHING = 2 FHSS_LAST_NONHOPPING_STATE = FHSS_STATE_SYNCHING FHSS_STATE_SYNCHED = 3 FHSS_STATE_SYNC_MASTER = 4 FHSS_STATE_SYNCINGMASTER = 5 FHSS_LAST_STATE = 5 # used for testing FHSS_STATES = {} for key,val in globals().items(): if key.startswith("FHSS_STATE_"): FHSS_STATES[key] = val FHSS_STATES[val] = key T2SETTINGS = {} T2SETTINGS_24MHz = { 100: (4, 147, 3), 150: (5, 110, 3), 200: (5, 146, 3), 250: (5, 183, 3), } T2SETTINGS_26MHz = { 100: (4, 158, 3), 150: (5, 119, 3), 200: (5, 158, 3), 250: (5, 198, 3), } TIP = (64,128,256,1024) def calculateT2(ms, mhz=24): TICKSPD = [(mhz*1000000/pow(2,x)) for x in range(8)] ms = 1.0*ms/1000 candidates = [] for tickidx in xrange(8): for tipidx in range(4): for PR in xrange(256): T = 1.0 * PR * TIP[tipidx] / TICKSPD[tickidx] if abs(T-ms) < .010: candidates.append((T, tickidx, tipidx, PR)) diff = 1024 best = None for c in candidates: if abs(c[0] - ms) < diff: best = c diff = abs(c[0] - ms) return best #return ms, candidates, best def invertBits(data): output = [] ldata = len(data) off = 0 if ldata&1: output.append( chr( ord( data[0] ) ^ 0xff) ) off = 1 if ldata&2: output.append( struct.pack( "<H", struct.unpack( "<H", data[off:off+2] )[0] ^ 0xffff) ) off += 2 #method 1 #for idx in xrange( off, ldata, 4): # output.append( struct.pack( "<I", struct.unpack( "<I", data[idx:idx+4] )[0] & 0xffff) ) #method2 count = ldata / 4 #print ldata, count numlist = struct.unpack( "<%dI" % count, data[off:] ) modlist = [ struct.pack("<L", (x^0xffffffff) ) for x in numlist ] output.extend(modlist) return ''.join(output) class FHSSNIC(USBDongle): def __init__(self, idx=0, debug=False, copyDongle=None): USBDongle.__init__(self, idx, debug, copyDongle) def setRfMode(self, rfmode, parms=''): r = self.send(APP_NIC, NIC_RFMODE, "%c"%rfmode + parms) # set repeat & offset to optionally repeat tx of a section of the data block. repeat of 65535 means 'forever' def RFxmit(self, data, repeat=0, offset=0): # calculate wait time waitlen = len(data) waitlen += repeat * (len(data) - offset) wait = USB_TX_WAIT * ((waitlen / RF_MAX_TX_BLOCK) + 1) self.send(APP_NIC, NIC_XMIT, "%s" % struct.pack("<HHH",len(data),repeat,offset)+data, wait=wait) # set blocksize to larger than 255 to receive large blocks or 0 to revert to normal def RFrecv(self, timeout=USB_RX_WAIT, blocksize=None): if not blocksize == None: self.send(APP_NIC, NIC_SET_RECV_LARGE, "%s" % struct.pack("<H",blocksize)) return self.recv(APP_NIC, NIC_RECV, timeout) def RFlisten(self): ''' just sit and dump packets as they come in kinda like discover() but without changing any of the communications settings ''' while not keystop(): try: y, t = self.RFrecv() print "(%5.3f) Received: %s" % (t, y.encode('hex')) except ChipconUsbTimeoutException: pass except KeyboardInterrupt: print "Please press <enter> to stop" sys.stdin.read(1) def RFcapture(self): ''' dump packets as they come in, but return a list of packets when you exit capture mode. kinda like discover() but without changing any of the communications settings ''' capture = [] while not keystop(): try: y, t = self.RFrecv() print "(%5.3f) Received: %s" % (t, y.encode('hex')) capture.append(y) except ChipconUsbTimeoutException: pass except KeyboardInterrupt: print "Please press <enter> to stop" sys.stdin.read(1) return ''.join(capture) def FHSSxmit(self, data): self.send(APP_NIC, FHSS_XMIT, "%c%s" % (len(data)+1, data)) def changeChannel(self, chan): return self.send(APP_NIC, FHSS_CHANGE_CHANNEL, "%c" % (chan)) def setChannels(self, channels=[]): chans = ''.join(["%c" % chan for chan in channels]) length = struct.pack("<H", len(chans)) return self.send(APP_NIC, FHSS_SET_CHANNELS, length + chans) def nextChannel(self): return self.send(APP_NIC, FHSS_NEXT_CHANNEL, '' ) def startHopping(self): return self.send(APP_NIC, FHSS_START_HOPPING, '') def stopHopping(self): return self.send(APP_NIC, FHSS_STOP_HOPPING, '') def setMACperiod(self, ms, mhz=24): val = calculateT2(ms, mhz) T, tickidx, tipidx, PR = val print "Setting MAC period to %f secs (%x %x %x)" % (val) t2ctl = (ord(self.peek(X_T2CTL)) & 0xfc) | (tipidx) clkcon = (ord(self.peek(X_CLKCON)) & 0xc7) | (tickidx<<3) self.poke(X_T2PR, chr(PR)) self.poke(X_T2CTL, chr(t2ctl)) self.poke(X_CLKCON, chr(clkcon)) def setMACdata(self, data): datastr = ''.join([chr(d) for x in data]) return self.send(APP_NIC, FHSS_SET_MAC_DATA, datastr) def getMACdata(self): datastr, timestamp = self.send(APP_NIC, FHSS_GET_MAC_DATA, '') print (repr(datastr)) data = struct.unpack("<BIHHHHHHBBH", datastr) return data def reprMACdata(self): data = self.getMACdata() return """\ u8 mac_state %x u32 MAC_threshold %x u16 NumChannels %x u16 NumChannelHops %x u16 curChanIdx %x u16 tLastStateChange %x u16 tLastHop %x u16 desperatelySeeking %x u8 txMsgIdx %x u8 txMsgIdxDone %x u16 synched_chans %x """ % data """ u8 mac_state; // MAC parameters (FIXME: make this all cc1111fhssmac.c/h?) u32 g_MAC_threshold; // when the T2 clock as overflowed this many times, change channel u16 g_NumChannels; // in case of multiple paths through the available channels u16 g_NumChannelHops; // total number of channels in pattern (>= g_MaxChannels) u16 g_curChanIdx; // indicates current channel index of the hopping pattern u16 g_tLastStateChange; u16 g_tLastHop; u16 g_desperatelySeeking; u8 g_txMsgIdx; """ def getMACthreshold(self): return self.send(APP_NIC, FHSS_SET_MAC_THRESHOLD, struct.pack("<I",value)) def setMACthreshold(self, value): return self.send(APP_NIC, FHSS_SET_MAC_THRESHOLD, struct.pack("<I",value)) def setFHSSstate(self, state): return self.send(APP_NIC, FHSS_SET_STATE, struct.pack("<I",state)) def getFHSSstate(self): state = self.send(APP_NIC, FHSS_GET_STATE, '') #print repr(state) state = ord(state[0]) return FHSS_STATES[state], state def mac_SyncCell(self, CellID=0x0000): return self.send(APP_NIC, FHSS_START_SYNC, struct.pack("<H",CellID)) def setPktAddr(self, addr): return self.poke(ADDR, chr(addr)) def getPktAddr(self): return self.peek(ADDR) def discover(self, lowball=1, debug=None, length=30, IdentSyncWord=False, SyncWordMatchList=None): oldebug = self._debug if IdentSyncWord: print "Entering Discover mode and searching for possible SyncWords..." if SyncWordMatchList is not None: print " seeking one of: %s" % repr([hex(x) for x in SyncWordMatchList]) else: print "Entering Discover mode..." self.lowball(level=lowball, length=length) if debug is not None: self._debug = debug while not keystop(): try: y, t = self.RFrecv() print "(%5.3f) Received: %s" % (t, y.encode('hex')) if IdentSyncWord: if lowball == 1: y = '\xaa\xaa' + y poss = bits.findDword(y) if len(poss): print " possible Sync Dwords: %s" % repr([hex(x) for x in poss]) if SyncWordMatchList is not None: for x in poss: if x in SyncWordMatchList: print "MATCH WITH KNOWN SYNC WORD:" + hex(x) except ChipconUsbTimeoutException: pass except KeyboardInterrupt: print "Please press <enter> to stop" sys.stdin.read(1) self._debug = oldebug self.lowballRestore() print "Exiting Discover mode..." def unittest(dongle): import cc1111client cc1111client.unittest(dongle) print "\nTesting FHSS State set/get" fhssstate = dongle.getFHSSstate() print repr(fhssstate) for stateidx in range(FHSS_LAST_STATE+1): print repr(dongle.setFHSSstate(stateidx)) print repr(dongle.getFHSSstate()) print repr(dongle.setFHSSstate(fhssstate[1] )) print repr(dongle.getFHSSstate()) if __name__ == "__main__": idx = 0 if len(sys.argv) > 1: idx = int(sys.argv.pop()) d = FHSSNIC(idx=idx)
Python
import vstruct from vstruct.primitives import * class RadioConfig(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.sync1 = v_uint8() #df00 self.sync0 = v_uint8() #df01 self.pktlen = v_uint8() #df02 self.pktctrl1 = v_uint8() #df03 self.pktctrl0 = v_uint8() #df04 self.addr = v_uint8() #df05 self.channr = v_uint8() #df06 self.fsctrl1 = v_uint8() #df07 self.fsctrl0 = v_uint8() #df08 self.freq2 = v_uint8() #df09 self.freq1 = v_uint8() #df0a self.freq0 = v_uint8() #df0b self.mdmcfg4 = v_uint8() #df0c self.mdmcfg3 = v_uint8() #df0d self.mdmcfg2 = v_uint8() #df0e self.mdmcfg1 = v_uint8() #df0f self.mdmcfg0 = v_uint8() #df10 self.deviatn = v_uint8() #df11 self.mcsm2 = v_uint8() #df12 self.mcsm1 = v_uint8() #df13 self.mcsm0 = v_uint8() #df14 self.foccfg = v_uint8() #df15 self.bscfg = v_uint8() #df16 self.agcctrl2 = v_uint8() #df17 self.agcctrl1 = v_uint8() #df18 self.agcctrl0 = v_uint8() #df19 self.frend1 = v_uint8() #df1a self.frend0 = v_uint8() #df1b self.fscal3 = v_uint8() #df1c self.fscal2 = v_uint8() #df1d self.fscal1 = v_uint8() #df1e self.fscal0 = v_uint8() #df1f self.z0 = v_uint8() #df20,21,22 self.z1 = v_uint8() #df20,21,22 self.z2 = v_uint8() #df20,21,22 self.test2 = v_uint8() #df23 self.test1 = v_uint8() #df24 self.test0 = v_uint8() #df25 self.z3 = v_uint8() #df26 self.pa_table7 = v_uint8() #df27 self.pa_table6 = v_uint8() #df28 self.pa_table5 = v_uint8() #df29 self.pa_table4 = v_uint8() #df2a self.pa_table3 = v_uint8() #df2b self.pa_table2 = v_uint8() #df2c self.pa_table1 = v_uint8() #df2d self.pa_table0 = v_uint8() #df2e self.iocfg2 = v_uint8() #df2f self.iocfg1 = v_uint8() #df30 self.iocfg0 = v_uint8() #df31 self.z4 = v_uint8() #df32,33,34,35 self.z5 = v_uint8() #df32,33,34,35 self.z6 = v_uint8() #df32,33,34,35 self.z7 = v_uint8() #df32,33,34,35 self.partnum = v_uint8() #df36 self.chipid = v_uint8() #df37 self.freqest = v_uint8() #df38 self.lqi = v_uint8() #df39 self.rssi = v_uint8() #df3a self.marcstate = v_uint8() #df3b self.pkstatus = v_uint8() #df3c self.vco_vc_dac = v_uint8() #df3d AC = 64 ACC = 0xE0 ACC_0 = 1 ACC_1 = 2 ACC_2 = 4 ACC_3 = 8 ACC_4 = 16 ACC_5 = 32 ACC_6 = 64 ACC_7 = 128 ACTIVE = 1 ADCCFG = 0xF2 ADCCFG_0 = 0x01 ADCCFG_1 = 0x02 ADCCFG_2 = 0x04 ADCCFG_3 = 0x08 ADCCFG_4 = 0x10 ADCCFG_5 = 0x20 ADCCFG_6 = 0x40 ADCCFG_7 = 0x80 ADCCON1 = 0xB4 ADCCON1_EOC = 0x80 ADCCON1_RCTRL = 0x0C ADCCON1_RCTRL0 = 0x04 ADCCON1_RCTRL1 = 0x08 ADCCON1_RCTRL_COMPL = (0x00 << 2) ADCCON1_RCTRL_LFSR13 = (0x01 << 2) ADCCON1_ST = 0x40 ADCCON1_STSEL = 0x30 ADCCON1_STSEL0 = 0x10 ADCCON1_STSEL1 = 0x20 ADCCON2 = 0xB5 ADCCON2_ECH = 0x0F ADCCON2_ECH0 = 0x01 ADCCON2_ECH1 = 0x02 ADCCON2_ECH2 = 0x04 ADCCON2_ECH3 = 0x08 ADCCON2_SCH = 0x0F ADCCON2_SCH0 = 0x01 ADCCON2_SCH1 = 0x02 ADCCON2_SCH2 = 0x04 ADCCON2_SCH3 = 0x08 ADCCON2_SCH_AIN0 = (0x00) ADCCON2_SCH_AIN0_1 = (0x08) ADCCON2_SCH_AIN1 = (0x01) ADCCON2_SCH_AIN2 = (0x02) ADCCON2_SCH_AIN2_3 = (0x09) ADCCON2_SCH_AIN3 = (0x03) ADCCON2_SCH_AIN4 = (0x04) ADCCON2_SCH_AIN4_5 = (0x0A) ADCCON2_SCH_AIN5 = (0x05) ADCCON2_SCH_AIN6 = (0x06) ADCCON2_SCH_AIN6_7 = (0x0B) ADCCON2_SCH_AIN7 = (0x07) ADCCON2_SCH_GND = (0x0C) ADCCON2_SCH_POSVOL = (0x0D) ADCCON2_SCH_TEMPR = (0x0E) ADCCON2_SCH_VDD_3 = (0x0F) ADCCON2_SDIV = 0x30 ADCCON2_SDIV0 = 0x10 ADCCON2_SDIV1 = 0x20 ADCCON2_SDIV_128 = (0x01 << 4) ADCCON2_SDIV_256 = (0x02 << 4) ADCCON2_SDIV_512 = (0x03 << 4) ADCCON2_SDIV_64 = (0x00 << 4) ADCCON2_SREF = 0xC0 ADCCON2_SREF0 = 0x40 ADCCON2_SREF1 = 0x80 ADCCON2_SREF_1_25V = (0x00 << 6) ADCCON2_SREF_AVDD = (0x02 << 6) ADCCON2_SREF_P0_6_P0_7 = (0x03 << 6) ADCCON2_SREF_P0_7 = (0x01 << 6) ADCCON3 = 0xB6 ADCCON3_ECH_AIN0 = (0x00) ADCCON3_ECH_AIN0_1 = (0x08) ADCCON3_ECH_AIN1 = (0x01) ADCCON3_ECH_AIN2 = (0x02) ADCCON3_ECH_AIN2_3 = (0x09) ADCCON3_ECH_AIN3 = (0x03) ADCCON3_ECH_AIN4 = (0x04) ADCCON3_ECH_AIN4_5 = (0x0A) ADCCON3_ECH_AIN5 = (0x05) ADCCON3_ECH_AIN6 = (0x06) ADCCON3_ECH_AIN6_7 = (0x0B) ADCCON3_ECH_AIN7 = (0x07) ADCCON3_ECH_GND = (0x0C) ADCCON3_ECH_POSVOL = (0x0D) ADCCON3_ECH_TEMPR = (0x0E) ADCCON3_ECH_VDD_3 = (0x0F) ADCCON3_EDIV = 0x30 ADCCON3_EDIV0 = 0x10 ADCCON3_EDIV1 = 0x20 ADCCON3_EDIV_128 = (0x01 << 4) ADCCON3_EDIV_256 = (0x02 << 4) ADCCON3_EDIV_512 = (0x03 << 4) ADCCON3_EDIV_64 = (0x00 << 4) ADCCON3_EREF = 0xC0 ADCCON3_EREF0 = 0x40 ADCCON3_EREF1 = 0x80 ADCCON3_EREF_1_25V = (0x00 << 6) ADCCON3_EREF_AVDD = (0x02 << 6) ADCCON3_EREF_P0_6_P0_7 = (0x03 << 6) ADCCON3_EREF_P0_7 = (0x01 << 6) ADCH = 0xBB ADCIE = 2 ADCIF = 32 ADCL = 0xBA ADC_VECTOR = 1 # ADC End of Conversion ADDR = 0xDF05 ADR_CHK_0_255_BRDCST = (0x03) ADR_CHK_0_BRDCST = (0x02) ADR_CHK_NONE = (0x00) ADR_CHK_NO_BRDCST = (0x01) AGCCTRL0 = 0xDF19 AGCCTRL0_AGC_FREEZE = 0x0C AGCCTRL0_FILTER_LENGTH = 0x03 AGCCTRL0_HYST_LEVEL = 0xC0 AGCCTRL0_WAIT_TIME = 0x30 AGCCTRL1 = 0xDF18 AGCCTRL1_AGC_LNA_PRIORITY = 0x40 AGCCTRL1_CARRIER_SENSE_ABS_THR = 0x0F AGCCTRL1_CARRIER_SENSE_REL_THR = 0x30 AGCCTRL2 = 0xDF17 AGCCTRL2_MAGN_TARGET = 0x07 AGCCTRL2_MAX_DVGA_GAIN = 0xC0 AGCCTRL2_MAX_LNA_GAIN = 0x38 B = 0xF0 BSCFG = 0xDF16 BSCFG_BS_LIMIT = 0x03 BSCFG_BS_LIMIT0 = 0x01 BSCFG_BS_LIMIT1 = 0x02 BSCFG_BS_LIMIT_0 = (0x00) BSCFG_BS_LIMIT_12 = (0x03) BSCFG_BS_LIMIT_3 = (0x01) BSCFG_BS_LIMIT_6 = (0x02) BSCFG_BS_POST_KI = 0x08 BSCFG_BS_POST_KP = 0x04 BSCFG_BS_PRE_KI = 0xC0 BSCFG_BS_PRE_KI0 = 0x40 BSCFG_BS_PRE_KI1 = 0x80 BSCFG_BS_PRE_KI_1K = (0x00 << 6) BSCFG_BS_PRE_KI_2K = (0x01 << 6) BSCFG_BS_PRE_KI_3K = (0x02 << 6) BSCFG_BS_PRE_KI_4K = (0x03 << 6) BSCFG_BS_PRE_KP = 0x30 BSCFG_BS_PRE_KP0 = 0x10 BSCFG_BS_PRE_KP1 = 0x20 BSCFG_BS_PRE_KP_1K = (0x00 << 4) BSCFG_BS_PRE_KP_2K = (0x01 << 4) BSCFG_BS_PRE_KP_3K = (0x02 << 4) BSCFG_BS_PRE_KP_4K = (0x03 << 4) B_0 = 1 B_1 = 2 B_2 = 4 B_3 = 8 B_4 = 16 B_5 = 32 B_6 = 64 B_7 = 128 CHANNR = 0xDF06 CLKCON = 0xC6 CLKCON_CLKSPD = 0x07 # bit mask, for the clock speed CLKCON_CLKSPD0 = 0x01 # bit mask, for the clock speed CLKCON_CLKSPD1 = 0x02 # bit mask, for the clock speed CLKCON_CLKSPD2 = 0x04 # bit mask, for the clock speed CLKCON_OSC = 0x40 # bit mask, for the system clock oscillator CLKCON_OSC32 = 0x80 # bit mask, for the slow 32k clock oscillator CLKCON_TICKSPD = 0x38 # bit mask, for timer ticks output setting CLKCON_TICKSPD0 = 0x08 # bit mask, for timer ticks output setting CLKCON_TICKSPD1 = 0x10 # bit mask, for timer ticks output setting CLKCON_TICKSPD2 = 0x20 # bit mask, for timer ticks output setting CLKSPD_DIV_1 = (0x00) CLKSPD_DIV_128 = (0x07) CLKSPD_DIV_16 = (0x04) CLKSPD_DIV_2 = (0x01) CLKSPD_DIV_32 = (0x05) CLKSPD_DIV_4 = (0x02) CLKSPD_DIV_64 = (0x06) CLKSPD_DIV_8 = (0x03) CY = 128 DEVIATN = 0xDF11 DEVIATN_DEVIATION_E = 0x70 DEVIATN_DEVIATION_E0 = 0x10 DEVIATN_DEVIATION_E1 = 0x20 DEVIATN_DEVIATION_E2 = 0x40 DEVIATN_DEVIATION_M = 0x07 DEVIATN_DEVIATION_M0 = 0x01 DEVIATN_DEVIATION_M1 = 0x02 DEVIATN_DEVIATION_M2 = 0x04 DMA0CFGH = 0xD5 DMA0CFGL = 0xD4 DMA1CFGH = 0xD3 DMA1CFGL = 0xD2 DMAARM = 0xD6 DMAARM0 = 0x01 DMAARM1 = 0x02 DMAARM2 = 0x04 DMAARM3 = 0x08 DMAARM4 = 0x10 DMAARM_ABORT = 0x80 DMAIE = 1 DMAIF = 1 DMAIRQ = 0xD1 DMAIRQ_DMAIF0 = 0x01 DMAIRQ_DMAIF1 = 0x02 DMAIRQ_DMAIF2 = 0x04 DMAIRQ_DMAIF3 = 0x08 DMAIRQ_DMAIF4 = 0x10 DMAREQ = 0xD7 DMAREQ0 = 0x01 DMAREQ1 = 0x02 DMAREQ2 = 0x04 DMAREQ3 = 0x08 DMAREQ4 = 0x10 DMA_VECTOR = 8 # DMA Transfer Complete DPH0 = 0x83 DPH1 = 0x85 DPL0 = 0x82 DPL1 = 0x84 DPS = 0x92 DPS_VDPS = 0x01 DSM_IP_OFF_OS_OFF = (0x03) # Interpolator & output shaping disabled DSM_IP_OFF_OS_ON = (0x02) # Interpolator disabled & output shaping enabled DSM_IP_ON_OS_OFF = (0x01) # Interpolator enabled & output shaping disabled DSM_IP_ON_OS_ON = (0x00) # Interpolator & output shaping enabled EA = 128 ENCCS = 0xB3 ENCCS_CMD = 0x06 ENCCS_CMD0 = 0x02 ENCCS_CMD1 = 0x04 ENCCS_CMD_DEC = (0x01 << 1) ENCCS_CMD_ENC = (0x00 << 1) ENCCS_CMD_LDIV = (0x03 << 1) ENCCS_CMD_LDKEY = (0x02 << 1) ENCCS_MODE = 0x70 ENCCS_MODE0 = 0x10 ENCCS_MODE1 = 0x20 ENCCS_MODE2 = 0x40 ENCCS_MODE_CBC = (0x00 << 4) ENCCS_MODE_CBCMAC = (0x05 << 4) ENCCS_MODE_CFB = (0x01 << 4) ENCCS_MODE_CTR = (0x03 << 4) ENCCS_MODE_ECB = (0x04 << 4) ENCCS_MODE_OFB = (0x02 << 4) ENCCS_RDY = 0x08 ENCCS_ST = 0x01 ENCDI = 0xB1 ENCDO = 0xB2 ENCIE = 16 ENCIF_0 = 1 ENCIF_1 = 2 ENC_VECTOR = 4 # AES Encryption/Decryption Complete EP_STATE_IDLE = 0 EP_STATE_RX = 2 EP_STATE_STALL = 3 EP_STATE_TX = 1 ERR = 8 F0 = 32 F1 = 2 FADDRH = 0xAD FADDRL = 0xAC FCTL = 0xAE FCTL_BUSY = 0x80 FCTL_CONTRD = 0x10 FCTL_ERASE = 0x01 FCTL_SWBSY = 0x40 FCTL_WRITE = 0x02 FE = 16 FOCCFG = 0xDF15 FOCCFG_FOC_BS_CS_GATE = 0x20 FOCCFG_FOC_LIMIT = 0x03 FOCCFG_FOC_LIMIT0 = 0x01 FOCCFG_FOC_LIMIT1 = 0x02 FOCCFG_FOC_POST_K = 0x04 FOCCFG_FOC_PRE_K = 0x18 FOCCFG_FOC_PRE_K0 = 0x08 FOCCFG_FOC_PRE_K1 = 0x10 FOC_LIMIT_0 = (0x00) FOC_LIMIT_DIV2 = (0x03) FOC_LIMIT_DIV4 = (0x02) FOC_LIMIT_DIV8 = (0x01) FOC_PRE_K_1K = (0x00 << 3) FOC_PRE_K_2K = (0x02 << 3) FOC_PRE_K_3K = (0x03 << 3) FOC_PRE_K_4K = (0x04 << 3) FREND0 = 0xDF1B FREND0_LODIV_BUF_CURRENT_TX = 0x30 FREND0_PA_POWER = 0x07 FREND1 = 0xDF1A FREND1_LNA2MIX_CURRENT = 0x30 FREND1_LNA_CURRENT = 0xC0 FREND1_LODIV_BUF_CURRENT_RX = 0x0C FREND1_MIX_CURRENT = 0x03 FREQ0 = 0xDF0B FREQ1 = 0xDF0A FREQ2 = 0xDF09 FREQEST = 0xDF38 FSCAL0 = 0xDF1F FSCAL1 = 0xDF1E FSCAL2 = 0xDF1D FSCAL2_FSCAL2 = 0x1F FSCAL2_VCO_CORE_H_EN = 0x20 FSCAL3 = 0xDF1C FSCAL3_CHP_CURR_CAL_EN = 0x30 FSCAL3_FSCAL3 = 0xC0 FSCTRL0 = 0xDF08 FSCTRL1 = 0xDF07 FS_AUTOCAL_4TH_TO_IDLE = (0x03 << 4) FS_AUTOCAL_FROM_IDLE = (0x01 << 4) FS_AUTOCAL_NEVER = (0x00 << 4) FS_AUTOCAL_TO_IDLE = (0x02 << 4) FWDATA = 0xAF FWT = 0xAB I2SCFG0 = 0xDF40 I2SCFG0_ENAB = 0x01 I2SCFG0_MASTER = 0x02 I2SCFG0_RXIEN = 0x40 I2SCFG0_RXMONO = 0x04 I2SCFG0_TXIEN = 0x80 I2SCFG0_TXMONO = 0x08 I2SCFG0_ULAWC = 0x10 I2SCFG0_ULAWE = 0x20 I2SCFG1 = 0xDF41 I2SCFG1_IOLOC = 0x01 I2SCFG1_TRIGNUM = 0x06 I2SCFG1_TRIGNUM0 = 0x02 I2SCFG1_TRIGNUM1 = 0x04 I2SCFG1_TRIGNUM_IOC_1 = (0x02 << 1) I2SCFG1_TRIGNUM_NO_TRIG = (0x00 << 1) I2SCFG1_TRIGNUM_T1_CH0 = (0x03 << 1) I2SCFG1_TRIGNUM_USB_SOF = (0x01 << 1) I2SCFG1_WORDS = 0xF8 I2SCFG1_WORDS0 = 0x08 I2SCFG1_WORDS1 = 0x10 I2SCFG1_WORDS2 = 0x20 I2SCFG1_WORDS3 = 0x40 I2SCFG1_WORDS4 = 0x80 I2SCLKF0 = 0xDF46 I2SCLKF1 = 0xDF47 I2SCLKF2 = 0xDF48 I2SDATH = 0xDF43 I2SDATL = 0xDF42 I2SSTAT = 0xDF45 I2SSTAT_RXIRQ = 0x04 I2SSTAT_RXLR = 0x10 I2SSTAT_RXOVF = 0x40 I2SSTAT_TXIRQ = 0x08 I2SSTAT_TXLR = 0x20 I2SSTAT_TXUNF = 0x80 I2SSTAT_WCNT = 0x03 I2SSTAT_WCNT0 = 0x01 I2SSTAT_WCNT1 = 0x02 I2SSTAT_WCNT_10BIT = (0x02) I2SSTAT_WCNT_9BIT = (0x01) I2SSTAT_WCNT_9_10BIT = (0x02) I2SWCNT = 0xDF44 IEN0 = 0xA8 IEN1 = 0xB8 IEN2 = 0x9A IEN2_I2STXIE = 0x08 IEN2_P1IE = 0x10 IEN2_P2IE = 0x02 IEN2_RFIE = 0x01 IEN2_USBIE = 0x02 IEN2_UTX0IE = 0x04 IEN2_UTX1IE = 0x08 IEN2_WDTIE = 0x20 IOCFG0 = 0xDF31 IOCFG0_GDO0_CFG = 0x3F IOCFG0_GDO0_INV = 0x40 IOCFG1 = 0xDF30 IOCFG1_GDO1_CFG = 0x3F IOCFG1_GDO1_INV = 0x40 IOCFG1_GDO_DS = 0x80 IOCFG2 = 0xDF2F IOCFG2_GDO2_CFG = 0x3F IOCFG2_GDO2_INV = 0x40 IP0 = 0xA9 IP0_IPG0 = 0x01 IP0_IPG1 = 0x02 IP0_IPG2 = 0x04 IP0_IPG3 = 0x08 IP0_IPG4 = 0x10 IP0_IPG5 = 0x20 IP1 = 0xB9 IP1_IPG0 = 0x01 IP1_IPG1 = 0x02 IP1_IPG2 = 0x04 IP1_IPG3 = 0x08 IP1_IPG4 = 0x10 IP1_IPG5 = 0x20 IRCON = 0xC0 IRCON2 = 0xE8 IT0 = 1 IT1 = 4 LQI = 0xDF39 MARCSTATE = 0xDF3B MARCSTATE_MARC_STATE = 0x1F MARC_STATE_BWBOOST = 0x09 MARC_STATE_ENDCAL = 0x0C MARC_STATE_FSTXON = 0x12 MARC_STATE_FS_LOCK = 0x0A MARC_STATE_IDLE = 0x01 MARC_STATE_IFADCON = 0x0B MARC_STATE_MANCAL = 0x05 MARC_STATE_REGON = 0x07 MARC_STATE_REGON_MC = 0x04 MARC_STATE_RX = 0x0D MARC_STATE_RXTX_SWITCH = 0x15 MARC_STATE_RX_END = 0x0E MARC_STATE_RX_OVERFLOW = 0x11 MARC_STATE_RX_RST = 0x0F MARC_STATE_SLEEP = 0x00 MARC_STATE_STARTCAL = 0x08 MARC_STATE_TX = 0x13 MARC_STATE_TXRX_SWITCH = 0x10 MARC_STATE_TX_END = 0x14 MARC_STATE_TX_UNDERFLOW = 0x16 MARC_STATE_VCOON = 0x06 MARC_STATE_VCOON_MC = 0x03 MCSM0 = 0xDF14 MCSM0_FS_AUTOCAL = 0x30 MCSM1 = 0xDF13 MCSM1_CCA_MODE = 0x30 MCSM1_CCA_MODE0 = 0x10 MCSM1_CCA_MODE1 = 0x20 MCSM1_CCA_MODE_ALWAYS = (0x00 << 4) MCSM1_CCA_MODE_PACKET = (0x02 << 4) MCSM1_CCA_MODE_RSSI0 = (0x01 << 4) MCSM1_CCA_MODE_RSSI1 = (0x03 << 4) MCSM1_RXOFF_MODE = 0x0C MCSM1_RXOFF_MODE0 = 0x04 MCSM1_RXOFF_MODE1 = 0x08 MCSM1_RXOFF_MODE_FSTXON = (0x01 << 2) MCSM1_RXOFF_MODE_IDLE = (0x00 << 2) MCSM1_RXOFF_MODE_RX = (0x03 << 2) MCSM1_RXOFF_MODE_TX = (0x02 << 2) MCSM1_TXOFF_MODE = 0x03 MCSM1_TXOFF_MODE0 = 0x01 MCSM1_TXOFF_MODE1 = 0x02 MCSM1_TXOFF_MODE_FSTXON = (0x01 << 0) MCSM1_TXOFF_MODE_IDLE = (0x00 << 0) MCSM1_TXOFF_MODE_RX = (0x03 << 0) MCSM1_TXOFF_MODE_TX = (0x02 << 0) MCSM2 = 0xDF12 MCSM2_RX_TIME = 0x07 MCSM2_RX_TIME_QUAL = 0x08 MCSM2_RX_TIME_RSSI = 0x10 MDMCFG0 = 0xDF10 MDMCFG1 = 0xDF0F MDMCFG2 = 0xDF0E MDMCFG2_DEM_DCFILT_OFF = 0x80 MDMCFG2_MANCHESTER_EN = 0x08 MDMCFG2_MOD_FORMAT = 0x70 MDMCFG2_MOD_FORMAT0 = 0x10 MDMCFG2_MOD_FORMAT1 = 0x20 MDMCFG2_MOD_FORMAT2 = 0x40 MDMCFG2_SYNC_MODE = 0x07 MDMCFG2_SYNC_MODE0 = 0x01 MDMCFG2_SYNC_MODE1 = 0x02 MDMCFG2_SYNC_MODE2 = 0x04 MDMCFG3 = 0xDF0D MDMCFG4 = 0xDF0C MFMCFG1_CHANSPC_E = 0x03 MFMCFG1_CHANSPC_E0 = 0x01 MFMCFG1_CHANSPC_E1 = 0x02 MFMCFG1_FEC_EN = 0x80 MFMCFG1_NUM_PREAMBLE = 0x70 MFMCFG1_NUM_PREAMBLE0 = 0x10 MFMCFG1_NUM_PREAMBLE1 = 0x20 MFMCFG1_NUM_PREAMBLE2 = 0x40 MFMCFG1_NUM_PREAMBLE_12 = (0x05 << 4) MFMCFG1_NUM_PREAMBLE_16 = (0x06 << 4) MFMCFG1_NUM_PREAMBLE_2 = (0x00 << 4) MFMCFG1_NUM_PREAMBLE_24 = (0x07 << 4) MFMCFG1_NUM_PREAMBLE_3 = (0x01 << 4) MFMCFG1_NUM_PREAMBLE_4 = (0x02 << 4) MFMCFG1_NUM_PREAMBLE_6 = (0x03 << 4) MFMCFG1_NUM_PREAMBLE_8 = (0x04 << 4) MDMCTRL0H = 0xDF02 MEMCTR = 0xC7 MEMCTR_CACHD = 0x02 MEMCTR_PREFD = 0x01 MODE = 128 MOD_FORMAT_2_FSK = (0x00 << 4) MOD_FORMAT_GFSK = (0x01 << 4) MOD_FORMAT_MSK = (0x07 << 4) MPAGE = 0x93 OV = 4 OVFIM = 64 P = 1 P0 = 0x80 P0DIR = 0xFD P0IE = 32 P0IF = 32 P0IFG = 0x89 P0IFG_USB_RESUME = 0x80 #rw0 P0INP = 0x8F P0INT_VECTOR = 13 # Port 0 Inputs P0SEL = 0xF3 P0_0 = 1 P0_1 = 2 P0_2 = 4 P0_3 = 8 P0_4 = 16 P0_5 = 32 P0_6 = 64 P0_7 = 128 P1 = 0x90 P1DIR = 0xFE P1IEN = 0x8D P1IF = 8 P1IFG = 0x8A P1INP = 0xF6 P1INT_VECTOR = 15 # Port 1 Inputs P1SEL = 0xF4 P1_0 = 1 P1_1 = 2 P1_2 = 4 P1_3 = 8 P1_4 = 16 P1_5 = 32 P1_6 = 64 P1_7 = 128 P2 = 0xA0 P2DIR = 0xFF P2DIR_0PRIP0 = 0x40 P2DIR_1PRIP0 = 0x80 P2DIR_DIRP2 = 0x1F P2DIR_DIRP2_0 = (0x01) P2DIR_DIRP2_1 = (0x02) P2DIR_DIRP2_2 = (0x04) P2DIR_DIRP2_3 = (0x08) P2DIR_DIRP2_4 = (0x10) P2DIR_PRIP0 = 0xC0 P2DIR_PRIP0_0 = (0x00 << 6) P2DIR_PRIP0_1 = (0x01 << 6) P2DIR_PRIP0_2 = (0x02 << 6) P2DIR_PRIP0_3 = (0x03 << 6) P2IF = 1 P2IFG = 0x8B P2INP = 0xF7 P2INP_MDP2 = 0x1F P2INP_MDP2_0 = (0x01) P2INP_MDP2_1 = (0x02) P2INP_MDP2_2 = (0x04) P2INP_MDP2_3 = (0x08) P2INP_MDP2_4 = (0x10) P2INP_PDUP0 = 0x20 P2INP_PDUP1 = 0x40 P2INP_PDUP2 = 0x80 P2INT_VECTOR = 6 # Port 2 Inputs P2SEL = 0xF5 P2SEL_PRI0P1 = 0x08 P2SEL_PRI1P1 = 0x10 P2SEL_PRI2P1 = 0x20 P2SEL_PRI3P1 = 0x40 P2SEL_SELP2_0 = 0x01 P2SEL_SELP2_3 = 0x02 P2SEL_SELP2_4 = 0x04 P2_0 = 1 P2_1 = 2 P2_2 = 4 P2_3 = 8 P2_4 = 16 P2_5 = 32 P2_6 = 64 P2_7 = 128 PARTNUM = 0xDF36 PA_TABLE0 = 0xDF2E PA_TABLE1 = 0xDF2D PA_TABLE2 = 0xDF2C PA_TABLE3 = 0xDF2B PA_TABLE4 = 0xDF2A PA_TABLE5 = 0xDF29 PA_TABLE6 = 0xDF28 PA_TABLE7 = 0xDF27 PCON = 0x87 PCON_IDLE = 0x01 PERCFG = 0xF1 PERCFG_T1CFG = 0x40 PERCFG_T3CFG = 0x20 PERCFG_T4CFG = 0x10 PERCFG_U0CFG = 0x01 PERCFG_U1CFG = 0x02 PICTL = 0x8C PICTL_P0ICON = 0x01 PICTL_P0IENH = 0x10 PICTL_P0IENL = 0x08 PICTL_P1ICON = 0x02 PICTL_P2ICON = 0x04 PICTL_P2IEN = 0x20 PICTL_PADSC = 0x40 PKTCTRL0 = 0xDF04 PKTCTRL0_CC2400_EN = 0x08 PKTCTRL0_CRC_EN = 0x04 PKTCTRL0_LENGTH_CONFIG = 0x03 PKTCTRL0_LENGTH_CONFIG0 = 0x01 PKTCTRL0_LENGTH_CONFIG_FIX = (0x00) PKTCTRL0_LENGTH_CONFIG_VAR = (0x01) PKTCTRL0_PKT_FORMAT = 0x30 PKTCTRL0_PKT_FORMAT0 = 0x10 PKTCTRL0_PKT_FORMAT1 = 0x20 PKTCTRL0_WHITE_DATA = 0x40 PKTCTRL1 = 0xDF03 PKTCTRL1_ADR_CHK = 0x03 PKTCTRL1_ADR_CHK0 = 0x01 PKTCTRL1_ADR_CHK1 = 0x02 PKTCTRL1_APPEND_STATUS = 0x04 PKTCTRL1_PQT = 0xE0 PKTCTRL1_PQT0 = 0x20 PKTCTRL1_PQT1 = 0x40 PKTCTRL1_PQT2 = 0x80 PKTLEN = 0xDF02 PKTSTATUS = 0xDF3C PKT_FORMAT_NORM = (0x00) PKT_FORMAT_RAND = (0x02) PSW = 0xD0 RE = 64 RFD = 0xD9 RFIF = 0xE9 RFIF_IRQ_CCA = 0x02 RFIF_IRQ_CS = 0x08 RFIF_IRQ_DONE = 0x10 RFIF_IRQ_PQT = 0x04 RFIF_IRQ_RXOVF = 0x40 RFIF_IRQ_SFD = 0x01 RFIF_IRQ_TIMEOUT = 0x20 RFIF_IRQ_TXUNF = 0x80 RFIM = 0x91 RFIM_IM_CCA = 0x02 RFIM_IM_CS = 0x08 RFIM_IM_DONE = 0x10 RFIM_IM_PQT = 0x04 RFIM_IM_RXOVF = 0x40 RFIM_IM_SFD = 0x01 RFIM_IM_TIMEOUT = 0x20 RFIM_IM_TXUNF = 0x80 RFST = 0xE1 RFST_SCAL = 0x01 RFST_SFSTXON = 0x00 RFST_SIDLE = 0x04 RFST_SNOP = 0x05 RFST_SRX = 0x02 RFST_STX = 0x03 RFTXRXIE = 1 RFTXRXIF = 2 RFTXRX_VECTOR = 0 # RF TX done / RX ready RF_VECTOR = 16 # RF General Interrupts RNDH = 0xBD RNDL = 0xBC RS0 = 8 RS1 = 16 RSSI = 0xDF3A RX_BYTE = 4 S0CON = 0x98 S1CON = 0x9B S1CON_RFIF_0 = 0x01 S1CON_RFIF_1 = 0x02 SLAVE = 32 SLEEP = 0xBE SLEEP_HFRC_S = 0x20 SLEEP_MODE = 0x03 SLEEP_MODE0 = 0x01 SLEEP_MODE1 = 0x02 SLEEP_MODE_PM0 = (0x00) SLEEP_MODE_PM1 = (0x01) SLEEP_MODE_PM2 = (0x02) SLEEP_MODE_PM3 = (0x03) SLEEP_OSC_PD = 0x04 SLEEP_RST = 0x18 SLEEP_RST0 = 0x08 SLEEP_RST1 = 0x10 SLEEP_RST_EXT = (0x01 << 3) SLEEP_RST_POR_BOD = (0x00 << 3) SLEEP_RST_WDT = (0x02 << 3) SLEEP_USB_EN = 0x80 SLEEP_XOSC_S = 0x40 SP = 0x81 STIE = 32 STIF = 128 STSEL_FULL_SPEED = (0x01 << 4) STSEL_P2_0 = (0x00 << 4) STSEL_ST = (0x03 << 4) STSEL_T1C0_CMP_EVT = (0x02 << 4) ST_VECTOR = 5 # Sleep Timer Compare SYNC0 = 0xDF01 SYNC1 = 0xDF00 SYNC_MODE_15_16 = (0x01) SYNC_MODE_15_16_CS = (0x05) SYNC_MODE_16_16 = (0x02) SYNC_MODE_16_16_CS = (0x06) SYNC_MODE_30_32 = (0x03) SYNC_MODE_30_32_CS = (0x07) SYNC_MODE_NO_PRE = (0x00) SYNC_MODE_NO_PRE_CS = (0x04) # CS = carrier-sense above threshold T1C0_BOTH_EDGE = (0x03) # Capture on both edges T1C0_CLR_CMP_UP_SET_0 = (0x04 << 3) # Set output on compare T1C0_CLR_ON_CMP = (0x01 << 3) # Set output on compare-up clear on 0 T1C0_FALL_EDGE = (0x02) # Capture on falling edge T1C0_NO_CAP = (0x00) # No capture T1C0_RISE_EDGE = (0x01) # Capture on rising edge T1C0_SET_CMP_UP_CLR_0 = (0x03 << 3) # Clear output on compare T1C0_SET_ON_CMP = (0x00 << 3) # Clear output on compare-up set on 0 T1C0_TOG_ON_CMP = (0x02 << 3) # Toggle output on compare T1C1_BOTH_EDGE = (0x03) # Capture on both edges T1C1_CLR_C1_SET_C0 = (0x06 << 3) # Clear when equal to T1CC1, set when equal to T1CC0 T1C1_CLR_CMP_UP_SET_0 = (0x04 << 3) # Clear output on compare-up set on 0 T1C1_CLR_ON_CMP = (0x01 << 3) # Clear output on compare T1C1_DSM_MODE = (0x07 << 3) # DSM mode T1C1_FALL_EDGE = (0x02) # Capture on falling edge T1C1_NO_CAP = (0x00) # No capture T1C1_RISE_EDGE = (0x01) # Capture on rising edge T1C1_SET_C1_CLR_C0 = (0x05 << 3) # Set when equal to T1CC1, clear when equal to T1CC0 T1C1_SET_CMP_UP_CLR_0 = (0x03 << 3) # Set output on compare-up clear on 0 T1C1_SET_ON_CMP = (0x00 << 3) # Set output on compare T1C1_TOG_ON_CMP = (0x02 << 3) # Toggle output on compare T1C2_BOTH_EDGE = (0x03) # Capture on both edges T1C2_CLR_C2_SET_C0 = (0x06 << 3) # Clear when equal to T1CC2, set when equal to T1CC0 T1C2_CLR_CMP_UP_SET_0 = (0x04 << 3) # Clear output on compare-up set on 0 T1C2_CLR_ON_CMP = (0x01 << 3) # Clear output on compare T1C2_FALL_EDGE = (0x02) # Capture on falling edge T1C2_NO_CAP = (0x00) # No capture T1C2_RISE_EDGE = (0x01) # Capture on rising edge T1C2_SET_C2_CLR_C0 = (0x05 << 3) # Set when equal to T1CC2, clear when equal to T1CC0 T1C2_SET_CMP_UP_CLR_0 = (0x03 << 3) # Set output on compare-up clear on 0 T1C2_SET_ON_CMP = (0x00 << 3) # Set output on compare T1C2_TOG_ON_CMP = (0x02 << 3) # Toggle output on compare T1CC0H = 0xDB T1CC0L = 0xDA T1CC1H = 0xDD T1CC1L = 0xDC T1CC2H = 0xDF T1CC2L = 0xDE T1CCTL0 = 0xE5 T1CCTL0_CAP = 0x03 T1CCTL0_CAP0 = 0x01 T1CCTL0_CAP1 = 0x02 T1CCTL0_CMP = 0x38 T1CCTL0_CMP0 = 0x08 T1CCTL0_CMP1 = 0x10 T1CCTL0_CMP2 = 0x20 T1CCTL0_CPSEL = 0x80 # Timer 1 channel 0 capture select T1CCTL0_IM = 0x40 # Channel 0 Interrupt mask T1CCTL0_MODE = 0x04 # Capture or compare mode T1CCTL1 = 0xE6 T1CCTL1_CAP = 0x03 T1CCTL1_CAP0 = 0x01 T1CCTL1_CAP1 = 0x02 T1CCTL1_CMP = 0x38 T1CCTL1_CMP0 = 0x08 T1CCTL1_CMP1 = 0x10 T1CCTL1_CMP2 = 0x20 T1CCTL1_CPSEL = 0x80 # Timer 1 channel 1 capture select T1CCTL1_DSM_SPD = 0x04 T1CCTL1_IM = 0x40 # Channel 1 Interrupt mask T1CCTL1_MODE = 0x04 # Capture or compare mode T1CCTL2 = 0xE7 T1CCTL2_CAP = 0x03 T1CCTL2_CAP0 = 0x01 T1CCTL2_CAP1 = 0x02 T1CCTL2_CMP = 0x38 T1CCTL2_CMP0 = 0x08 T1CCTL2_CMP1 = 0x10 T1CCTL2_CMP2 = 0x20 T1CCTL2_CPSEL = 0x80 # Timer 1 channel 2 capture select T1CCTL2_IM = 0x40 # Channel 2 Interrupt mask T1CCTL2_MODE = 0x04 # Capture or compare mode T1CNTH = 0xE3 T1CNTL = 0xE2 T1CTL = 0xE4 T1CTL_CH0IF = 0x20 # Timer 1 channel 0 interrupt flag T1CTL_CH1IF = 0x40 # Timer 1 channel 1 interrupt flag T1CTL_CH2IF = 0x80 # Timer 1 channel 2 interrupt flag T1CTL_DIV = 0x0C T1CTL_DIV0 = 0x04 T1CTL_DIV1 = 0x08 T1CTL_DIV_1 = (0x00 << 2) # Divide tick frequency by 1 T1CTL_DIV_128 = (0x03 << 2) # Divide tick frequency by 128 T1CTL_DIV_32 = (0x02 << 2) # Divide tick frequency by 32 T1CTL_DIV_8 = (0x01 << 2) # Divide tick frequency by 8 T1CTL_MODE = 0x03 T1CTL_MODE0 = 0x01 T1CTL_MODE1 = 0x02 T1CTL_MODE_FREERUN = (0x01) # Free Running mode T1CTL_MODE_MODULO = (0x02) # Modulo T1CTL_MODE_SUSPEND = (0x00) # Operation is suspended (halt) T1CTL_MODE_UPDOWN = (0x03) # Up/down T1CTL_OVFIF = 0x10 # Timer 1 counter overflow interrupt flag T1IE = 2 T1IF = 2 T1_VECTOR = 9 # Timer 1 (16-bit) Capture/Compare/Overflow T2CT = 0x9C T2CTL = 0x9E T2CTL_INT = 0x10 # Enable Timer 2 interrupt T2CTL_TEX = 0x40 T2CTL_TIG = 0x04 # Tick generator mode T2CTL_TIP = 0x03 T2CTL_TIP0 = 0x01 T2CTL_TIP1 = 0x02 T2CTL_TIP_1024 = (0x03) T2CTL_TIP_128 = (0x01) T2CTL_TIP_256 = (0x02) T2CTL_TIP_64 = (0x00) T2IE = 4 T2IF = 4 T2PR = 0x9D T2_VECTOR = 10 # Timer 2 (MAC Timer) Overflow T3C0_CLR_CMP_SET_0 = (0x06 << 3) # Clear when equal to T3CC0, set on 0 T3C0_CLR_CMP_UP_SET_0 = (0x04 << 3) # Clear output on compare-up set on 0 T3C0_CLR_ON_CMP = (0x01 << 3) # Clear output on compare T3C0_SET_CMP_CLR_255 = (0x05 << 3) # Set when equal to T3CC0, clear on 255 T3C0_SET_CMP_UP_CLR_0 = (0x03 << 3) # Set output on compare-up clear on 0 T3C0_SET_ON_CMP = (0x00 << 3) # Set output on compare T3C0_TOG_ON_CMP = (0x02 << 3) # Toggle output on compare T3C1_CLR_CMP_SET_C0 = (0x06 << 3) # Clear when equal to T3CC1, set when equal to T3CC0 T3C1_CLR_CMP_UP_SET_0 = (0x04 << 3) # Clear output on compare-up set on 0 T3C1_CLR_ON_CMP = (0x01 << 3) # Clear output on compare T3C1_SET_CMP_CLR_C0 = (0x05 << 3) # Set when equal to T3CC1, clear when equal to T3CC0 T3C1_SET_CMP_UP_CLR_0 = (0x03 << 3) # Set output on compare-up clear on 0 T3C1_SET_ON_CMP = (0x00 << 3) # Set output on compare T3C1_TOG_ON_CMP = (0x02 << 3) # Toggle output on compare T3CC0 = 0xCD T3CC1 = 0xCF T3CCTL0 = 0xCC T3CCTL0_CMP = 0x38 T3CCTL0_CMP0 = 0x08 T3CCTL0_CMP1 = 0x10 T3CCTL0_CMP2 = 0x20 T3CCTL0_IM = 0x40 T3CCTL0_MODE = 0x04 T3CCTL1 = 0xCE T3CCTL1_CMP = 0x38 T3CCTL1_CMP0 = 0x08 T3CCTL1_CMP1 = 0x10 T3CCTL1_CMP2 = 0x20 T3CCTL1_IM = 0x40 T3CCTL1_MODE = 0x04 T3CH0IF = 2 T3CH1IF = 4 T3CNT = 0xCA T3CTL = 0xCB T3CTL_CLR = 0x04 T3CTL_DIV = 0xE0 T3CTL_DIV0 = 0x20 T3CTL_DIV1 = 0x40 T3CTL_DIV2 = 0x80 T3CTL_DIV_1 = (0x00 << 5) T3CTL_DIV_128 = (0x07 << 5) T3CTL_DIV_16 = (0x04 << 5) T3CTL_DIV_2 = (0x01 << 5) T3CTL_DIV_32 = (0x05 << 5) T3CTL_DIV_4 = (0x02 << 5) T3CTL_DIV_64 = (0x06 << 5) T3CTL_DIV_8 = (0x03 << 5) T3CTL_MODE = 0x03 T3CTL_MODE0 = 0x01 T3CTL_MODE1 = 0x02 T3CTL_MODE_DOWN = (0x01) T3CTL_MODE_FREERUN = (0x00) T3CTL_MODE_MODULO = (0x02) T3CTL_MODE_UPDOWN = (0x03) T3CTL_OVFIM = 0x08 T3CTL_START = 0x10 T3IE = 8 T3IF = 8 T3OVFIF = 1 T3_VECTOR = 11 # Timer 3 (8-bit) Capture/Compare/Overflow T4CC0 = 0xED T4CC1 = 0xEF T4CCTL0 = 0xEC T4CCTL0_CLR_CMP_SET_0 = (0x06 << 3) T4CCTL0_CLR_CMP_UP_SET_0 = (0x04 << 3) T4CCTL0_CLR_ON_CMP = (0x01 << 3) T4CCTL0_CMP = 0x38 T4CCTL0_CMP0 = 0x08 T4CCTL0_CMP1 = 0x10 T4CCTL0_CMP2 = 0x20 T4CCTL0_IM = 0x40 T4CCTL0_MODE = 0x04 T4CCTL0_SET_CMP_CLR_255 = (0x05 << 3) T4CCTL0_SET_CMP_UP_CLR_0 = (0x03 << 3) T4CCTL0_SET_ON_CMP = (0x00 << 3) T4CCTL0_TOG_ON_CMP = (0x02 << 3) T4CCTL1 = 0xEE T4CCTL1_CLR_CMP_SET_C0 = (0x06 << 3) T4CCTL1_CLR_CMP_UP_SET_0 = (0x04 << 3) T4CCTL1_CLR_ON_CMP = (0x01 << 3) T4CCTL1_CMP = 0x38 T4CCTL1_CMP0 = 0x08 T4CCTL1_CMP1 = 0x10 T4CCTL1_CMP2 = 0x20 T4CCTL1_IM = 0x40 T4CCTL1_MODE = 0x04 T4CCTL1_SET_CMP_CLR_C0 = (0x05 << 3) T4CCTL1_SET_CMP_UP_CLR_0 = (0x03 << 3) T4CCTL1_SET_ON_CMP = (0x00 << 3) T4CCTL1_TOG_ON_CMP = (0x02 << 3) T4CH0IF = 16 T4CH1IF = 32 T4CNT = 0xEA T4CTL = 0xEB T4CTL_CLR = 0x04 T4CTL_DIV = 0xE0 T4CTL_DIV0 = 0x20 T4CTL_DIV1 = 0x40 T4CTL_DIV2 = 0x80 T4CTL_DIV_1 = (0x00 << 5) T4CTL_DIV_128 = (0x07 << 5) T4CTL_DIV_16 = (0x04 << 5) T4CTL_DIV_2 = (0x01 << 5) T4CTL_DIV_32 = (0x05 << 5) T4CTL_DIV_4 = (0x02 << 5) T4CTL_DIV_64 = (0x06 << 5) T4CTL_DIV_8 = (0x03 << 5) T4CTL_MODE = 0x03 T4CTL_MODE0 = 0x01 T4CTL_MODE1 = 0x02 T4CTL_MODE_DOWN = (0x01) T4CTL_MODE_FREERUN = (0x00) T4CTL_MODE_MODULO = (0x02) T4CTL_MODE_UPDOWN = (0x03) T4CTL_OVFIM = 0x08 T4CTL_START = 0x10 T4IE = 16 T4IF = 16 T4OVFIF = 8 T4_VECTOR = 12 # Timer 4 (8-bit) Capture/Compare/Overflow TCON = 0x88 TEST0 = 0xDF25 TEST1 = 0xDF24 TEST2 = 0xDF23 TICKSPD_DIV_1 = (0x00 << 3) TICKSPD_DIV_128 = (0x07 << 3) TICKSPD_DIV_16 = (0x04 << 3) TICKSPD_DIV_2 = (0x01 << 3) TICKSPD_DIV_32 = (0x05 << 3) TICKSPD_DIV_4 = (0x02 << 3) TICKSPD_DIV_64 = (0x06 << 3) TICKSPD_DIV_8 = (0x03 << 3) TIMIF = 0xD8 TX_BYTE = 2 U0BAUD = 0xC2 U0CSR = 0x86 U0CSR_ACTIVE = 0x01 U0CSR_ERR = 0x08 U0CSR_FE = 0x10 U0CSR_MODE = 0x80 U0CSR_RE = 0x40 U0CSR_RX_BYTE = 0x04 U0CSR_SLAVE = 0x20 U0CSR_TX_BYTE = 0x02 U0DBUF = 0xC1 U0GCR = 0xC5 U0GCR_BAUD_E = 0x1F U0GCR_BAUD_E0 = 0x01 U0GCR_BAUD_E1 = 0x02 U0GCR_BAUD_E2 = 0x04 U0GCR_BAUD_E3 = 0x08 U0GCR_BAUD_E4 = 0x10 U0GCR_CPHA = 0x40 U0GCR_CPOL = 0x80 U0GCR_ORDER = 0x20 U0UCR = 0xC4 U0UCR_BIT9 = 0x10 U0UCR_D9 = 0x20 U0UCR_FLOW = 0x40 U0UCR_FLUSH = 0x80 U0UCR_PARITY = 0x08 U0UCR_SPB = 0x04 U0UCR_START = 0x01 U0UCR_STOP = 0x02 U1BAUD = 0xFA U1CSR = 0xF8 U1CSR_ACTIVE = 0x01 U1CSR_ERR = 0x08 U1CSR_FE = 0x10 U1CSR_MODE = 0x80 U1CSR_RE = 0x40 U1CSR_RX_BYTE = 0x04 U1CSR_SLAVE = 0x20 U1CSR_TX_BYTE = 0x02 U1DBUF = 0xF9 U1GCR = 0xFC U1GCR_BAUD_E = 0x1F U1GCR_BAUD_E0 = 0x01 U1GCR_BAUD_E1 = 0x02 U1GCR_BAUD_E2 = 0x04 U1GCR_BAUD_E3 = 0x08 U1GCR_BAUD_E4 = 0x10 U1GCR_CPHA = 0x40 U1GCR_CPOL = 0x80 U1GCR_ORDER = 0x20 U1UCR = 0xFB U1UCR_BIT9 = 0x10 U1UCR_D9 = 0x20 U1UCR_FLOW = 0x40 U1UCR_FLUSH = 0x80 U1UCR_PARITY = 0x08 U1UCR_SPB = 0x04 U1UCR_START = 0x01 U1UCR_STOP = 0x02 URX0IE = 4 URX0IF = 8 URX0_VECTOR = 2 # USART0 RX Complete URX1IE = 8 URX1IF = 128 URX1_VECTOR = 3 # USART1 RX Complete USBADDR = 0xDE00 USBADDR_UPDATE = 0x80 #r USBCIE = 0xDE0B USBCIE_RESUMEIE = 0x02 #rw USBCIE_RSTIE = 0x04 #rw USBCIE_SOFIE = 0x08 #rw USBCIE_SUSPENDIE = 0x01 #rw USBCIF = 0xDE06 USBCIF_RESUMEIF = 0x02 #r h0 USBCIF_RSTIF = 0x04 #r h0 USBCIF_SOFIF = 0x08 #r h0 USBCIF_SUSPENDIF = 0x01 #r h0 USBCNT0 = 0xDE16 USBCNTH = 0xDE17 USBCNTL = 0xDE16 USBCS0 = 0xDE11 USBCS0_CLR_OUTPKT_RDY = 0x40 #rw h0 USBCS0_CLR_SETUP_END = 0x80 #rw h0 USBCS0_DATA_END = 0x08 #rw h0 USBCS0_INPKT_RDY = 0x02 #rw h0 USBCS0_OUTPKT_RDY = 0x01 #r USBCS0_SEND_STALL = 0x20 #rw h0 USBCS0_SENT_STALL = 0x04 #rw h1 USBCS0_SETUP_END = 0x10 #r USBCSIH = 0xDE12 USBCSIH_AUTOSET = 0x80 #rw USBCSIH_FORCE_DATA_TOG = 0x08 #rw USBCSIH_IN_DBL_BUF = 0x01 #rw USBCSIH_ISO = 0x40 #rw USBCSIL = 0xDE11 USBCSIL_CLR_DATA_TOG = 0x40 #rw h0 USBCSIL_FLUSH_PACKET = 0x08 #rw h0 USBCSIL_INPKT_RDY = 0x01 #rw h0 USBCSIL_PKT_PRESENT = 0x02 #r USBCSIL_SEND_STALL = 0x10 #rw USBCSIL_SENT_STALL = 0x20 #rw USBCSIL_UNDERRUN = 0x04 #rw USBCSOH = 0xDE15 USBCSOH_AUTOCLEAR = 0x80 #rw USBCSOH_ISO = 0x40 #rw USBCSOH_OUT_DBL_BUF = 0x01 #rw USBCSOL = 0xDE14 USBCSOL_CLR_DATA_TOG = 0x80 #rw h0 USBCSOL_DATA_ERROR = 0x08 #r USBCSOL_FIFO_FULL = 0x02 #r USBCSOL_FLUSH_PACKET = 0x10 #rw USBCSOL_OUTPKT_RDY = 0x01 #rw USBCSOL_OVERRUN = 0x04 #rw USBCSOL_SEND_STALL = 0x20 #rw USBCSOL_SENT_STALL = 0x40 #rw USBF0 = 0xDE20 USBF1 = 0xDE22 USBF2 = 0xDE24 USBF3 = 0xDE26 USBF4 = 0xDE28 USBF5 = 0xDE2A USBFRMH = 0xDE0D USBFRML = 0xDE0C USBIF = 1 USBIIE = 0xDE07 USBIIE_EP0IE = 0x01 #rw USBIIE_INEP1IE = 0x02 #rw USBIIE_INEP2IE = 0x04 #rw USBIIE_INEP3IE = 0x08 #rw USBIIE_INEP4IE = 0x10 #rw USBIIE_INEP5IE = 0x20 #rw USBIIF = 0xDE02 USBIIF_EP0IF = 0x01 #r h0 USBIIF_INEP1IF = 0x02 #r h0 USBIIF_INEP2IF = 0x04 #r h0 USBIIF_INEP3IF = 0x08 #r h0 USBIIF_INEP4IF = 0x10 #r h0 USBIIF_INEP5IF = 0x20 #r h0 USBINDEX = 0xDE0E USBMAXI = 0xDE10 USBMAXO = 0xDE13 USBOIE = 0xDE09 USBOIE_EP1IE = 0x02 #rw USBOIE_EP2IE = 0x04 #rw USBOIE_EP3IE = 0x08 #rw USBOIE_EP4IE = 0x10 #rw USBOIE_EP5IE = 0x20 #rw USBOIF = 0xDE04 USBOIF_OUTEP1IF = 0x02 #r h0 USBOIF_OUTEP2IF = 0x04 #r h0 USBOIF_OUTEP3IF = 0x08 #r h0 USBOIF_OUTEP4IF = 0x10 #r h0 USBOIF_OUTEP5IF = 0x20 #r h0 USBPOW = 0xDE01 USBPOW_ISO_WAIT_SOF = 0x80 #rw USBPOW_RESUME = 0x04 #rw USBPOW_RST = 0x08 #r USBPOW_SUSPEND = 0x02 #r USBPOW_SUSPEND_EN = 0x01 #rw USB_BM_REQTYPE_DIRMASK = 0x80 USB_BM_REQTYPE_DIR_IN = 0x80 USB_BM_REQTYPE_DIR_OUT = 0x00 USB_BM_REQTYPE_TGTMASK = 0x1f USB_BM_REQTYPE_TGT_DEV = 0x00 USB_BM_REQTYPE_TGT_EP = 0x02 USB_BM_REQTYPE_TGT_INTF = 0x01 USB_BM_REQTYPE_TYPEMASK = 0x60 USB_BM_REQTYPE_TYPE_CLASS = 0x20 USB_BM_REQTYPE_TYPE_RESERVED = 0x60 USB_BM_REQTYPE_TYPE_STD = 0x00 USB_BM_REQTYPE_TYPE_VENDOR = 0x40 USB_CLEAR_FEATURE = 0x01 USB_DESC_CONFIG = 0x02 USB_DESC_DEVICE = 0x01 USB_DESC_ENDPOINT = 0x05 USB_DESC_INTERFACE = 0x04 USB_DESC_STRING = 0x03 USB_ENABLE_PIN = P1_0 USB_GET_CONFIGURATION = 0x08 USB_GET_DESCRIPTOR = 0x06 USB_GET_INTERFACE = 0x0a USB_GET_STATUS = 0x00 USB_SET_ADDRESS = 0x05 USB_SET_CONFIGURATION = 0x09 USB_SET_DESCRIPTOR = 0x07 USB_SET_FEATURE = 0x03 USB_SET_INTERFACE = 0x11 USB_STATE_BLINK = 0xff USB_STATE_IDLE = 0 USB_STATE_RESET = 3 USB_STATE_RESUME = 2 USB_STATE_SUSPEND = 1 USB_STATE_WAIT_ADDR = 4 USB_SYNCH_FRAME = 0x12 UTX0IF = 2 UTX0_VECTOR = 7 # USART0 TX Complete UTX1IF = 4 UTX1_VECTOR = 14 # USART1 TX Complete VCO_VC_DAC = 0xDF3D VERSION = 0xDF37 WDCTL = 0xC9 WDCTL_CLR = 0xF0 WDCTL_CLR0 = 0x10 WDCTL_CLR1 = 0x20 WDCTL_CLR2 = 0x40 WDCTL_CLR3 = 0x80 WDCTL_EN = 0x08 WDCTL_INT = 0x03 WDCTL_INT0 = 0x01 WDCTL_INT1 = 0x02 WDCTL_INT1_MSEC_250 = (0x01) WDCTL_INT2_MSEC_15 = (0x02) WDCTL_INT3_MSEC_2 = (0x03) WDCTL_INT_SEC_1 = (0x00) WDCTL_MODE = 0x04 WDTIF = 16 WDT_VECTOR = 17 # Watchdog Overflow in Timer Mode WORCTL_WOR_RES = 0x03 WORCTL_WOR_RES0 = 0x01 WORCTL_WOR_RES1 = 0x02 WORCTL_WOR_RESET = 0x04 WORCTL_WOR_RES_1 = (0x00) WORCTL_WOR_RES_1024 = (0x02) WORCTL_WOR_RES_32 = (0x01) WORCTL_WOR_RES_32768 = (0x03) WORCTRL = 0xA2 WOREVT0 = 0xA3 WOREVT1 = 0xA4 WORIRQ = 0xA1 WORIRQ_EVENT0_FLAG = 0x01 WORIRQ_EVENT0_MASK = 0x10 WORTIME0 = 0xA5 WORTIME1 = 0xA6 X_ADCCFG = 0xDFF2 X_ADCCON1 = 0xDFB4 X_ADCCON2 = 0xDFB5 X_ADCCON3 = 0xDFB6 X_ADCH = 0xDFBB X_ADCL = 0xDFBA X_CLKCON = 0xDFC6 X_DMA0CFGH = 0xDFD5 X_DMA0CFGL = 0xDFD4 X_DMA1CFGH = 0xDFD3 X_DMA1CFGL = 0xDFD2 X_DMAARM = 0xDFD6 X_DMAIRQ = 0xDFD1 X_DMAREQ = 0xDFD7 X_ENCCS = 0xDFB3 X_ENCDI = 0xDFB1 X_ENCDO = 0xDFB2 X_FADDRH = 0xDFAD X_FADDRL = 0xDFAC X_FCTL = 0xDFAE X_FWDATA = 0xDFAF X_FWT = 0xDFAB X_MEMCTR = 0xDFC7 X_MPAGE = 0xDF93 X_P0DIR = 0xDFFD X_P0IFG = 0xDF89 X_P0INP = 0xDF8F X_P0SEL = 0xDFF3 X_P1DIR = 0xDFFE X_P1IEN = 0xDF8D X_P1IFG = 0xDF8A X_P1INP = 0xDFF6 X_P1SEL = 0xDFF4 X_P2DIR = 0xDFFF X_P2IFG = 0xDF8B X_P2INP = 0xDFF7 X_P2SEL = 0xDFF5 X_PERCFG = 0xDFF1 X_PICTL = 0xDF8C X_RFD = 0xDFD9 X_RFIF = 0xDFE9 X_RFIM = 0xDF91 X_RFST = 0xDFE1 X_RNDH = 0xDFBD X_RNDL = 0xDFBC X_SLEEP = 0xDFBE X_T1CC0H = 0xDFDB X_T1CC0L = 0xDFDA X_T1CC1H = 0xDFDD X_T1CC1L = 0xDFDC X_T1CC2H = 0xDFDF X_T1CC2L = 0xDFDE X_T1CCTL0 = 0xDFE5 X_T1CCTL1 = 0xDFE6 X_T1CCTL2 = 0xDFE7 X_T1CNTH = 0xDFE3 X_T1CNTL = 0xDFE2 X_T1CTL = 0xDFE4 X_T2CT = 0xDF9C X_T2CTL = 0xDF9E X_T2PR = 0xDF9D X_T3CC0 = 0xDFCD X_T3CC1 = 0xDFCF X_T3CCTL0 = 0xDFCC X_T3CCTL1 = 0xDFCE X_T3CNT = 0xDFCA X_T3CTL = 0xDFCB X_T4CC0 = 0xDFED X_T4CC1 = 0xDFEF X_T4CCTL0 = 0xDFEC X_T4CCTL1 = 0xDFEE X_T4CNT = 0xDFEA X_T4CTL = 0xDFEB X_TIMIF = 0xDFD8 X_U0BAUD = 0xDFC2 X_U0CSR = 0xDF86 X_U0DBUF = 0xDFC1 X_U0GCR = 0xDFC5 X_U0UCR = 0xDFC4 X_U1BAUD = 0xDFFA X_U1CSR = 0xDFF8 X_U1DBUF = 0xDFF9 X_U1GCR = 0xDFFC X_U1UCR = 0xDFFB X_WDCTL = 0xDFC9 X_WORCTRL = 0xDFA2 X_WOREVT0 = 0xDFA3 X_WOREVT1 = 0xDFA4 X_WORIRQ = 0xDFA1 X_WORTIME0 = 0xDFA5 X_WORTIME1 = 0xDFA6 _NA_ACC = 0xDFE0 _NA_B = 0xDFF0 _NA_DPH0 = 0xDF83 _NA_DPH1 = 0xDF85 _NA_DPL0 = 0xDF82 _NA_DPL1 = 0xDF84 _NA_DPS = 0xDF92 _NA_IEN0 = 0xDFA8 _NA_IEN1 = 0xDFB8 _NA_IEN2 = 0xDF9A _NA_IP0 = 0xDFA9 _NA_IP1 = 0xDFB9 _NA_IRCON = 0xDFC0 _NA_IRCON2 = 0xDFE8 _NA_P0 = 0xDF80 _NA_P1 = 0xDF90 _NA_P2 = 0xDFA0 _NA_PCON = 0xDF87 _NA_PSW = 0xDFD0 _NA_S0CON = 0xDF98 _NA_S1CON = 0xDF9B _NA_SP = 0xDF81 _NA_TCON = 0xDF88 _SFR8E = 0x8E _SFR94 = 0x94 _SFR95 = 0x95 _SFR96 = 0x96 _SFR97 = 0x97 _SFR99 = 0x99 _SFR9F = 0x9F _SFRA7 = 0xA7 _SFRAA = 0xAA _SFRB0 = 0xB0 _SFRB7 = 0xB7 _SFRBF = 0xBF _SFRC3 = 0xC3 _SFRC8 = 0xC8 _XPAGE = 0x93 _XREGDF20 = 0xDF20 _XREGDF21 = 0xDF21 _XREGDF22 = 0xDF22 _XREGDF26 = 0xDF26 _XREGDF32 = 0xDF32 _XREGDF33 = 0xDF33 _XREGDF34 = 0xDF34 _XREGDF35 = 0xDF35 _X_SFR8E = 0xDF8E _X_SFR94 = 0xDF94 _X_SFR95 = 0xDF95 _X_SFR96 = 0xDF96 _X_SFR97 = 0xDF97 _X_SFR99 = 0xDF99 _X_SFR9F = 0xDF9F _X_SFRA7 = 0xDFA7 _X_SFRAA = 0xDFAA _X_SFRB0 = 0xDFB0 _X_SFRB7 = 0xDFB7 _X_SFRBF = 0xDFBF _X_SFRC3 = 0xDFC3 _X_SFRC8 = 0xDFC8 ADCCON1S = {} ADCCON2S = {} ADCCON3S = {} AGCCTRL0S = {} AGCCTRL1S = {} BSCFGS = {} CLKCONS = {} CLKSPDS = {} DEVIATNS = {} IEN0S = {} IEN1S = {} IEN2S = {} IOCFG0S = {} IOCFG1S = {} IOCFG2S = {} MARC_STATES = {} MCSM0S = {} MCSM1S = {} MCSM2S = {} MDMCFG2S = {} PKTCTRL0S = {} PKTCTRL1S = {} RFIFS = {} RFIMS = {} for key,val in globals().items(): if key.startswith("RFIF_"): RFIFS[val] = key elif key.startswith("RFIM_"): RFIMS[val] = key elif key.startswith("ADCCON1_"): ADCCON1S[val] = key elif key.startswith("ADCCON2_"): ADCCON2S[val] = key elif key.startswith("ADCCON3_"): ADCCON3S[val] = key elif key.startswith("AGCCTRL0_"): AGCCTRL0S[val] = key elif key.startswith("AGCCTRL1_"): AGCCTRL1S[val] = key elif key.startswith("BSCFG_"): BSCFGS[val] = key elif key.startswith("CLKCON_"): CLKCONS[val] = key elif key.startswith("CLKSPD_"): CLKSPDS[val] = key elif key.startswith("DEVIATN_"): DEVIATNS[val] = key elif key.startswith("IEN0_"): IEN0S[val] = key elif key.startswith("IEN1_"): IEN1S[val] = key elif key.startswith("IEN2_"): IEN2S[val] = key elif key.startswith("IOCFG0_"): IOCFG0S[val] = key elif key.startswith("IOCFG1_"): IOCFG1S[val] = key elif key.startswith("IOCFG2_"): IOCFG2S[val] = key elif key.startswith("MARC_STATE_"): MARC_STATES[val] = key elif key.startswith("MCSM0_"): MCSM0S[val] = key elif key.startswith("MCSM1_"): MCSM1S[val] = key elif key.startswith("MCSM2_"): MCSM2S[val] = key elif key.startswith("MDMCFG2_"): MDMCFG2S[val] = key elif key.startswith("PKTCTRL0_"): PKTCTRL0S[val] = key elif key.startswith("PKTCTRL1_"): PKTCTRL1S[val] = key
Python
import re class tokenizer(object): def __init__(self, tokens, filename): self.tokens = tokens self.stream = 0 parts = [] for name, part in tokens: parts.append("(?P<%s>%s)" % (name, part)) self.regexpString = "|".join(parts) self.regexp = re.compile(self.regexpString, re.MULTILINE) try: self.stream = open(filename, "r") except IOError, e: print e def cleanup(self): self.stream.close() def next(self): # yield lexemes for text in self.stream: for match in self.regexp.finditer(text): found = False for name, rexp in self.tokens: m = match.group(name) if m is not None: yield (name, m) break self.stream.close() yield ('eof','eof')
Python
import sys import tokenizer class lpparser(object): def __init__(self,filename): self.tokens = [ ("variable", "[A-Za-z]+[0-9]+"), ("number", "[0-9]+"), ("sign", "[\+\-]"), ("relational", "[<>]{0,1}="), ("eol", "\n"), ] self.lex = tokenizer.tokenizer(self.tokens,filename) # Prime the machine by reading first token self.current = self.lex.next() def accept(self,tokenType): return self.current[0] == tokenType def pgm(self): done = False while not done: self.eol() def eol(self): self.accept('eol') if __name__ == "__main__": parser = lpparser("testcube.fm") for token in parser.lex.next(): print token[0],token[1] parser = lpparser("testcube.fm") parser.pgm()
Python
#!/usr/bin/env python '''PyLibrarian database helper functions''' import ConfigParser from datetime import datetime, timedelta from sqlalchemy.sql.functions import count from sqlalchemy.sql.expression import or_ from hashlib import sha256 import model config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) checkOutTime = config.get('library', 'checkout_time') # Database utility functions def addUser(name, username=None, password=None, street=None, city=None, state=None, zip=None, phone=None, email=None): '''Adds a user to the library database''' session = model.session() try: if not username: username = ''.join([c.lower() for c in name if c.isalpha()]) user = model.User(name=name, username=username, password=sha256(password).hexdigest(), street=street, city=city, state=state, zip=zip if str(zip).isdigit() else None, phone=phone, email=email) session.add(user) session.commit() finally: session.close() def updateUser(id, name, username=None, password=None, street=None, city=None, state=None, zip=None, phone=None, email=None): '''Adds a user to the library database''' session = model.session() try: if not username: username = ''.join([c.lower() for c in name if c.isalpha()]) user = session.query(model.User).filter_by(id=id).first() if user: if password: user.password = sha256(password).hexdigest() user.name = name user.username = username user.street = street user.city = city user.state = state user.zip = zip if str(zip).isdigit() else None user.phone = phone user.email = email session.add(user) session.commit() finally: session.close() def deleteUser(id): '''Removes a user from the system''' session = model.session() try: user = session.query(model.User).filter_by(id=id).first() if user: session.delete(user) session.commit() finally: session.close() def getUsers(): '''Returns a list of users''' session = model.session() try: users = [] for user in session.query(model.User).order_by(model.User.id.asc()).all(): rec = user.__dict__ del rec['password'] users.append(rec) return users finally: session.close() def getUserByID(id): '''Gets the user with the given ID''' session = model.session() try: result = session.query(model.User).filter_by(id=id).first() return result.__dict__ if result else {} finally: session.close() def checkLogin(username, password): '''Validates a login attempt. Returns the user object on success, None upon failure''' session = model.session() try: return session.query(model.User).filter_by(username=username).filter_by(password=sha256(password).hexdigest()).first() finally: session.close() def getResourceByID(id): '''Gets the resource with the given ID''' session = model.session() try: result = session.query(model.Resource).filter_by(id=id).first() return result.__dict__ if result else None finally: session.close() def getResourcesByISBN(isbn): '''Gets all resources with the given ISBN''' session = model.session() try: results = session.query(model.Resource).filter_by(isbn=isbn).all() return [res.__dict__ for res in results] finally: session.close() def getAvailableResourceByISBN(isbn): '''Gets the first available resource with the given ISBN. This is called if the user scans an ISBN instead of a resource-specific barcode.''' session = model.session() try: qry = session.query(model.Resource).filter_by(isbn=isbn).all() results = [res.__dict__ for res in qry if isResourceCheckedIn(res.id)] return results[0] if len(results) else {} finally: session.close() def getResources(): '''Returns a list of all resources''' session = model.session() try: return [resource.__dict__ for resource in session.query(model.Resource).order_by(model.Resource.id.desc()).all()] finally: session.close() def getPopularResources(): '''Returns a list of the top 20 most borrowed resources''' session = model.session() try: results = session.query(model.Resource).join(model.Loan).\ group_by(model.Resource.isbn).group_by(model.Resource.id).group_by(model.Resource.title).group_by(model.Resource.author).group_by(model.Resource.publisher).group_by(model.Resource.resource_type_id).group_by(model.Resource.summary).order_by(count(model.Resource.isbn).desc())[:20] return [result.__dict__ for result in results] finally: session.close() def getCheckedOutResources(user_id=None, overdue=False): '''Returns a list of resources that are checked, optionally filtered by user id and overdue status''' session = model.session() try: # Define the value endOfDay to be the last possible microsecond of today for determining overdue status endOfDay = datetime.now() endOfDay = endOfDay.replace(hour=11, minute=59, second=59, microsecond=999) query = session.query(model.Resource.id, model.Resource.title, model.Resource.resource_type_id, model.Loan.due_date, model.User.name, model.User.email).join(model.Loan).\ join(model.User).\ filter(model.Loan.returned_date==None) if overdue: # Optionally only return overdue resources query = query.filter(model.Loan.due_date < endOfDay) if user_id: query = query.filter(model.Loan.user_id==user_id) return [{'id': result[0], 'title': result[1], 'resource_type_id': result[2], 'due_date': result[3], 'card_name': result[4], 'card_email': result[5], 'overdue': result[3] < endOfDay} for result in query.all()] finally: session.close() def searchResources(search): '''Returns a list of resources matching the search string''' session = model.session() try: searchNum = int(search) if search.isdigit() else None search = '%%%s%%' % search return session.query(model.Resource)\ .filter(or_(model.Resource.title.ilike(search), model.Resource.author.ilike(search), model.Resource.publisher.ilike(search), model.Resource.summary.ilike(search), model.Resource.isbn == searchNum, model.Resource.id == searchNum)) finally: session.close() def getResourceTypes(): '''Returns a list of all resource types''' session = model.session() try: return [resource.__dict__ for resource in session.query(model.ResourceType).all()] finally: session.close() def addResource(isbn, resourceType, title, author, publisher=None, summary=None): '''Adds a resource to the library database''' session = model.session() try: resource = model.Resource(isbn=isbn, resource_type_id=resourceType, title=title, author=author, publisher=publisher, summary=summary) session.add(resource) session.commit() finally: session.close() def updateResource(id, resourceType, title, author, publisher=None, summary=None): session = model.session() try: resource = session.query(model.Resource).filter_by(id=id).first() if resource: resource.title = title resource.author = author resource.publisher = publisher resource.resource_type_id = resourceType resource.summary = summary session.add(resource) session.commit() finally: session.close() def updateResourcesByISBN(isbn, resourceType, title, author, publisher=None, summary=None): session = model.session() try: resources = session.query(model.Resource).filter_by(isbn=isbn).all() for resource in resources: resource.title = title resource.author = author resource.publisher = publisher resource.resource_type_id = resourceType resource.summary = summary session.add(resource) session.commit() finally: session.close() def deleteResourceByID(id): session = model.session() try: resource = session.query(model.Resource).filter_by(id=id).first() if resource: session.delete(resource) session.commit() finally: session.close() def checkoutResource(resource_id, user_id): '''Marks a resource as checked out by a user''' if not isResourceCheckedIn(resource_id) or not resource_id or not user_id: return False # already checked out session = model.session() try: loan = model.Loan(resource_id=resource_id, user_id=user_id, due_date=datetime.now() + timedelta(weeks=3)) session.add(loan) session.commit() return True except: return False finally: session.close() def checkinResource(resource_id): '''Marks a resource as checked in''' if isResourceCheckedIn(resource_id) or not resource_id: return False # already checked in or not enough info session = model.session() try: loans = session.query(model.Loan).filter_by(resource_id=resource_id).filter_by(returned_date=None).all() for loan in loans: loan.returned_date = datetime.now() session.add(loan) session.commit() return True except: return False finally: session.close() def getISBNCheckedOutByUser(isbn, user_id): '''Returns the loan information (if any) for a given ISBN and checked out by the given user''' session = model.session() try: result = session.query(model.Loan).join(model.Resource).filter(model.Resource.isbn==isbn).filter(model.Loan.user_id==user_id).filter(model.Loan.returned_date==None).first() return result.__dict__ if result else {} finally: session.close() def isResourceCheckedIn(id): '''Returns whether a resource is checked in or not''' session = model.session() try: return session.query(model.Loan).filter_by(resource_id=id).filter_by(returned_date=None).count() == 0 finally: session.close() def reserveResource(resource_isbn, user_id): '''Reserves a resource for a user''' raise NotImplementedError('Book resource reservations have not yet been implemented') session = model.session() try: hold = model.Hold(resource_isbn=resource_isbn, user_id=user_id) session.add(hold) session.commit() finally: session.close()
Python
#!/usr/bin/env python '''A PyGame, kiosk-style client for PyLibrarian''' import sys import ConfigParser import pygame import database from time import time, sleep config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) libraryName = config.get('library', 'name') timeout = config.getint('client', 'session_timeout') pygame.init() size = width, height = config.getint('client', 'screen_width'), config.getint('client', 'screen_height') screen = pygame.display.set_mode(size, pygame.FULLSCREEN) #screen = pygame.display.set_mode(size) black = 0, 0, 0 white = 255, 255, 255 green = 0, 255, 0 red = 255, 0, 0 titleFont = pygame.font.SysFont('Arial', 36) normalFont = pygame.font.SysFont('Arial', 24) LOGGED_OUT = 0 LOGGED_IN = 1 state = LOGGED_OUT user = None def attemptLogin(id): global user user = database.getUserByID(int(id)) return LOGGED_IN if bool(user) else LOGGED_OUT def displayConfirmation(message): text = normalFont.render(message, True, green) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx textpos.y = height - 42 screen.blit(text, textpos) pygame.display.flip() sleep(1) def displayError(message): text = normalFont.render(message, True, red) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx textpos.y = height - 42 screen.blit(text, textpos) pygame.display.flip() sleep(1) pygame.event.clear() def scanResource(id): global user try: if database.isResourceCheckedIn(id): result = database.checkoutResource(id, user.get('id')) if result: displayConfirmation('Checked out %s' % database.getResourceByID(id).get('title')) else: # The book was already checked out, so check it in result = database.checkinResource(id) if result: displayConfirmation('Returned %s' % database.getResourceByID(id).get('title')) if not result: displayError('There was a problem scanning. You are probably scanning too fast.') except: import traceback print traceback.format_exc() displayError('There was a problem scanning. You are probably scanning too fast.') def runKiosk(): global state global user inputBuffer = '' lastScan = time() # Hide the mouse pygame.mouse.set_visible(False) while True: # Main loop try: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN: # A key event was received (from the scanner I hope) if event.key < 127: if event.key == pygame.K_q: # A librarian plugged in a keyboard and pressed 'q' to quit sys.exit(0) # quit elif event.key == pygame.K_l: state = LOGGED_OUT elif event.key == pygame.K_RETURN: # A newline was received (end of scanned barcode) if state == LOGGED_OUT: # Try to login if we are logged out state = attemptLogin(inputBuffer) if state == LOGGED_IN: displayConfirmation('You may begin scanning books to check out or return') elif state == LOGGED_IN: if len(inputBuffer) == 8 and inputBuffer.isdigit(): # Try to log back out if we scanned a library card state = LOGGED_OUT if int(inputBuffer) == user.get('id') else attemptLogin(inputBuffer) if state == LOGGED_IN: displayConfirmation('You may begin scanning books to check out or return') elif len(inputBuffer) == 9 and inputBuffer.isdigit(): # Try to check a book out or in if we scanned a book code scanResource(inputBuffer) else: # We scanned a book by barcode loan = database.getISBNCheckedOutByUser(inputBuffer, user.get('id')) if not loan: scanResource(database.getAvailableResourceByISBN(inputBuffer).get('id')) else: scanResource(loan.get('resource_id')) if lastScan + 1 < time() or event.key == pygame.K_RETURN: # If we have had no input for 1 second (reasonable with a barcode reader), clear the input buffer inputBuffer = '' inputBuffer += chr(event.key) lastScan = time() screen.fill(black) if state == LOGGED_OUT: text = titleFont.render('Welcome to the %s' % (libraryName), True, white) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx screen.blit(text, textpos) text = normalFont.render('Please scan your library card', True, white) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx textpos.y = 42 screen.blit(text, textpos) elif state == LOGGED_IN: text = titleFont.render("Check Out Books", True, white) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx screen.blit(text, textpos) text = normalFont.render('Please scan a book, or scan your card again to finish', True, white) textpos = text.get_rect() textpos.centerx = screen.get_rect().centerx textpos.y = 42 screen.blit(text, textpos) if time() > lastScan + timeout: state = LOGGED_OUT pygame.display.flip() sleep(1.0/100) except SystemExit: raise except: displayError('Oops, something really went wrong. Contact the librarian if problems continue') runKiosk()
Python
#!/usr/bin/env python import sys import database import ConfigParser from smtplib import SMTP try: # 2.5 compatibility from smtplib import SMTP_SSL except ImportError: pass from email.MIMEText import MIMEText from email.Header import Header from email.Utils import parseaddr, formataddr config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) libraryName = config.get('library', 'name') libraryString = ('the %s' % libraryName) if not libraryName.lower().startswith('the ') else libraryName # Read SMTP configuration try: server = config.get('backend', 'smtp_server') except ConfigParser.NoOptionError: server = None if server: try: port = int(config.get('backend', 'smtp_port')) except ConfigParser.NoOptionError: port = None try: useSSL = bool(int(config.get('backend', 'smtp_ssl'))) except ConfigParser.NoOptionError: useSSL = False try: useTLS = bool(int(config.get('backend', 'smtp_tls'))) except ConfigParser.NoOptionError: useTLS = False try: username = config.get('backend', 'smtp_username') except ConfigParser.NoOptionError: username = '' try: password = config.get('backend', 'smtp_password') except ConfigParser.NoOptionError: password = '' else: port = None useSSL = False try: serverEmail = '%s <%s>' % (libraryName, config.get('backend', 'server_email')) except ConfigParser.NoOptionError: print 'Error: You must specify a value for server_email in your configuration file!' sys.exit(1) def send_email(sender, recipient, subject, body): ''' This code was borrowed from http://mg.pov.lt/blog/unicode-emails-in-python.html Many thanks to Marius Gedminas for posting this code. Send an email. All arguments should be Unicode strings (plain ASCII works as well). Only the real name part of sender and recipient addresses may contain non-ASCII characters. The email will be properly MIME encoded and delivered though SMTP to localhost port 25. This is easy to change if you want something different. The charset of the email will be the first one out of US-ASCII, ISO-8859-1 and UTF-8 that can represent all the characters occurring in the email. ''' # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = 'ISO-8859-1' # We must choose the body charset manually for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8': try: body.encode(body_charset) except UnicodeError: pass else: break # Split real name (which is optional) and email address parts sender_name, sender_addr = parseaddr(sender) recipient_name, recipient_addr = parseaddr(recipient) # We must always pass Unicode strings to Header, otherwise it will # use RFC 2047 encoding even on plain ASCII strings. sender_name = str(Header(unicode(sender_name), header_charset)) recipient_name = str(Header(unicode(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters sender_addr = sender_addr.encode('ascii') recipient_addr = recipient_addr.encode('ascii') # Create the message ('plain' stands for Content-Type: text/plain) msg = MIMEText(body.encode(body_charset), 'plain', body_charset) msg['From'] = formataddr((sender_name, sender_addr)) msg['To'] = formataddr((recipient_name, recipient_addr)) msg['Subject'] = Header(unicode(subject), header_charset) # Send the message via SMTP to localhost:25 smtp = SMTP_SSL(server, port) if useSSL else SMTP(server, port) smtp.ehlo() if useTLS: smtp.starttls() if username: smtp.login(username, password) smtp.sendmail(sender, recipient, msg.as_string()) smtp.quit() # Fetch the list of overdue books overdue = database.getCheckedOutResources(user_id=None, overdue=True) records = {} # Sort the overdue resources by email address for record in overdue: email = record['card_email'] if email: if email not in records: records[email] = [] records[email].append(record) # Send the individual emails for email in records: overdueResources = records[email] name = overdueResources[0]['card_name'] header = u'%s %s' % ('Title'.ljust(120), 'Due Date') body = '\n'.join([u'%s %s' % (resource['title'][:120].ljust(120), resource['due_date'].date()) for resource in overdueResources]) message = u'%s,\n\nThis is an automated message from %s to let you know that you have some overdue resources.\n\n%s\n%s' % (name, libraryString, header, body) send_email(serverEmail, email, 'Overdue notice', message)
Python
# -*- coding: utf-8 -*- """ Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with url parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template engines - all in a single file and with no dependencies other than the Python Standard Library. Homepage and documentation: http://wiki.github.com/defnull/bottle Licence (MIT) ------------- Copyright (c) 2009, Marcel Hellkamp. 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 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. Example ------- from bottle import route, run, request, response, send_file, abort @route('/') def hello_world(): return 'Hello World!' @route('/hello/:name') def hello_name(name): return 'Hello %s!' % name @route('/hello', method='POST') def hello_post(): name = request.POST['name'] return 'Hello %s!' % name @route('/static/:filename#.*#') def static_file(filename): send_file(filename, root='/path/to/static/files/') run(host='localhost', port=8080) Code Comments ------------- #BC: Backward compatibility. This piece of code makes no sense but is here to maintain compatibility to previous releases. #TODO: Please help to improve this piece of code. There is something ugly or missing here. #REF: A reference to a bug report, article, api doc or howto. Follow the link to read more. """ __author__ = 'Marcel Hellkamp' __version__ = '0.6.4' __license__ = 'MIT' import types import sys import cgi import mimetypes import os import os.path import traceback import re import random import threading import time import warnings import email.utils from wsgiref.headers import Headers as HeaderWrapper from Cookie import SimpleCookie import subprocess import thread import tempfile import hmac import base64 from urllib import quote as urlquote from urlparse import urlunsplit, urljoin if sys.version_info >= (3,0,0): # See Request.POST from io import BytesIO from io import TextIOWrapper else: from StringIO import StringIO as BytesIO TextIOWrapper = None try: from urlparse import parse_qs except ImportError: # pragma: no cover from cgi import parse_qs try: import cPickle as pickle except ImportError: # pragma: no cover import pickle as pickle try: try: from json import dumps as json_dumps except ImportError: # pragma: no cover from simplejson import dumps as json_dumps except ImportError: # pragma: no cover json_dumps = None # Exceptions and Events class BottleException(Exception): """ A base class for exceptions used by bottle. """ pass class HTTPResponse(BottleException): """ Used to break execution and imediately finish the response """ def __init__(self, output='', status=200): super(BottleException, self).__init__(status, output) self.status = int(status) self.output = output class HTTPError(HTTPResponse): """ Used to generate an error page """ def __init__(self, code=500, message='Unknown Error', exception=None): super(HTTPError, self).__init__(message, code) self.exception = exception def __str__(self): return ERROR_PAGE_TEMPLATE % { 'status' : self.status, 'url' : request.path, 'error_name' : HTTP_CODES.get(self.status, 'Unknown').title(), 'error_message' : repr(self.output) } # Routing # Bottle uses routes to map URLs to handler callbacks. class RouteError(BottleException): """ This is a base class for all routing related exceptions """ class RouteSyntaxError(RouteError): """ The route parser found something not supported by this router """ class RouteBuildError(RouteError): """ The route could not been build """ class Router(object): ''' A route associates a string (e.g. URL) with an object (e.g. function) Dynamic routes use regular expressions to describe all matching strings. Some dynamic routes may extract parts of the string and provide them as data. This router matches a string against multiple routes and returns the associated object along with the extracted data. ''' syntax = re.compile(r'(?P<pre>.*?)' r'(?P<escape>\\)?' r':(?P<name>[a-zA-Z_]+)?' r'(#(?P<rex>.*?)#)?') def __init__(self): self.static = dict() self.dynamic = [] self.splits = dict() def is_dynamic(self, route): ''' Returns True if the route contains dynamic syntax ''' for text, name, rex in self.itersplit(route): if name or rex: return True return False def split(self, route): ''' Splits a route into (prefix, parameter name, pattern) triples. The prefix may be empty. The other two may be None. ''' return list(self.itersplit(route)) def itersplit(self, route): ''' Same as Router.split() but returns an iterator. ''' match = None for match in self.syntax.finditer(route): pre = match.group('pre') name = match.group('name') rex = match.group('rex') if match.group('escape'): yield match.group(0).replace('\\:',':',1), None, None continue if rex: rex = re.sub(r'\(\?P<[^>]*>', '(?:', rex) rex = re.sub(r'\((?!\?)', '(?:', rex) try: rex = re.compile(rex) except re.error, e: raise RouteSyntaxError("Syntax error in '%s' offset %d: %s" % (route, match.start('rex'), repr(e))) if rex.groups > 1: # Should not be possible. raise RouteSyntaxError("Groups in route '%s'." % (route)) yield pre, name, rex if not match: yield route, None, None elif match.end() < len(route): yield route[match.end():], None, None def parse(self, route): ''' Parses a route and returns a tuple. The first element is a RegexObject with named groups. The second is a non-grouping version of that RegexObject. ''' rexp = '' fexp = '' isdyn = False for text, name, rex in self.itersplit(route): rexp += re.escape(text) fexp += re.escape(text) if name and rex: rexp += '(?P<%s>%s)' % (name, rex.pattern) fexp += '(?:%s)' % rex.pattern elif name: rexp += '(?P<%s>[^/]+)' % name fexp += '[^/]+' elif rex: rexp += '(?:%s)' % rex.pattern fexp += '(?:%s)' % rex.pattern return re.compile('%s' % rexp), re.compile('%s' % fexp) def add(self, route, data, static=False, name=None): ''' Adds a route to the router. Syntax: `:name` matches everything up to the next slash. `:name#regexp#` matches a regular expression. `:#regexp#` creates an anonymous match. A backslash can be used to escape the `:` character. ''' if not self.is_dynamic(route) or static: self.static[route] = data return rexp, fexp = self.parse(route) rexp = re.compile('^(%s)$' % rexp.pattern) if not rexp.groupindex: rexp = None # No named groups -> Nothing to extract if fexp.groups: # Should not be possible. raise RouteSyntaxError("Route contains groups '%s'." % (route)) try: big_re, subroutes = self.dynamic[-1] big_re = '%s|(^%s$)' % (big_re.pattern, fexp.pattern) big_re = re.compile(big_re) subroutes.append((data, rexp)) self.dynamic[-1] = (big_re, subroutes) except (AssertionError, IndexError), e: # AssertionError: To many groups self.dynamic.append((re.compile('(^%s$)' % fexp.pattern), [(data, rexp)])) if name: self.splits[name] = self.split(route) def match(self, uri): ''' Matches an URL and returns a (handler, data) tuple ''' if uri in self.static: return self.static[uri], None for big_re, subroutes in self.dynamic: match = big_re.match(uri) if match: data, group_re = subroutes[match.lastindex - 1] if not group_re: return data, None group_match = group_re.match(uri) if not group_match: return None, None return data, group_match.groupdict() return None, None def build(self, route_name, **args): ''' Builds an URL out of a named route and some parameters.''' if route_name not in self.splits: raise RouteBuildError("No route found with name '%s'." % route_name) out = [] for text, key, rex in self.splits[route_name]: out.append(text) if key and key not in args: raise RouteBuildError("Missing parameter '%s' in route '%s'" % (key, route_name)) if rex and not key: raise RouteBuildError("Anonymous pattern found. Can't " "generate the route '%s'." % route_name) #TODO: Do this in add() if rex and not re.match('^%s$' % rex.pattern, args[key]): raise RouteBuildError("Parameter '%s' does not match pattern " "for route '%s': '%s'" % (key, route_name, rex.pattern)) if key: out.append(args[key]) return ''.join(out) # WSGI abstraction: Request and response management class Bottle(object): def __init__(self, catchall=True, autojson=True, path = ''): self.routes = dict() self.default_route = None self.error_handler = {} if autojson and json_dumps: self.jsondump = json_dumps else: self.jsondump = False self.catchall = catchall self.config = dict() self.serve = True self.rootpath = path def match_url(self, path, method='GET'): """ Find a callback bound to a path and a specific method. Return (callback, param) tuple or (None, None). method=HEAD falls back to GET. method=GET fall back to ALL. """ if not path.startswith(self.rootpath): return None, None path = path[len(self.rootpath):].strip().lstrip('/') method = method.upper() handler, param = self.routes.setdefault(method, Router()).match(path) if not handler and method == 'HEAD': handler, param = self.routes.setdefault('GET', Router()).match(path) if not handler: handler, param = self.routes.setdefault('ALL', Router()).match(path) if not handler: handler, param = self.default_route, None return handler, param def get_url(self, routename, **kargs): pass def route(self, url, method='GET', **kargs): """ Decorator for request handler. """ path = url.strip().lstrip('/') method = method.upper() def wrapper(handler): self.routes.setdefault(method, Router())\ .add(path, handler, **kargs) return handler return wrapper def default(self): """ Decorator for request handler. Same as add_defroute( handler ).""" def wrapper(handler): self.default_route = handler return handler return wrapper def error(self, code=500): """ Decorator for error handler. """ def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper def handle(self, url, method, catchall=True): """ Run the matching handler. Return handler output, HTTPResponse or HTTPError. If catchall is true, all exceptions thrown within a handler function are converted to HTTPError(500). """ if not self.serve: return HTTPError(503, "Server stopped") handler, args = self.match_url(request.path, request.method) if not handler: return HTTPError(404, "Not found") if not args: args = dict() try: return handler(**args) except HTTPResponse, e: return e except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception, e: if not self.catchall: raise err = "Unhandled Exception: %s\n" % (repr(e)) if DEBUG: err += '\n\nTraceback:\n' + traceback.format_exc(10) request.environ['wsgi.errors'].write(err) return HTTPError(500, err, e) def cast(self, out): """ Try to cast the input into something WSGI compatible. Correct HTTP headers and status codes when possible. Empty output on HEAD requests. Support: False, str, unicode, list(unicode), file, dict, list(dict), HTTPResponse and HTTPError """ if isinstance(out, HTTPResponse): response.status = out.status if isinstance(out, HTTPError): out = self.error_handler.get(out.status, str)(out) else: out = out.output if not out: response.header['Content-Length'] = '0' return [] if isinstance(out, types.StringType): out = [out] elif isinstance(out, unicode): out = [out.encode(response.charset)] elif isinstance(out, list) and isinstance(out[0], unicode): out = map(lambda x: x.encode(response.charset), out) elif hasattr(out, 'read'): out = request.environ.get('wsgi.file_wrapper', lambda x: iter(lambda: x.read(8192), ''))(out) elif self.jsondump and isinstance(out, dict)\ or self.jsondump and isinstance(out, list) and isinstance(out[0], dict): out = [self.jsondump(out)] response.content_type = 'application/json' if isinstance(out, list) and len(out) == 1: response.header['Content-Length'] = str(len(out[0])) if response.status in (100, 101, 204, 304) or request.method == 'HEAD': out = [] # rfc2616 section 4.3 if not hasattr(out, '__iter__'): raise TypeError('Request handler for route "%s" returned [%s] ' 'which is not iterable.' % (request.path, type(out).__name__)) return out def __call__(self, environ, start_response): """ The bottle WSGI-interface. """ try: request.bind(environ, self) response.bind(self) out = self.handle(request.path, request.method) out = self.cast(out) status = '%d %s' % (response.status, HTTP_CODES[response.status]) start_response(status, response.wsgiheaders()) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception, e: if not self.catchall: raise err = "<h1>Critial error while processing request: %s</h1>" %\ environ.get('PATH_INFO', '/') if DEBUG: err += '<h2>Error:</h2>\n<pre>%s</pre>\n'\ '<h2>Traceback:</h2>\n<pre>%s</pre>\n' %\ (repr(e), traceback.format_exc(10)) environ['wsgi.errors'].write(err) start_response('500 INTERNAL SERVER ERROR', []) return [err] class Request(threading.local): """ Represents a single request using thread-local namespace. """ def bind(self, environ, app): """ Binds the enviroment of the current request to this request handler """ self.environ = environ self._GET = None self._POST = None self._GETPOST = None self._COOKIES = None self._body = None self.path = environ.get('PATH_INFO', '/').strip() self.app = app if not self.path.startswith('/'): self.path = '/' + self.path @property def method(self): """ Get the request method (GET,POST,PUT,DELETE,...) """ return self.environ.get('REQUEST_METHOD', 'GET').upper() @property def query_string(self): """ Get content of QUERY_STRING """ return self.environ.get('QUERY_STRING', '') @property def fullpath(self): """ Get the request path including SCRIPT_NAME """ return self.environ.get('SCRIPT_NAME', '').rstrip('/') + self.path @property def url(self): """ Get the request URL (scheme://host:port/scriptname/path?query) """ scheme = self.environ.get('wsgi.url_scheme', 'http') host = self.environ.get('HTTP_HOST', None) if not host: host = self.environ.get('SERVER_NAME') port = self.environ.get('SERVER_PORT', '80') if scheme + port not in ('https443', 'http80'): host += ':' + port parts = (scheme, host, urlquote(self.fullpath), self.query_string, '') return urlunsplit(parts) @property def input_length(self): """ Get content of CONTENT_LENGTH """ try: return max(0,int(self.environ.get('CONTENT_LENGTH', '0'))) except ValueError: return 0 @property def GET(self): """ Get a dict with GET parameters. """ if self._GET is None: data = parse_qs(self.query_string, keep_blank_values=True) self._GET = {} for key, value in data.iteritems(): if len(value) == 1: self._GET[key] = value[0] else: self._GET[key] = value return self._GET @property def POST(self): """ Get a dict with parsed POST or PUT data. """ if self._POST is None: qs_backup = self.environ.get('QUERY_STRING','') self.environ['QUERY_STRING'] = '' if TextIOWrapper: fb = TextIOWrapper(self.body, encoding='ISO-8859-1') else: fb = self.body data = cgi.FieldStorage(fp=fb, environ=self.environ, keep_blank_values=True) self.environ['QUERY_STRING'] = qs_backup self._POST = {} for item in data.list: name = item.name if not item.filename: item = item.value self._POST.setdefault(name, []).append(item) for key in self._POST: if len(self._POST[key]) == 1: self._POST[key] = self._POST[key][0] return self._POST @property def params(self): """ Returns a mix of GET and POST data. POST overwrites GET """ if self._GETPOST is None: self._GETPOST = dict(self.GET) self._GETPOST.update(dict(self.POST)) return self._GETPOST @property def body(self): if not self._body: maxread = self.input_length if maxread < 1024*100: #TODO Should not be hard coded... self._body = BytesIO() else: self._body = tempfile.TemporaryFile(mode='w+b') while maxread > 0: part = self.environ['wsgi.input'].read(min(maxread, 8192)) if not part: #TODO: Wrong content_length. Error? Do nothing? break self._body.write(part) maxread -= len(part) self.environ['wsgi.input'] = self._body self._body.seek(0) return self._body @property def auth(self): #TODO: Tests and docs. Add support for digest. namedtuple? return parse_auth(self.environ.get('HTTP_AUTHORIZATION')) @property def COOKIES(self): """ Returns a dict with COOKIES. """ if self._COOKIES is None: raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE','')) self._COOKIES = {} for cookie in raw_dict.itervalues(): self._COOKIES[cookie.key] = cookie.value return self._COOKIES def get_cookie(self, *args): value = self.COOKIES.get(*args) sec = self.app.config['securecookie.key'] dec = cookie_decode(value, sec) return dec or value class Response(threading.local): """ Represents a single response using thread-local namespace. """ def bind(self, app): """ Clears old data and creates a brand new Response object """ self._COOKIES = None self.status = 200 self.header_list = [] self.header = HeaderWrapper(self.header_list) self.charset = 'UTF-8' self.content_type = 'text/html; charset=UTF-8' self.error = None self.app = app def add_header(self, key, value): self.header.add_header(key.title(), str(value)) def wsgiheaders(self): ''' Returns a wsgi conform list of header/value pairs ''' for c in self.COOKIES.values(): self.add_header('Set-Cookie', c.OutputString()) return self.header_list @property def COOKIES(self): if not self._COOKIES: self._COOKIES = SimpleCookie() return self._COOKIES def set_cookie(self, key, value, **kargs): """ Sets a Cookie. Optional settings: expires, path, comment, domain, max-age, secure, version, httponly """ if not isinstance(value, basestring): sec = self.app.config['securecookie.key'] value = cookie_encode(value, sec) self.COOKIES[key] = value for k, v in kargs.iteritems(): self.COOKIES[key][k.replace('_', '-')] = v def get_content_type(self): """ Get the current 'Content-Type' header. """ return self.header['Content-Type'] def set_content_type(self, value): if 'charset=' in value: self.charset = value.split('charset=')[-1].split(';')[0].strip() self.header['Content-Type'] = value content_type = property(get_content_type, set_content_type, None, get_content_type.__doc__) class BaseController(object): _singleton = None def __new__(cls, *a, **k): if not cls._singleton: cls._singleton = object.__new__(cls, *a, **k) return cls._singleton _default_app = Bottle() def app(newapp = None): """ Returns the current default app or sets a new one. Defaults to an instance of Bottle """ global _default_app if newapp: _default_app = newapp return _default_app default_app = app # BC: 0.6.4 def abort(code=500, text='Unknown Error: Appliction stopped.'): """ Aborts execution and causes a HTTP error. """ raise HTTPError(code, text) def redirect(url, code=303): """ Aborts execution and causes a 303 redirect """ scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/' response.header['Location'] = urljoin(request.url, urljoin(scriptname, url)) raise HTTPError(code, "") def send_file(*a, **k): #BC 0.6.4 """ Raises the output of static_file() """ raise static_file(*a, **k) def static_file(filename, root, guessmime = True, mimetype = None, download = False): """ Opens a file in a save way and returns a HTTPError object with status code 200, 305, 401 or 404. Sets Content-Type, Content-Length and Last-Modified header. Obeys If-Modified-Since header and HEAD requests. """ root = os.path.abspath(root) + os.sep filename = os.path.abspath(os.path.join(root, filename.strip('/\\'))) if not filename.startswith(root): return HTTPError(401, "Access denied.") if not os.path.exists(filename) or not os.path.isfile(filename): return HTTPError(404, "File does not exist.") if not os.access(filename, os.R_OK): return HTTPError(401, "You do not have permission to access this file.") if guessmime and not mimetype: mimetype = mimetypes.guess_type(filename)[0] if not mimetype: mimetype = 'text/plain' response.content_type = mimetype if download == True: request.header['Content-Disposition'] = 'attachment; filename=%s' %\ os.path.basename(filename) elif download: request.header['Content-Disposition'] = 'attachment; filename=%s' %\ download stats = os.stat(filename) if 'Last-Modified' not in response.header: lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime)) response.header['Last-Modified'] = lm if 'HTTP_IF_MODIFIED_SINCE' in request.environ: ims = request.environ['HTTP_IF_MODIFIED_SINCE'] # IE sends "<date>; length=146" ims = ims.split(";")[0].strip() ims = parse_date(ims) if ims is not None and ims >= stats.st_mtime: return HTTPError(304, "Not modified") if 'Content-Length' not in response.header: response.header['Content-Length'] = str(stats.st_size) if request.method == 'HEAD': return HTTPResponse('') else: return HTTPResponse(open(filename, 'rb')) def parse_date(ims): """ Parses date strings usually found in HTTP header and returns UTC epoch. Understands rfc1123, rfc850 and asctime. """ try: ts = email.utils.parsedate_tz(ims) if ts is not None: if ts[9] is None: return time.mktime(ts[:8] + (0,)) - time.timezone else: return time.mktime(ts[:8] + (0,)) - ts[9] - time.timezone except (ValueError, IndexError): return None def parse_auth(header): try: method, data = header.split(None, 1) if method.lower() == 'basic': name, pwd = base64.b64decode(data).split(':', 1) return name, pwd except (KeyError, ValueError, TypeError), a: return None def cookie_encode(data, key): ''' Encode and sign a pickle-able object. Return a string ''' msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(key, msg).digest()) return '!%s?%s' % (sig, msg) def cookie_decode(data, key): ''' Verify and decode an encoded string. Return an object or None''' if cookie_is_encoded(data): sig, msg = data.split('?',1) if sig[1:] == base64.b64encode(hmac.new(key, msg).digest()): return pickle.loads(base64.b64decode(msg)) return None def cookie_is_encoded(data): ''' Verify and decode an encoded string. Return an object or None''' return bool(data.startswith('!') and '?' in data) def url(routename, **kargs): """ Helper generates URLs out of anmed routes """ return app().get_url(routename, **kargs) # Decorators #TODO: Replace default_app() with app() def validate(**vkargs): """ Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403). """ def decorator(func): def wrapper(**kargs): for key, value in vkargs.iteritems(): if key not in kargs: abort(403, 'Missing parameter: %s' % key) try: kargs[key] = value(kargs[key]) except ValueError, e: abort(403, 'Wrong parameter format for: %s' % key) return func(**kargs) return wrapper return decorator def route(url, **kargs): ''' Decorator for requests routes ''' return default_app().route(url, **kargs) def get(url, **kargs): ''' Decorator for GET requests routes ''' return default_app().route(url, method='GET', **kargs) def post(url, **kargs): ''' Decorator for POST requests routes ''' return default_app().route(url, method='POST', **kargs) def put(url, **kargs): ''' Decorator for PUT requests routes ''' return default_app().route(url, method='PUT', **kargs) def delete(url, **kargs): ''' Decorator for DELETE requests routes ''' return default_app().route(url, method='DELETE', **kargs) def default(): """ Decorator for request handler. Same as set_default(handler). """ return default_app().default() def error(code=500): """ Decorator for error handler. Same as set_error_handler(code, handler). """ return default_app().error(code) # Server adapter class WSGIAdapter(object): def run(self, handler): # pragma: no cover pass def __repr__(self): return "%s()" % (self.__class__.__name__) class CGIServer(WSGIAdapter): def run(self, handler): from wsgiref.handlers import CGIHandler CGIHandler().run(handler) class ServerAdapter(WSGIAdapter): def __init__(self, host='127.0.0.1', port=8080, **kargs): WSGIAdapter.__init__(self) self.host = host self.port = int(port) self.options = kargs def __repr__(self): return "%s (%s:%d)" % (self.__class__.__name__, self.host, self.port) class WSGIRefServer(ServerAdapter): def run(self, handler): from wsgiref.simple_server import make_server srv = make_server(self.host, self.port, handler) srv.serve_forever() class CherryPyServer(ServerAdapter): def run(self, handler): from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler) server.start() class FlupServer(ServerAdapter): def run(self, handler): from flup.server.fcgi import WSGIServer WSGIServer(handler, bindAddress=(self.host, self.port)).run() class PasteServer(ServerAdapter): def run(self, handler): from paste import httpserver from paste.translogger import TransLogger app = TransLogger(handler) httpserver.serve(app, host=self.host, port=str(self.port), **self.options) class FapwsServer(ServerAdapter): """ Extremly fast webserver using libev. See http://william-os4y.livejournal.com/ Experimental ... """ def run(self, handler): import fapws._evwsgi as evwsgi from fapws import base evwsgi.start(self.host, self.port) evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('',app)) evwsgi.run() def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, interval=1, reloader=False, **kargs): """ Runs bottle as a web server. """ if not app: app = default_app() quiet = bool(kargs.get('quiet', False)) # Instantiate server, if it is a class instead of an instance if isinstance(server, type): if issubclass(server, CGIServer): server = server() elif issubclass(server, ServerAdapter): server = server(host=host, port=port, **kargs) if not isinstance(server, WSGIAdapter): raise RuntimeError("Server must be a subclass of WSGIAdapter") if not quiet and isinstance(server, ServerAdapter): # pragma: no cover if not reloader or os.environ.get('BOTTLE_CHILD') == 'true': print "Bottle server starting up (using %s)..." % repr(server) print "Listening on http://%s:%d/" % (server.host, server.port) print "Use Ctrl-C to quit." print else: print "Bottle auto reloader starting up..." try: if reloader and interval: reloader_run(server, app, interval) else: server.run(app) except KeyboardInterrupt: if not quiet: # pragma: no cover print "Shutting Down..." #TODO: If the parent process is killed (with SIGTERM) the childs survive... def reloader_run(server, app, interval): if os.environ.get('BOTTLE_CHILD') == 'true': # We are a child process files = dict() for module in sys.modules.values(): file_path = getattr(module, '__file__', None) if file_path and os.path.isfile(file_path): file_split = os.path.splitext(file_path) if file_split[1] in ('.py', '.pyc', '.pyo'): file_path = file_split[0] + '.py' files[file_path] = os.stat(file_path).st_mtime thread.start_new_thread(server.run, (app,)) while True: time.sleep(interval) for file_path, file_mtime in files.iteritems(): if not os.path.exists(file_path): print "File changed: %s (deleted)" % file_path elif os.stat(file_path).st_mtime > file_mtime: print "File changed: %s (modified)" % file_path else: continue print "Restarting..." app.serve = False time.sleep(interval) # be nice and wait for running requests sys.exit(3) while True: args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' exit_status = subprocess.call(args, env=environ) if exit_status != 3: sys.exit(exit_status) # Templates class TemplateError(HTTPError): def __init__(self, message): HTTPError.__init__(self, 500, message) class BaseTemplate(object): def __init__(self, template='', name=None, filename=None, lookup=[]): """ Create a new template. If a name is provided, but no filename and no template string, the filename is guessed using the lookup path list. Subclasses can assume that either self.template or self.filename is set. If both are present, self.template should be used. """ self.name = name self.filename = filename self.template = template self.lookup = lookup if self.name and not self.filename: for path in self.lookup: fpath = os.path.join(path, self.name+'.tpl') if os.path.isfile(fpath): self.filename = fpath if not self.template and not self.filename: raise TemplateError('Template (%s) not found.' % self.name) self.prepare() def prepare(self): """ Run preparatios (parsing, caching, ...). It should be possible to call this multible times to refresh a template. """ raise NotImplementedError def render(self, **args): """ Render the template with the specified local variables and return an iterator of strings (bytes). This must be thread save! """ raise NotImplementedError class MakoTemplate(BaseTemplate): output_encoding=None input_encoding=None default_filters=None global_variables={} def prepare(self): from mako.template import Template from mako.lookup import TemplateLookup #TODO: This is a hack... http://github.com/defnull/bottle/issues#issue/8 mylookup = TemplateLookup(directories=map(os.path.abspath, self.lookup)+['./']) if self.template: self.tpl = Template(self.template, lookup=mylookup, output_encoding=MakoTemplate.output_encoding, input_encoding=MakoTemplate.input_encoding, default_filters=MakoTemplate.default_filters ) else: self.tpl = Template(filename=self.filename, lookup=mylookup, output_encoding=MakoTemplate.output_encoding, input_encoding=MakoTemplate.input_encoding, default_filters=MakoTemplate.default_filters ) def render(self, **args): _defaults = MakoTemplate.global_variables.copy() _defaults.update(args) return self.tpl.render(**_defaults) class CheetahTemplate(BaseTemplate): def prepare(self): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} if self.template: self.tpl = Template(source=self.template, searchList=[self.context.vars]) else: self.tpl = Template(file=self.filename, searchList=[self.context.vars]) def render(self, **args): self.context.vars.update(args) out = str(self.tpl) self.context.vars.clear() return [out] class Jinja2Template(BaseTemplate): env = None # hopefully, a Jinja environment is actually thread-safe def prepare(self): if not self.env: from jinja2 import Environment, FunctionLoader self.env = Environment(line_statement_prefix="#", loader=FunctionLoader(self.loader)) if self.template: self.tpl = self.env.from_string(self.template) else: self.tpl = self.env.get_template(self.filename) def render(self, **args): return self.tpl.render(**args).encode("utf-8") def loader(self, name): if not name.endswith(".tpl"): for path in self.lookup: fpath = os.path.join(path, name+'.tpl') if os.path.isfile(fpath): name = fpath break f = open(name) try: return f.read() finally: f.close() class SimpleTemplate(BaseTemplate): re_python = re.compile(r'^\s*%\s*(?:(if|elif|else|try|except|finally|for|' 'while|with|def|class)|(include|rebase)|(end)|(.*))') re_inline = re.compile(r'\{\{(.*?)\}\}') dedent_keywords = ('elif', 'else', 'except', 'finally') def prepare(self): if self.template: code = self.translate(self.template) self.co = compile(code, '<string>', 'exec') else: code = self.translate(open(self.filename).read()) self.co = compile(code, self.filename, 'exec') def translate(self, template): indent = 0 strbuffer = [] code = [] self.includes = dict() class PyStmt(str): def __repr__(self): return 'str(' + self + ')' def flush(allow_nobreak=False): if len(strbuffer): if allow_nobreak and strbuffer[-1].endswith("\\\\\n"): strbuffer[-1]=strbuffer[-1][:-3] code.append(' ' * indent + "_stdout.append(%s)" % repr(''.join(strbuffer))) code.append((' ' * indent + '\n') * len(strbuffer)) # to preserve line numbers del strbuffer[:] def cadd(line): code.append(" " * indent + line.strip() + '\n') for line in template.splitlines(True): m = self.re_python.match(line) if m: flush(allow_nobreak=True) keyword, subtpl, end, statement = m.groups() if keyword: if keyword in self.dedent_keywords: indent -= 1 cadd(line[m.start(1):]) indent += 1 elif subtpl: tmp = line[m.end(2):].strip().split(None, 1) if not tmp: cadd("_stdout.extend(_base)") else: name = tmp[0] args = tmp[1:] and tmp[1] or '' if name not in self.includes: self.includes[name] = SimpleTemplate(name=name, lookup=self.lookup) if subtpl == 'include': cadd("_ = _includes[%s].execute(_stdout, %s)" % (repr(name), args)) else: cadd("_tpl['_rebase'] = (_includes[%s], dict(%s))" % (repr(name), args)) elif end: indent -= 1 cadd('#' + line[m.start(3):]) elif statement: cadd(line[m.start(4):]) else: splits = self.re_inline.split(line) # text, (expr, text)* if len(splits) == 1: strbuffer.append(line) else: flush() for i in range(1, len(splits), 2): splits[i] = PyStmt(splits[i]) splits = [x for x in splits if bool(x)] cadd("_stdout.extend(%s)" % repr(splits)) flush() return ''.join(code) def execute(self, stdout, **args): args['_stdout'] = stdout args['_includes'] = self.includes args['_tpl'] = args eval(self.co, args) if '_rebase' in args: subtpl, args = args['_rebase'] args['_base'] = stdout[:] #copy stdout del stdout[:] # clear stdout return subtpl.execute(stdout, **args) return args def render(self, **args): """ Render the template using keyword arguments as local variables. """ stdout = [] self.execute(stdout, **args) return stdout def template(tpl, template_adapter=SimpleTemplate, **args): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. ''' lookup = args.get('template_lookup', TEMPLATE_PATH) if tpl not in TEMPLATES or DEBUG: if "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tpl] = template_adapter(template=tpl, lookup=lookup) elif '.' in tpl: TEMPLATES[tpl] = template_adapter(filename=tpl, lookup=lookup) else: TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup) if not TEMPLATES[tpl]: abort(500, 'Template (%s) not found' % tpl) args['abort'] = abort args['request'] = request args['response'] = response return TEMPLATES[tpl].render(**args) def mako_template(tpl_name, **kargs): kargs['template_adapter'] = MakoTemplate return template(tpl_name, **kargs) def cheetah_template(tpl_name, **kargs): kargs['template_adapter'] = CheetahTemplate return template(tpl_name, **kargs) def jinja2_template(tpl_name, **kargs): kargs['template_adapter'] = Jinja2Template return template(tpl_name, **kargs) def view(tpl_name, **defaults): ''' Decorator: Rendes a template for a handler. Return a dict of template vars to fill out the template. ''' def decorator(func): def wrapper(**kargs): out = func(**kargs) defaults.update(out) return template(tpl_name, **defaults) return wrapper return decorator def mako_view(tpl_name, **kargs): kargs['template_adapter'] = MakoTemplate return view(tpl_name, **kargs) def cheetah_view(tpl_name, **kargs): kargs['template_adapter'] = CheetahTemplate return view(tpl_name, **kargs) def jinja2_view(tpl_name, **kargs): kargs['template_adapter'] = Jinja2Template return view(tpl_name, **kargs) # Modul initialization and configuration TEMPLATE_PATH = ['./', './views/'] TEMPLATES = {} DEBUG = False HTTP_CODES = { 100: 'CONTINUE', 101: 'SWITCHING PROTOCOLS', 200: 'OK', 201: 'CREATED', 202: 'ACCEPTED', 203: 'NON-AUTHORITATIVE INFORMATION', 204: 'NO CONTENT', 205: 'RESET CONTENT', 206: 'PARTIAL CONTENT', 300: 'MULTIPLE CHOICES', 301: 'MOVED PERMANENTLY', 302: 'FOUND', 303: 'SEE OTHER', 304: 'NOT MODIFIED', 305: 'USE PROXY', 306: 'RESERVED', 307: 'TEMPORARY REDIRECT', 400: 'BAD REQUEST', 401: 'UNAUTHORIZED', 402: 'PAYMENT REQUIRED', 403: 'FORBIDDEN', 404: 'NOT FOUND', 405: 'METHOD NOT ALLOWED', 406: 'NOT ACCEPTABLE', 407: 'PROXY AUTHENTICATION REQUIRED', 408: 'REQUEST TIMEOUT', 409: 'CONFLICT', 410: 'GONE', 411: 'LENGTH REQUIRED', 412: 'PRECONDITION FAILED', 413: 'REQUEST ENTITY TOO LARGE', 414: 'REQUEST-URI TOO LONG', 415: 'UNSUPPORTED MEDIA TYPE', 416: 'REQUESTED RANGE NOT SATISFIABLE', 417: 'EXPECTATION FAILED', 500: 'INTERNAL SERVER ERROR', 501: 'NOT IMPLEMENTED', 502: 'BAD GATEWAY', 503: 'SERVICE UNAVAILABLE', 504: 'GATEWAY TIMEOUT', 505: 'HTTP VERSION NOT SUPPORTED', } ERROR_PAGE_TEMPLATE = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>Error %(status)d: %(error_name)s</title> </head> <body> <h1>Error %(status)d: %(error_name)s</h1> <p>Sorry, the requested URL <tt>%(url)s</tt> caused an error:</p> <pre> %(error_message)s </pre> </body> </html> """ request = Request() response = Response() local = threading.local() #TODO: Global and app local configuration (debug, defaults, ...) is a mess def debug(mode=True): global DEBUG DEBUG = bool(mode)
Python
#!/usr/bin/env python '''PyLibrarian database model''' import ConfigParser from datetime import datetime, timedelta from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import * from sqlalchemy.schema import * from sqlalchemy.engine import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm.session import sessionmaker config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) engine = create_engine(config.get('backend', 'connection_string')) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base(bind=engine) class User(Base): '''Users table - keeps track of the library users''' __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(Unicode(100), index=True) username = Column(Unicode(100), unique=True, nullable=False) password = Column(Unicode(100)) street = Column(Unicode(500)) city = Column(Unicode(100)) state = Column(Unicode(100)) zip = Column(Integer) phone = Column(Unicode(25)) email = Column(Unicode(250)) admin = Column(Boolean, default=False, nullable=False) class ResourceType(Base): '''ResourceTypes table - keeps tracks of different types of resources''' __tablename__ = 'resource_types' id = Column(Integer, primary_key=True) description = Column(String(100), unique=True, nullable=False) class Resource(Base): '''Resources table - keeps track of the resources in the library''' __tablename__ = 'resources' id = Column(Integer, primary_key=True) isbn = Column(Unicode(50), index=True) # May be left blank if the resource doesn't have an ISBN title = Column(Unicode(500), index=True) author = Column(Unicode(500), nullable=False) publisher = Column(Unicode(500)) resource_type_id = Column(ForeignKey('resource_types.id', name='resource_type_id'), nullable=False) summary = Column(UnicodeText()) class Loan(Base): '''Loans table - keeps track of which resources are checked out''' __tablename__ = 'loans' id = Column(Integer, primary_key=True) resource_id = Column(ForeignKey('resources.id', name='resource_id'), nullable=False) user_id = Column(ForeignKey('users.id', name='user_id'), nullable=False) checkout_date = Column(DateTime, default=datetime.now) due_date = Column(DateTime, default=lambda x=None: datetime.now() + timedelta(weeks=config.getint('library', 'checkout_time'))) returned_date = Column(DateTime) class Hold(Base): '''Holds table - keeps track of which resources are on hold''' __tablename__ = 'holds' id = Column(Integer, primary_key=True) resource_isbn = Column(Integer, primary_key=True) user_id = Column(ForeignKey('users.id', name='user_id')) date = Column(DateTime, default=datetime.now) def addResourceTypes(event, target, bind): db = session() try: types = ['Book', # A list of the resource types supported by the library 'Cassette', 'CD', 'DVD', 'VHS'] for type in types: rec = db.query(ResourceType).filter_by(description=type).first() if not rec: rec = ResourceType(description=type) db.add(rec) db.commit() finally: db.close() Base.metadata.append_ddl_listener('after-create', addResourceTypes) Base.metadata.create_all()
Python
#!/usr/bin/env python '''PyLibrarian label generator (for generating book labels to be printed on Avery 5160/8160 or compatible address labels)''' try: import json except ImportError: import simplejson as json import ConfigParser from reportlab.pdfgen.canvas import Canvas from reportlab.lib.pagesizes import letter from reportlab.lib.units import cm, mm, inch, pica from reportlab.graphics.barcode.code128 import Code128 config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) libraryName = config.get('library', 'name') def cmpData(a, b): '''Comparison function for sorting lists of dicts by the data key of the dict''' if a['data'] < b['data']: return -1 elif a['data'] > b['data']: return 1 else: return 0 def generateLabels(data): '''Generates book labels using the data dictionary passed in. Each code should be an integer, and will be printed using 9 digits (padded with zeroes if necessary). Up to 30 labels will be generated per page for compatibility with Avery 5160/8160 or most other address label forms containing 30 per sheet. The text of a PDF document is returned (to be sent back to the browser).''' pdf = Canvas("foo.pdf", pagesize = letter) # PDF name is irrelevant as it only ever exists in RAM pdf.setFillColorRGB(0, 0, 0) imgX = startX = 45 imgY = startY = letter[1] - 71 for res in data: txt = '%09d' % res['code'] if imgX > 600: # Start a new page imgX = startX imgY = startY pdf.showPage() # Generate and draw the barcode codeImg = Code128(txt, barWidth=.9) codeImg.drawOn(pdf, imgX, imgY) pdf.setFont("Courier", 12) pdf.drawCentredString(imgX + 64.5, imgY - 10, txt) pdf.setFont("Courier", 10) pdf.drawCentredString(imgX + 64.5, imgY - 20, res['data'].upper()[:20].strip()) imgY -= 73 # Move down to the next label location if imgY < 50: # Start a new column imgY = startY imgX += 200 pdf.showPage() return pdf.getpdfdata() def generateLibrarianCardholderSheet(data): '''Generates a sheet with 30 cardholder barcodes per page. This is useful for smaller libraries that want to keep a master sheet in case one of their cardholders forgets his/her card.''' pdf = Canvas("bar.pdf", pagesize = letter) # PDF name is irrelevant as it only ever exists in RAM pdf.setFillColorRGB(0, 0, 0) imgX = startX = 45 imgY = startY = letter[1] - 71 data.sort(cmpData) # Keep the librarian sheets in alphabetical order for res in data: txt = '%08d' % res['code'] if imgX > 600: # Start a new page imgX = startX imgY = startY pdf.showPage() # Generate and draw the barcode codeImg = Code128(txt, barWidth=.9) codeImg.drawOn(pdf, imgX, imgY) pdf.setFont("Courier", 12) pdf.drawCentredString(imgX + 55, imgY - 10, txt) pdf.setFont("Courier", 10) pdf.drawCentredString(imgX + 55, imgY - 20, res['data'].upper()[:50].strip()) imgY -= 73 # Move down to the next label location if imgY < 50: # Start a new column imgY = startY imgX += 200 pdf.showPage() return pdf.getpdfdata() def generateCards(data): '''Generates library cards using the data dictionary passed in. Each user id should be an integer, and will be printed using 8 digits (padded with zeroes if necessary). The resulting PDF can be printed on Avery 5390 or a compatible template.''' pdf = Canvas("bar.pdf", pagesize = letter) # PDF name is irrelevant as it only ever exists in RAM pdf.setFillColorRGB(0, 0, 0) imgX = startX = 120 imgY = startY = letter[1] - 135 for res in data: txt = '%08d' % res['code'] if imgX > 600: # Start a new page imgX = startX imgY = startY pdf.showPage() # Generate and draw the barcode codeImg = Code128(txt, barWidth=.9) codeImg.drawOn(pdf, imgX, imgY) pdf.setFont("Courier", 12) pdf.drawCentredString(imgX + 55, imgY - 10, txt) pdf.setFont("Courier", 10) pdf.drawCentredString(imgX + 55, imgY - 20, res['data'].upper()[:25].strip()) pdf.setFont("Courier", 10) pdf.drawCentredString(imgX + 55, imgY - 40, libraryName.upper()[:30].strip()) imgY -= 170 # Move down to the next label location if imgY < 50: # Start a new column imgY = startY imgX += 260 pdf.showPage() return pdf.getpdfdata()
Python
#!/usr/bin/env python '''PyLibrarian web administration interface''' import ConfigParser import math import database import model import urllib2 import traceback import codecs import pdfGen import os from bottle import * from xml.dom import minidom from beaker.middleware import SessionMiddleware try: import json except ImportError: import simplejson as json config = ConfigParser.ConfigParser() config.readfp(open('config.ini')) libraryName = config.get('library', 'name') accessKey = config.get('library', 'isbndb_access_key') paging = config.getint('library', 'paging') server_port = config.get('backend', 'server_port') app = default_app() session_opts = { 'session.type': 'file', 'session.cookie_expires': 300, 'session.data_dir': os.path.join(os.path.dirname(__file__), 'data') } app = SessionMiddleware(app, session_opts) # # Page handlers # @route('/') def index(): '''Web access front page''' numResources = len(database.getResources()) popularResources = database.getPopularResources() resourceTypes = dict([(res['id'], res['description']) for res in database.getResourceTypes()]) resourceAvailability = dict((resource['id'], True if database.isResourceCheckedIn(resource['id']) else False) for resource in popularResources) return template('index', libraryName=libraryName, numResources=numResources, popularResources=popularResources, resourceAvailability=resourceAvailability, resourceTypes=resourceTypes) @route('/search') def search(): '''Resource search results page''' searchText = request.GET.get('search_text', '').strip() page = int(request.GET.get('page', 1)) asc = int(request.GET.get('asc', 0)) sortColumn = eval('model.Resource.%s' % request.GET.get('sort', '')) \ if hasattr(model.Resource, request.GET.get('sort', '')) \ else None query = database.searchResources(searchText) numResults = query.count() if sortColumn: query = query.order_by(sortColumn.asc()) if asc else query.order_by(sortColumn.desc()) resources = [result.__dict__ for result in query .limit(paging) .offset((page - 1) * paging) .all()] resourceTypes = dict([(res['id'], res['description']) for res in database.getResourceTypes()]) resourceAvailability = dict((resource['id'], True if database.isResourceCheckedIn(resource['id']) else False) for resource in resources) return template('search', libraryName=libraryName, searchText=searchText, resources=resources, resourceTypes=resourceTypes, resourceAvailability=resourceAvailability, page=page, numPages=int(math.ceil(numResults / float(paging))), numResults=numResults, paging=paging, sortColumn=request.GET.get('sort', ''), asc=asc) @route('/administration') def admin(): '''Administration home page''' if not check_admin_login(request): redirect('/administration/login') return template('admin', libraryName=libraryName, message=request.GET.get('result', '')) @route('/administration/addResourceStep2', method='POST') def addResourceStep2(): '''Page for filling out information for a new resource''' if not check_admin_login(request): redirect('/administration/login') error = False isbn = request.POST.get('isbn') data = lookupISBN(isbn) resourceTypes = database.getResourceTypes() if not data: error = True data = {'isbn': isbn} if data.get('inDB'): database.addResource(data.get('isbn'), data.get('resource_type_id'), data.get('title'), data.get('author'), data.get('publisher'), data.get('summary')) redirect('/administration/manageResources?message=Resource+added+automatically+since+we+already+have+another+copy+of+it') else: return template('addResourceStep2', libraryName=libraryName, data=data, resourceTypes=resourceTypes, error=error, noISBN=isbn.strip() == '') @route('/administration/addResource', method='POST') def addResource(): '''Adds a resource to the database''' if not check_admin_login(request): redirect('/administration/login') isbn = request.POST.get('isbn') title = request.POST.get('title') author = request.POST.get('author') publisher = request.POST.get('publisher') resource_type_id = request.POST.get('resource_type_id') summary = request.POST.get('summary') database.addResource(isbn, resource_type_id, title, author, publisher, summary) redirect('/administration/manageResources?message=Success%21') @route('/administration/deleteResource/:id') def deleteResource(id): '''Removes a resource from the database''' if not check_admin_login(request): redirect('/administration/login') database.deleteResourceByID(id) redirect('/administration/manageResources?message=Resource%20deleted') @route('/administration/manageResources') def manageResources(): '''Page listing resources and management options''' if not check_admin_login(request): redirect('/administration/login') resourceTypes = dict([(res['id'], res['description']) for res in database.getResourceTypes()]) resources = database.getResources() resourceAvailability = dict((resource['id'], True if database.isResourceCheckedIn(resource['id']) else False) for resource in resources) message = request.GET.get('message', '') return template('manageResources', libraryName=libraryName, resources=resources, resourceTypes=resourceTypes, message=message, resourceAvailability=resourceAvailability) @route('/administration/manageResource/:id') def manageResource(id): '''Page for managing a resource''' if not check_admin_login(request): redirect('/administration/login') resource = database.getResourceByID(id) resourceTypes = database.getResourceTypes() return template('manageResource', libraryName=libraryName, data=resource, resourceTypes=resourceTypes) @route('/administration/checkedOut') def checkedOutResources(): '''Page that lists checked out resources''' try: checkIn = request.GET.get('checkIn') if checkIn and checkIn.isdigit(): database.checkinResource(int(checkIn)) resources = database.getCheckedOutResources() resourceTypes = dict([(res['id'], res['description']) for res in database.getResourceTypes()]) return template('checkedOut', libraryName=libraryName, resources=resources, resourceTypes=resourceTypes, overdue=False) except: print traceback.format_exc() raise @route('/administration/overdue') def overdueResources(): '''Page that lists overdue resources''' try: resources = database.getCheckedOutResources(overdue=True) resourceTypes = dict([(res['id'], res['description']) for res in database.getResourceTypes()]) return template('checkedOut', libraryName=libraryName, resources=resources, resourceTypes=resourceTypes, overdue=True) except: print traceback.format_exc() raise @route('/administration/updateResource/:isbn', method='POST') def updateResource(isbn): '''Updates a resource's database record''' if not check_admin_login(request): redirect('/administration/login') title = request.POST.get('title') author = request.POST.get('author') publisher = request.POST.get('publisher') resource_type_id = request.POST.get('resource_type_id') summary = request.POST.get('summary') if isbn != 'NO ISBN': database.updateResourcesByISBN(isbn, resource_type_id, title, author, publisher, summary) else: database.updateResource(request.POST.get('id'), resource_type_id, title, author, publisher, summary) redirect('/administration/manageResources?message=Resource%20updated') @route('/administration/addUser', method='POST') def addUser(): '''Adds a user to the system''' if not check_admin_login(request): redirect('/administration/login') name = request.POST.get('name') username = request.POST.get('username') password = request.POST.get('password') street = request.POST.get('street') city = request.POST.get('city') state = request.POST.get('state') zip = request.POST.get('zip') phone = request.POST.get('phone') email = request.POST.get('email') database.addUser(name, username, password, street, city, state, zip, phone, email) redirect('/administration/manageUsers?message=Success%21') @route('/administration/manageUsers') def manageUsers(): '''Page listing users with management options''' if not check_admin_login(request): redirect('/administration/login') users = database.getUsers() message = request.GET.get('message', '') return template('manageUsers', libraryName=libraryName, users=users, message=message) @route('/administration/manageUser/:id') def manageUser(id): '''Page for managing user information''' if not check_admin_login(request): redirect('/administration/login') user = database.getUserByID(id) resourceTypes = database.getResourceTypes() return template('manageUser', libraryName=libraryName, data=user, resourceTypes=resourceTypes) @route('/administration/updateUser/:id', method='POST') def updateUser(id): '''Updates user information''' if not check_admin_login(request): redirect('/administration/login') name = request.POST.get('name') username = request.POST.get('username') password = request.POST.get('password') street = request.POST.get('street') city = request.POST.get('city') state = request.POST.get('state') zip = request.POST.get('zip') phone = request.POST.get('phone') email = request.POST.get('email') database.updateUser(id, name, username, password, street, city, state, zip, phone, email) redirect('/administration/manageUsers?message=User%20updated') @route('/administration/deleteUser/:id') def deleteUser(id): '''Removes a user from the system''' if not check_admin_login(request): redirect('/administration/login') database.deleteUser(id) redirect('/administration/manageUsers?message=User%20deleted') @route('/administration/printLabels') def printLabels(): '''Book selection page for label printing''' if not check_admin_login(request): redirect('/administration/login') resourceTypes = dict([(res['id'], res['description']) for res in database.getResourceTypes()]) resources = database.getResources() resourceAvailability = dict((resource['id'], True if database.isResourceCheckedIn(resource['id']) else False) for resource in resources) return template('printLabels', libraryName=libraryName, resources=resources, resourceTypes=resourceTypes) @route('/administration/generateLabels.pdf', method='GET') def generateLabels(): '''Label generation page - serves a dynamically generated PDF with printable barcodes for the requested books''' if not check_admin_login(request): redirect('/administration/login') ids = json.loads(request.GET.get('ids')) response.content_type = 'application/pdf' return pdfGen.generateLabels(ids) @route('/administration/printCards') def printCards(): '''Book selection page for label printing''' if not check_admin_login(request): redirect('/administration/login') users = database.getUsers() return template('printCards', libraryName=libraryName, users=users) @route('/administration/generateCards.pdf', method='GET') def generateCards(): '''Library Card generation page - serves a dynamically generated PDF with printable barcodes for the requested users''' if not check_admin_login(request): redirect('/administration/login') ids = json.loads(request.GET.get('ids')) response.content_type = 'application/pdf' return pdfGen.generateCards(ids) @route('/administration/generateLibrarianCardSheet.pdf', method='GET') def generateCardSheet(): '''Library Card generation page - serves a dynamically generated PDF with printable barcodes for the requested users''' if not check_admin_login(request): redirect('/administration/login') ids = json.loads(request.GET.get('ids')) response.content_type = 'application/pdf' return pdfGen.generateLibrarianCardholderSheet(ids) @route('/administration/login') def adminLogin(): '''Login page''' error = False if request.GET.get('pylibrary_username') and check_admin_login(request, request.GET.get('pylibrary_username'), request.GET.get('pylibrary_password')): redirect('/administration') elif request.GET.get('pylibrary_username') or request.GET.get('pylibrary_password') : error = True return template('login', libraryName=libraryName, error=error) @route('/logout') def logout(): '''Logout page''' s = request.environ.get('beaker.session') s['admin_login'] = False s['logged_in'] = False s.save() redirect('/') # # Static file handlers # @route('/css/:filename#.*\.css#') def static_css(filename): '''CSS static file handler''' send_file(filename, root='css', mimetype='text/css') @route('/js/:filename#.*\.js#') def static_js(filename): '''JavaScript static file handler''' send_file(filename, root='js', mimetype='text/javascript') @route('/images/:filename#.*\.gif#') def static_gifs(filename): '''GIF static file handler''' send_file(filename, root='images', mimetype='image/gif') # # Utility functions # def check_admin_login(request, username=None, password=None): '''Checks a user's login credentials to ensure that the are 1) valid, and 2) they are for an administrator account''' s = request.environ.get('beaker.session') if s.get('admin_login'): return True try: if database.checkLogin(username, password).admin: s['admin_login'] = True s['logged_in'] = True s.save() return True else: return False except: return False def lookupISBN(isbn): '''Looks up information on an ISBN number from the local database first, and then isbndb.com if it is a new book to our system (not in the db)''' try: results = database.getResourcesByISBN(isbn) if results: result = results[0] title = result['title'] author = result['author'] publisher = result['publisher'] isbn = result['isbn'] resource_type_id = result['resource_type_id'] summary = result['summary'] inDB = True elif len(isbn) == 10 or len(isbn) == 13: # Save API calls when we scan a non-ISBN stream = urllib2.urlopen('http://isbndb.com/api/books.xml?access_key=%s&results=texts&index1=isbn&value1=%s' % (accessKey, isbn)) result = stream.read() stream.close() xmlDoc = minidom.parseString(result) resourceData = xmlDoc.getElementsByTagName('BookList')[0].getElementsByTagName('BookData')[0] title = resourceData.getElementsByTagName('Title')[0].firstChild.nodeValue.strip() author = resourceData.getElementsByTagName('AuthorsText')[0].firstChild.nodeValue.strip().rstrip(',') publisher = resourceData.getElementsByTagName('PublisherText')[0].firstChild.nodeValue.strip() isbn = resourceData.getAttribute('isbn13') if resourceData.hasAttribute('isbn13') else resourceData.getAttribute('isbn') try: summary = resourceData.getElementsByTagName('Summary')[0].firstChild.nodeValue.strip() except: print 'error getting summary:', traceback.format_exc() summary = '' inDB = False resource_type_id = None else: return {} return {'title': title, 'author': author, 'publisher': publisher, 'summary': summary, 'isbn': isbn, 'resource_type_id': resource_type_id, 'inDB': inDB} except: print traceback.format_exc() return {} if __name__ == '__main__': run(app=app, host='0.0.0.0', port=server_port)
Python
# Django settings for website project. import os ROOT_PATH = os.path.dirname(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'inmo.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '#g16-2+c57$y108squ1l!#%+rjrtf2+t3t$*kvev79m*)0g=-c' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'website.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'website.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(ROOT_PATH, 'templates') ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'inmobiliarias', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
Python
from django.conf.urls import patterns, include, url from inmobiliarias.views import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^buscar/?$', ResultadoBusquedaView.as_view(), name='result'), url(r'^ndpto/?$', CrearDpto.as_view(), name='nuevoDpto'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
Python
""" WSGI config for website project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Python
from django.db import models from django.contrib.auth.models import User, UserManager ESTADOS_CHOICES = ( ('A Estrenar', 'A Estrenar'), ('Excelente', 'Excelente'), ('Muy Bueno', 'Muy Bueno'), ('Bueno', 'Bueno'), ('Malo', 'Malo'), ('-', '-'), #agregar las "para reciclar"/demoler ) TIPO_CAMPO_CHOICES = ( ('', ''), ) TIPO_PROPIEDAD_CHOICES = ( ('Casa', 'Casa' ), ('Departamento', 'Departamento' ), ('Campo', 'Campo' ), ('Terreno', 'Terreno' ), ('Quinta', 'Quinta' ), ('Local', 'Local' ), ) TIPO_OPERACION_CHOICES = ( ('Venta', 'Venta'), ('Alquiler', 'Alquiler'), ) CIUDADES_CHOICES = ( ('Rio Cuarto', 'Rio Cuarto'), ('Cordoba', 'Cordoba'), ) PROVINCIAS_CHOICES = ( ('Cordoba', 'Cordoba'), ) class Propiedad(models.Model): #cantidad de visitas #agregar video e imagenes publicante = models.ForeignKey(User, null = True) titulo = models.CharField(max_length=100) descripcion_corta = models.CharField(max_length=200) descripcion = models.TextField() destacado = models.BooleanField() provincia = models.CharField(max_length=25, choices=PROVINCIAS_CHOICES) ciudad = models.CharField(max_length=25, choices=CIUDADES_CHOICES) direccion = models.CharField(max_length=25) tipo = models.CharField(max_length=25, choices=TIPO_PROPIEDAD_CHOICES) estado = models.CharField(max_length=25, choices=ESTADOS_CHOICES) precio = models.IntegerField() fecha_publicacion = models.DateTimeField() class Inmobiliaria(User): nombre = models.CharField(max_length=25) direccion = models.CharField(max_length=25) limite = models.PositiveIntegerField() objects = UserManager() class Departamento(Propiedad): cantidad_habitaciones = models.IntegerField() cantidad_ambientes = models.IntegerField() cantidad_metros = models.IntegerField() nro_piso = models.IntegerField() cochera = models.BooleanField() balcon = models.BooleanField() vista_a_calle = models.BooleanField() todos_los_servicios = models.BooleanField() dependencia = models.BooleanField() amoblado = models.BooleanField() class Casa(Propiedad): cantidad_habitaciones = models.IntegerField() cantidad_banos = models.IntegerField() cantidad_metros = models.IntegerField() patio = models.BooleanField() garage = models.BooleanField() todos_los_servicios = models.BooleanField() dependencia = models.BooleanField() amoblado = models.BooleanField() class Local(Propiedad): cantidad_metros_cuadrados = models.IntegerField() class Terreno(Propiedad): todos_los_servicios = models.BooleanField() class Quinta(Propiedad): hectareas = models.IntegerField() class Campo(Propiedad): hectareas = models.IntegerField() tipo_campo = models.CharField(max_length=25, choices=TIPO_CAMPO_CHOICES)
Python
from django.forms import ModelForm, Form, ModelChoiceField, IntegerField, CharField, Select from models import * class PropiedadSearchForm(Form): provincia = CharField(max_length=25, widget= Select(choices=PROVINCIAS_CHOICES)) ciudad = CharField(max_length=25, widget= Select(choices=CIUDADES_CHOICES)) tipo = CharField(max_length=25, widget = Select(choices=TIPO_PROPIEDAD_CHOICES)) precio_desde = IntegerField(initial=0, min_value=0, label='desde') precio_hasta = IntegerField(label='hasta') class PropiedadForm(ModelForm): class Meta: model = Propiedad exclude = ('publicante',) class DepartamentoForm(ModelForm): class Meta: model = Departamento exclude = ('publicante',) class CasaForm(ModelForm): class Meta: model = Casa exclude = ('publicante',) class CampoForm(ModelForm): class Meta: model = Campo exclude = ('publicante',) class QuintaForm(ModelForm): class Meta: model = Quinta exclude = ('publicante',) class LocalForm(ModelForm): class Meta: model = Local exclude = ('publicante',) class TerrenoForm(ModelForm): class Meta: model = Terreno exclude = ('publicante',)
Python
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
Python
from django.http import HttpResponse, Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import TemplateView, ListView from django.views.generic.edit import CreateView from inmobiliarias.models import * from inmobiliarias.forms import * #vistas genericas class InmobiliariasView(TemplateView): def get_context_data(self, **kwargs): context = dict() context['current'] = getattr(self, 'current', None) return context class InmobiliariasListView(ListView): def get_context_data(self, **kwargs): context = dict() context['current'] = getattr(self, 'current', None) return context class GenericInicioView(InmobiliariasView): current = 'INICIO' class GenericListView(InmobiliariasListView): current = 'List' ##vistas concretas class HomeView(GenericInicioView): template_name = 'website/home.html' def get_context_data(self, **kwargs): context = super(GenericInicioView, self).get_context_data(**kwargs) context['formularioBusqueda'] = PropiedadSearchForm()#ver si ya la cargo no valido return context class ResultadoBusquedaView(ListView): context_object_name = "propiedades" template_name = 'website/resultado.html' paginate_by = 20 def get_queryset(self): form = PropiedadSearchForm(self.request.GET) if form.data['tipo'] == 'Casa': TipoPropiedad = Casa if form.data['tipo'] == 'Departamento': TipoPropiedad = Departamento if form.data['tipo'] == 'Campo': TipoPropiedad = Campo model = TipoPropiedad.objects.filter( ciudad=form.data['ciudad'], provincia=form.data['provincia'], precio__gte = form.data['precio_desde'], precio__lte = form.data['precio_hasta']) return model def get_context_data(self, **kwargs): context = super(ResultadoBusquedaView, self).get_context_data(**kwargs) context['formularioBusqueda'] = PropiedadSearchForm() return context class CrearDpto(CreateView): form_class = DepartamentoForm model = Departamento #class Busqueda(CreateView): # form_class = PropiedadForm # model = Propiedad # def form_valid(self, form): # #form.instance.publicante = self.request.user esto para publicar casa por inmobiliaria # return super(Busqueda, self).form_valid(form)
Python
from inmobiliarias.models import * from django.contrib import admin admin.site.register(Propiedad) admin.site.register(Inmobiliaria) admin.site.register(Departamento) admin.site.register(Casa)
Python
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1&sort=priority' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): # Handle missing version info (LooseVersion doesn't) if (a == ''): return -1 if (b == ''): return 1 av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1&sort=priority' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): # Handle missing version info (LooseVersion doesn't) if (a == ''): return -1 if (b == ''): return 1 av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1&sort=priority' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): # Handle missing version info (LooseVersion doesn't) if (a == ''): return -1 if (b == ''): return 1 av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1&sort=priority' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): # Handle missing version info (LooseVersion doesn't) if (a == ''): return -1 if (b == ''): return 1 av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Sets the property in a java property file to the specified value, or adds it if it isn't present. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. # NOTE: This is a huge amount of broilerplate, isn't there any better command line reader utility? import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print "Sets the property in a java property file to the specified value, or adds it if it isn't present." print ' -h, --help Show this help.' print ' -f, --file The property file to read from / edit.' print ' -p, --property The property to set.' print ' -v, --value The value to set the property to.' print ' -o, --output The output file. If omitted, the change is written back to the input file, if present, the change is written to the output file instead. If an empty string ("") for -o is given, the result is printed to stdout.' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:p:v:o:q", ["help", "file=","property=","value=","output=", "quiet"]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) FILE = '' PROPERTY = '' VALUE = None OUTPUT = None QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-f", "--file"): FILE = a elif o in ("-p", "--property"): PROPERTY = a elif o in ("-v", "--value"): VALUE = a elif o in ("-o", "--output"): OUTPUT = a else: assert False, 'unhandled option' if (PROPERTY == ''): print print 'Please specify a property.' usage() sys.exit(2) if (VALUE == None): print print 'Please specify a value.' usage() sys.exit(2) if (FILE == ''): print print 'Please specify a file.' usage() sys.exit(2) if (OUTPUT == None): OUTPUT = FILE # Load input file propertyFile = open(FILE, "rb") result = '' # Scan through the file and do a replace propertyFound = False line = propertyFile.readline() while line <> '': if line.strip().startswith( PROPERTY ): line = PROPERTY + "=" + VALUE + '\n' propertyFound = True result += line line = propertyFile.readline() propertyFile.close() if not propertyFound: result += '\n' + PROPERTY + "=" + VALUE + '\n' if (OUTPUT == ''): print result else: outputFile = open(OUTPUT,"w") outputFile.write( result ) outputFile.close() if not QUIET: print "Property '"+PROPERTY+"' changed to value '"+VALUE+"' in '" + OUTPUT +"'" print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1&sort=priority' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): # Handle missing version info (LooseVersion doesn't) if (a == ''): return -1 if (b == ''): return 1 av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#! /usr/bin/python # Google code issue system to changelist.txt generator. # Programmed 2008-11 by Hans Haggstrom (zzorn at iki.fi) # Public domain, adapt and use as you want. import csv, getopt, os, sys, datetime, time from distutils import version def usage(): print print 'Google code issue downloader and changelist generator' print ' -h, --help Show this help' print ' -p, --project The google code project id (this is a unix style user name, as used in the project URL). This is required.' print ' -n, --name The name to use for the project in the changelist. Defaults to the project name.' print ' -o, --output The name of the output file to save the report to. If not specified, will print to stdout.' print ' -r, --release The release to create a changelist for. All releases up to and including this release are included in the report. Default is 1.0.' print ' -t, --temp The name of the temporary file to load the issue csv to. Defaults to issue-changes.csv.' print ' --prefix The prefix used by the project for marking which release an issue belongs to. Defaults to "Release". (Currently only its length is used)' print ' -q, --quiet Does not print any output if there are no errors.' def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hp:n:o:r:t:q", ["help", "project=","name=","output=","release=","temp=", "quiet", "prefix="]) except getopt.GetoptError, err: # print help information and exit: print print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) APP_NAME = '' GOOGLE_CODE_PROJECT_ID = '' ISSUE_IMPORT_FILE = "issue-changes.csv" OUTPUT_FILE = '' RELEASE = '1.0' RELESE_PREFIX = 'Release' QUIET = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-q", "--quiet"): QUIET = True elif o in ("-p", "--project"): GOOGLE_CODE_PROJECT_ID = a elif o in ("-n", "--name"): APP_NAME = a elif o in ("-o", "--output"): OUTPUT_FILE = a elif o in ("-r", "--release"): RELEASE = a elif o in ("-t", "--temp"): ISSUE_IMPORT_FILE = a elif o in ("--prefix"): RELESE_PREFIX = a else: assert False, 'unhandled option' if (GOOGLE_CODE_PROJECT_ID == ''): print print 'Please specify a google project id using the -p option.' usage() sys.exit(2) if (APP_NAME == ''): APP_NAME = GOOGLE_CODE_PROJECT_ID # Download issues from google code in csv format url = 'http://code.google.com/p/'+GOOGLE_CODE_PROJECT_ID+'/issues/csv?can=1&sort=priority' wgetOpts = ' -q ' if not QUIET: print 'Downloading google code project issue list from ' + url wgetOpts = '' os.system(' wget '+wgetOpts+' -O '+ISSUE_IMPORT_FILE+' "'+url+'" ') # Load google code issue export file reader = csv.reader(open(ISSUE_IMPORT_FILE, "rb")) # Read in headers from the file headers = {} i = 0 for name in reader.next(): headers[name] = i i += 1 # Handle each issue, build a list of releases releases = {} openBugs = [] for row in reader: if len(row) > 0: issueNumber = row[headers['ID']] kind = row[headers['Type']] status = row[headers['Status']] priority = row[headers['Priority']] milestone = row[headers['Milestone']] [ len(RELESE_PREFIX) : ] owner = row[headers['Owner']] summary = row[headers['Summary']] release = {} if releases.has_key(milestone): release = releases[milestone] else: release['name'] = milestone release['features'] = [] release['bugfixes'] = [] release['enhancements'] = [] releases[milestone] = release entry = ' * Issue ' + issueNumber + ' ('+priority+'): ' + summary if status == 'Verified' or status == 'Fixed': if kind == 'Defect': release['bugfixes'].append( entry ) if kind == 'Enhancement': release['enhancements'].append( entry ) if (status == 'Accepted' or status == 'Started') and kind == 'Defect': openBugs.append( entry ) # Output the releases def compareVersion( a, b ): # Handle missing version info (LooseVersion doesn't) if (a == ''): return -1 if (b == ''): return 1 av = version.LooseVersion(a ) bv = version.LooseVersion(b ) return cmp( bv, av ) releaseIds = releases.keys() releaseIds.sort( compareVersion ) output = '' NL = '\n' output += NL output += 'Changelist for ' + APP_NAME + NL latestRelease = True for releaseId in releaseIds: if compareVersion( releaseId, RELEASE ) >= 0: release = releases[ releaseId ] output += NL output += NL output += ' ' + APP_NAME + ' v. ' + release['name'] + NL ## The features section is planned for more full length descriptions of major features implemented for the release ## and could be pulled from the wiki for example. ## TODO: Implement. #print #print ' Features ' #for f in release['features']: # print f output += NL output += ' Enhancements ' + NL for e in release['enhancements']: output += e + NL output += NL output += ' Fixed bugs ' + NL for b in release['bugfixes']: output += b + NL if latestRelease: latestRelease = False output += NL output += ' Known open bugs ' + NL for b in openBugs: output += b + NL output += NL output += NL output += 'This changelist was automatically generated on ' + str( datetime.date.today() ) + '.' + NL if (OUTPUT_FILE == ''): print output else: fileObj = open(OUTPUT_FILE,"w") fileObj.write( output ) fileObj.close() if not QUIET: print 'Changelist generated and saved to ' + OUTPUT_FILE print if __name__ == "__main__": main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import cgi import traceback try: import json except: import simplejson as json import threading import functools from xml.dom.minidom import parseString ''' import sae.const 'database':{ 'db':sae.const.MYSQL_DB, 'type':'mysql', 'name':'name', 'user':sae.const.MYSQL_USER, 'passwd':sae.const.MYSQL_PASS, 'host':sae.const.MYSQL_HOST, 'port':int(sae.const.MYSQL_PORT), 'charset':'utf8' }, ''' ##config config = { 'app':'demo', 'media':'public', 'template':'templates', 'template_module':'mako', 'database':{ 'db':'', 'type':'mysql', 'name':'name', 'user':'', 'passwd':'', 'host':'', 'port':'', 'charset':'utf8' }, 'middleware':[], 'storge':'threading', 'charset':'utf-8', 'base_path':os.path.abspath('.') } ##requst class InputProcessed(object): def read(self, *args): raise EOFError('The wsgi.input stream has already been consumed') readline = readlines = __iter__ = read class Requst(object): def __init__(self, environ): self.environ = environ self.input = environ['wsgi.input'] self.method = environ["REQUEST_METHOD"].upper() self.encoding = config['charset'] def is_post_request(self): if self.method != 'POST': return False content_type = self.environ.get("CONTENT_TYPE","application/x-www-form-urlencoded") return (content_type.startswith("application/x-www-form-urlencoded") or content_type.startswith("multipart/form-data")) def get_post_form(self): assert self.is_post_request() input = self.environ['wsgi.input'] post_form = self.environ.get('wsgi.post_form') if (post_form is not None and post_form[0] is input): return post_form[2] self.environ.setdefault('QUERY_STRING', '') fs = cgi.FieldStorage(fp=input, environ=self.environ, keep_blank_values=1) new_input = InputProcessed() post_form = (new_input, input, fs) self.environ['wsgi.post_form'] = post_form self.environ['wsgi.input'] = new_input return fs def run(self): post, get, files, cookie = {}, {}, {}, {} if self.is_post_request(): fs = self.get_post_form() for key in fs.keys(): if key == 'file': files.update({key:{"filename":fs[key].filename, "file": fs[key].file}}) else: post.update({key: fs[key].value}) request.POST = post request.files = files querys = self.environ.get("QUERY_STRING").split("&") if self.environ.get("QUERY_STRING") else [] for q in querys: if len(q)>0: b = q.split("=") get.update({b[0]:b[1]}) request.GET = get cookies = self.environ.get("HTTP_COOKIE").split("&") if self.environ.get("HTTP_COOKIE") else [] for c in cookies: if len(c)>0: d = c.split("=") cookie.update({d[0]:d[1]}) request.cookie = cookie request.path = self.environ['PATH_INFO'] request.method = self.method return request ##response class Response(object): def __init__(self, start_response): self.request = request self.start_response = start_response def _header(self): header = [("Content-type","%s; charset=%s" % (request.content_type, config['charset']))] if hasattr(request, 'content_disposition'): header.append(("Content-disposition", "attachment;filename=" + request.content_disposition)) return header def run(self): self.start_response(request.status, self._header()) _local = threading.local() class Stack(dict): def __getattr__(self, key): if key in self: return self[key] def __setattr__(self, key, value): if value != None: self[key] = value def __delattr__(self, key): if key in self: del self[key] class Local_stack(object): def __init__(self, name): self._local = setattr(_local, name, Stack()) def __getattr__(self, name): if hasattr(_local, name): return getattr(_local, name) def __setattr__(self, name, value): setattr(_local, name, value) def __delattr__(self, name): if hasattr(_local, name): delattr(_local, name) request = Local_stack('request') class Local_decorate(object): def __init__(self): self.name = 'Local_dcorate' def run(self, func): call = func.callback(*request.args) if len(request.args) > 0 else func.callback() if func.type == 'text/html': request.content_type = 'text/html' elif func.type == 'json': request.content_type = 'application/json' call = self._json(call) elif func.type == 'xml': request.content_type = 'text/xml' call = self._xml(call) self._befor_response() return call def _json(self, j): try: return json.dumps(j) except: traceback.print_exc() def _xml(self, x): try: parseString(x) return x except: traceback.print_exc() def _static(self): if request.path: file = os.path.abspath(os.path.join(os.path.abspath(config["base_path"]) + os.sep,request.path.strip("/\\"))) if os.path.isfile(file): return open(file, 'rb') else: request.status = '404 Not Found' else: raise 'no request path, please check it request.path' def _befor_response(self): Response(request.start_response).run() decorate = Local_decorate() ##templete class MakoTemplete(object): def __init__(self): from mako.template import Template from mako.lookup import TemplateLookup self.mylookup = TemplateLookup(directories=[config['template']], output_encoding=config['charset'], input_encoding=config['charset'], encoding_errors='replace', default_filters=['decode.%s' % (config['charset'].replace('-', "_"))] ) def render_to_response(self, templatename, kwargs): mytemplate = self.mylookup.get_template(templatename) return mytemplate.render(**kwargs) if kwargs else mytemplate.render() def render_to_response(templatename, kwargs = None): if config['template_module'] == 'mako': return MakoTemplete().render_to_response(templatename, kwargs) ##route class Router(object): def __init__(self): self.routers = {} def _rule(self, path): for key, router in self.routers.iteritems(): regex = re.search(router.path, path) if regex: request.args = regex.groups() request.status = '200 OK' return decorate.run(router) else: request.status = '404 Not Found' def push(self, path, callback, method, type): path = ''.join(['^', path.replace('<int>', '(\d+)').replace('<str>', '(\w+)').replace('<*>', '(\S)'), '$']) if not self.routers.get(path): _stack = Stack() _stack.path, _stack.callback, _stack.method, _stack.type = path, callback, method, type self.routers.update({path:_stack}) def get(self): return self._rule(request.path) def all(self): return self.routers router = Router() #######main########### class Flying(object): def __init__(self): self.config = {} self.request = None self.response = None def route(self, path, method = 'GET', type = 'text/html', callback=None, *args): if callable(path): path, callback = None, path def decorator(callback): router.push(path, callback, method, type) return callback return decorator(callback) if callback else decorator def run(self, *args, **kwargs): config = self.config = kwargs WSGIRefServer(*args, **kwargs).run() def wsgi(self, environ, start_response): Requst(environ).run() return router.get() def __call__(self, environ, start_response): request.environ = environ request.start_response = start_response return self.wsgi(environ, start_response) def make_default_app_wrapper(name): @functools.wraps(getattr(Flying, name)) def wrapper(*args, **kwargs): return getattr(Flying(), name)(*args, **kwargs) return wrapper route = make_default_app_wrapper('route') @route('/public/*') def public(): return decorate._static() ##server class WSGIRefServer(object): def __init__(self, host='127.0.0.1', port=8080, **option): self.option = option self.host = host self.port = int(port) def __repr__(self): args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.option.items()]) return "%s(%s)" % (self.__class__.__name__, args) def run(self, app): from wsgiref.simple_server import make_server, WSGIRequestHandler srv = make_server(self.host, self.port, app) srv.serve_forever()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from flying import * app = Flying() @route('/') def index(): return render_to_response('hello.html',{'hello':'欢迎'}) @route('/json', type = 'json') def json(): return dict(a = 123) @route('/xml', type = 'xml') def xml(): return "<myxml>Some data<empty/> some more data</myxml>" @route('/a/<int>/<str>/a') def test2(id, page): return "%s_%s" % (id, page) if __name__ == "__main__": mWSGIRefServer = WSGIRefServer() mWSGIRefServer.run(app)
Python
#!/usr/bin/env python ############################################################################### # # MODULE: m.fuzzy.sensitivity # AUTHOR: Thomas Leppelt # PURPOSE: Compute sensitivity anaylsis for fuzzy models in ranges of given # raster cell maps or by direct input and plotting the output in R. # ############################################################################### #%module #% description: Compute sensitivity anaylsis for fuzzy models. #% keywords: Miscellaneous #% keywords: Fuzzy model,TAG2E, sensitivity analysis #%end #%option G_OPT_F_INPUT #% description: List of input raster maps representing driving parameters of a fuzzy model. #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Basename of output vector map containing model results of sensitivity analysis. #% required : yes #% guisection: Files & format #%end #%option #% key: parameter #% type : string #% description: List of XML fuzzy inference parameter file names. #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: basename #% type : string #% description: Basename of vector files for calculated fuzzy models. #% required : yes #% multiple: no #% guisection: Files & format #%end #%option #% key: file #% type : string #% description: Text file containing XML fuzzy inference parameter file names as list. #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: driver #% type : string #% description: Name of the model drivers in the order of the raster map list that are used also in the XML fuzzy inference scheme file. #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option #% key: breaks #% type : integer #% description: Number of equally sized breaks per parameter. #% required : yes #% multiple: no #% answer: 10 #% guisection: Files & format #%end #%flag #% key: p #% description: Plot the sensitivity analysis result as 2D/3D vector graphic in R (Packages: scatterplot3d & SDMTools are required). #%end import grass.script as grass import grass.pygrass.modules as pygrass from grass.pygrass.vector import VectorTopo from grass.pygrass.vector.geometry import Point from grass.pygrass.vector.table import Link import itertools as it from subprocess import PIPE import numpy as np import os import sys import csv import subprocess import tempfile def Get_Parameter_Range(parameters, drivers, breaks = 10): """!This function calculates parameter ranges from given input raster cell maps for given driving parameter list. @param parameter List of raster cell maps representing driving parameters of a fuzzy model. @param drivers List of driver names in same order as given corresponding raster maps. @param breaks Number of steps created in between ranges of parameters. @return Dictionary with parameter ranges. """ # Check if parameter and drivers have same length. if len(parameters) != len(drivers): grass.fatal("Length of parameters (%s) and fuzzy model drivers (%s) does not match." %(parameters, drivers)) # Check driving parameter list. if isinstance(parameters, list) == False: grass.fatal("Expected parameter list object. Got: %s." %(parameters)) # Build pyGrass module for r.info. mod_rinfo = pygrass.Module('r.info') mod_rinfo.flags["r"].value = True para_dict = {} range_dict = {} # Number of generated values. n = breaks # Loop over parameter list and build dictionary with range values of parameter. for i in range(len(parameters)): para = parameters[i] mod_rinfo(map = str(para), stdout_= PIPE) para_range = mod_rinfo.outputs.stdout.strip().split('\n') range_dict[drivers[i]] = [float(para_range[0][4:]),float(para_range[1][4:])] # Create parameter lists with n steps in given ranges. for i in range(len(parameters)): para = drivers[i] para_min = range_dict[para][0] para_max = range_dict[para][1] para_range = para_max - para_min step = para_range / n para_vect = np.arange(para_min, para_max, step) para_list = list(para_vect) + [para_max] para_dict[para] = para_list # Return dictionary with range values for given parameters. return(para_dict) ############################################################################### def Run_Fuzzy_Model(name, model_list, drivers, para_ranges, basename): """!This function generates input data and calculates fuzzy models for given input XML fuzzy model files. @param name Name of output vector file with data in given ranges. @param model_list List of fuzzy model XML representations. @param drivers List of driver names that are used in the fuzzy model XML representation. @param para_ranges Dictionary with parameter ranges. @param basename Basename string to name calculated fuzzy models. . @return Dictionary with parameter ranges. """ # Build pyGrass module for fuzzy model application. mod_vfuzzy = pygrass.Module('v.fuzzy.model') mod_vfuzzy.flags.overwrite = grass.overwrite() # Fuzzy model sensitivity analysis. # Create input vector files. model_data = VectorTopo(name) model_data.overwrite = grass.overwrite() # Generate attribute data. data_product = [x for x in apply(it.product, para_ranges.values())] # Set the layer name. model_data.layer = 1 # Create a Link object. link = Link(layer=model_data.layer, name=model_data.name, table=model_data.name, key='cat', database='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', driver='sqlite') # Define columns and create column list. cols = [(u'cat', 'INTEGER PRIMARY KEY')] for col in para_ranges.keys(): cols.append((u'%s'%(col), 'DOUBLE PRECISION')) cols.append((u'result_mean', 'DOUBLE PRECISION')) # Apply fuzzy model on generated data. count = 0 result_all = [] for xml in model_list: out_name = basename + '_' + str(count) # Calculate fuzzy model values. mod_vfuzzy(input = name, parameter = xml, output = out_name) # Read result values from vector table. result = VectorTopo(out_name) #result.build() result.open('r') link = result.dblinks[0] conn = link.connection() cur = conn.cursor() cur.execute("SELECT result FROM %s" % result.name) print("SELECT result FROM %s" % result.name) result_vec = cur.fetchall() # Store results in table. if count == 0: result_all = result_vec else: result_all = [x+(y) for x,y in zip(result_all, result_vec)] cur.close() conn.close() result.close() count= count + 1 result_mean = [np.mean(i) for i in result_all] result_table = [x+(y,) for x,y in zip(data_product, result_mean)] # Open vector object in write mode. model_data.open('w', tab_cols=cols) # Add link to vector map. model_data.dblinks.add(link) # Write vector poitns and parameter data to table. for i in range(len(data_product)): point_i = Point(i, i) p_attr = data_product[i] model_data.write(point_i, (str(p_attr[0]),str(p_attr[1]),str(p_attr[2]), str(result_mean[i]), )) # Save the changes and close the map. model_data.table.conn.commit() model_data.close() return(result_table) def Plot_Fuzzy_Result(name, result, drivers): """!This function generates a csv file of the sensitivity analysis result in temporary directory and creates a 2D/3D plot of the results. @param name Name of the export csv file for input data. @param result Name of list containing results. @param drivers List of drivers for the fuzzy model. . @return File containing plotted results. """ csv_dir = tempfile.gettempdir() csv_name = str(name + '.csv') # Export result table as csv. o = open(str(csv_dir + '/' + csv_name), "w+") w = csv.writer(o) cols = [] for col in drivers: cols.append(col) cols.append('result_mean') w.writerow(cols) for row in result: w.writerow(row) print("Exporting " + str(csv_dir + '/' + csv_name)) # Close csv file. o.close() # Execute R-script. RScript = """ # Perform sensitivity analysis of fuzzy models for different land use categories. require(scatterplot3d) require(SDMTools) add_plots = FALSE # Export as pdf file. exportpdf <- paste("outputname", "_", Sys.Date(), '.pdf', sep = '') pdf(file = exportpdf) ############################################################################### # Fuzzy model sensitivity. # Model directory and file name. model_sensitive_dir = "temp_dir" model_sensitive_name = "fuzzy_result" # Import model sensitivity analysis data. modeldata <- read.csv(paste(model_sensitive_dir,'/',model_sensitive_name, sep='')) # Check number of columns. modellen <- length(modeldata) # Transform fluxes. modeldata$result_mean <- exp(modeldata$result_mean) - 0.5 # 3D plot. # Create a function to generate a continuous color palette. colPal <- colorRampPalette(c('yellow', 'green', 'cyan', 'blue', 'violet', 'red')) # This adds a column of color values based on the emission values. modeldata$col <- colPal(200)[as.numeric(cut(modeldata$result_mean,breaks = 200))] modeldata$cex <- as.numeric(cut(modeldata$result_mean,breaks = 10))/2 xlim <- range(modeldata[,1]) ylim <- range(modeldata[,2]) zlim <- range(modeldata[,3]) scatterplot3d(x = modeldata[,1], y = modeldata[,2], z = modeldata[,3], color = modeldata$col, cex.symbols = modeldata$cex, pch = 16, xlim=xlim, ylim=ylim, zlim=zlim) pnts = (cbind(x =c(max(modeldata[,1]),max(modeldata[,1]) + 0.5,max(modeldata[,1]) + 0.5,max(modeldata[,1])), y =c(max(modeldata[,3]) + 7.5,max(modeldata[,3]) + 5.5,max(modeldata[,3]) + 5.5,max(modeldata[,3]) + 2))) legend.gradient(pnts,cols=colPal(30),limits=round(range(modeldata$result_mean),2), title='Flux') if (add_plots) { # Extract high fluxes. modeldata_high <- subset(modeldata, result_mean > 0.8) with(modeldata_high,scatterplot3d(ph,rr_annual,wt, color = col, cex.symbols = cex, pch = 16, xlim=xlim, ylim=ylim, zlim=zlim)) modeldata_low <- subset(modeldata, result_mean <= 0.8) with(modeldata_low,scatterplot3d(ph,rr_annual,wt, color = col, cex.symbols = cex, pch = 16, xlim=xlim, ylim=ylim, zlim=zlim)) } print("Plotting Result") ############################################################################### """ RScript = RScript.replace("outputname", name) RScript = RScript.replace("temp_dir", csv_dir) RScript = RScript.replace("fuzzy_result", csv_name) inputlist = ["R", "--vanilla"] proc = subprocess.Popen(args=inputlist, stdin=subprocess.PIPE) proc.stdin.write(RScript) proc.communicate() def main(): input = options['input'] output = options['output'] parameter = options['parameter'] basename = options['basename'] filename = options['file'] driver = options['driver'] breaks = options['breaks'] plot = flags['p'] # Check if parameters and file name are both input. if parameter and filename: grass.fatal("Expected either parameter list or file with list of parameters. Got both.") # Convert inputs into correct format. input_list = input.split(',') driver_list = driver.split(',') breaks = float(breaks) if parameter: parameter_list = parameter.split(',') elif filename: parameter_list = [] with open(filename, 'rb') as xmlfile: xmlreader = csv.reader(xmlfile, delimiter=',') for row in xmlreader: parameter_list = parameter_list + (row) # Calculate parameter ranges. para_dict = Get_Parameter_Range(input_list, driver_list, breaks) # Calculate fuzzy models and create output vector file. result_list = Run_Fuzzy_Model(output, parameter_list, driver_list, para_dict, basename) # Plotting the results in R. if plot: Plot_Fuzzy_Result(output, result_list, driver_list) if __name__ == "__main__": if len(sys.argv) == 2 and sys.argv[1] == 'doctest': import doctest doctest.testmod() exit() options, flags = grass.parser() main()
Python
#!/usr/bin/env python ############################################################################### # # MODULE: m.fuzzy.sensitivity # AUTHOR: Thomas Leppelt # PURPOSE: Compute sensitivity anaylsis for fuzzy models in ranges of given # raster cell maps or by direct input and plotting the output in R. # ############################################################################### #%module #% description: Compute sensitivity anaylsis for fuzzy models. #% keywords: Miscellaneous #% keywords: Fuzzy model,TAG2E, sensitivity analysis #%end #%option G_OPT_F_INPUT #% description: List of input raster maps representing driving parameters of a fuzzy model. #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Basename of output vector map containing model results of sensitivity analysis. #% required : yes #% guisection: Files & format #%end #%option #% key: parameter #% type : string #% description: List of XML fuzzy inference parameter file names. #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: basename #% type : string #% description: Basename of vector files for calculated fuzzy models. #% required : yes #% multiple: no #% guisection: Files & format #%end #%option #% key: file #% type : string #% description: Text file containing XML fuzzy inference parameter file names as list. #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: driver #% type : string #% description: Name of the model drivers in the order of the raster map list that are used also in the XML fuzzy inference scheme file. #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option #% key: breaks #% type : integer #% description: Number of equally sized breaks per parameter. #% required : yes #% multiple: no #% answer: 10 #% guisection: Files & format #%end #%flag #% key: p #% description: Plot the sensitivity analysis result as 2D/3D vector graphic in R (Packages: scatterplot3d & SDMTools are required). #%end import grass.script as grass import grass.pygrass.modules as pygrass from grass.pygrass.vector import VectorTopo from grass.pygrass.vector.geometry import Point from grass.pygrass.vector.table import Link import itertools as it from subprocess import PIPE import numpy as np import os import sys import csv import subprocess import tempfile def Get_Parameter_Range(parameters, drivers, breaks = 10): """!This function calculates parameter ranges from given input raster cell maps for given driving parameter list. @param parameter List of raster cell maps representing driving parameters of a fuzzy model. @param drivers List of driver names in same order as given corresponding raster maps. @param breaks Number of steps created in between ranges of parameters. @return Dictionary with parameter ranges. """ # Check if parameter and drivers have same length. if len(parameters) != len(drivers): grass.fatal("Length of parameters (%s) and fuzzy model drivers (%s) does not match." %(parameters, drivers)) # Check driving parameter list. if isinstance(parameters, list) == False: grass.fatal("Expected parameter list object. Got: %s." %(parameters)) # Build pyGrass module for r.info. mod_rinfo = pygrass.Module('r.info') mod_rinfo.flags["r"].value = True para_dict = {} range_dict = {} # Number of generated values. n = breaks # Loop over parameter list and build dictionary with range values of parameter. for i in range(len(parameters)): para = parameters[i] mod_rinfo(map = str(para), stdout_= PIPE) para_range = mod_rinfo.outputs.stdout.strip().split('\n') range_dict[drivers[i]] = [float(para_range[0][4:]),float(para_range[1][4:])] # Create parameter lists with n steps in given ranges. for i in range(len(parameters)): para = drivers[i] para_min = range_dict[para][0] para_max = range_dict[para][1] para_range = para_max - para_min step = para_range / n para_vect = np.arange(para_min, para_max, step) para_list = list(para_vect) + [para_max] para_dict[para] = para_list # Return dictionary with range values for given parameters. return(para_dict) ############################################################################### def Run_Fuzzy_Model(name, model_list, drivers, para_ranges, basename): """!This function generates input data and calculates fuzzy models for given input XML fuzzy model files. @param name Name of output vector file with data in given ranges. @param model_list List of fuzzy model XML representations. @param drivers List of driver names that are used in the fuzzy model XML representation. @param para_ranges Dictionary with parameter ranges. @param basename Basename string to name calculated fuzzy models. . @return Dictionary with parameter ranges. """ # Build pyGrass module for fuzzy model application. mod_vfuzzy = pygrass.Module('v.fuzzy.model') mod_vfuzzy.flags.overwrite = grass.overwrite() # Fuzzy model sensitivity analysis. # Create input vector files. model_data = VectorTopo(name) model_data.overwrite = grass.overwrite() # Generate attribute data. data_product = [x for x in apply(it.product, para_ranges.values())] # Set the layer name. model_data.layer = 1 # Create a Link object. link = Link(layer=model_data.layer, name=model_data.name, table=model_data.name, key='cat', database='$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', driver='sqlite') # Define columns and create column list. cols = [(u'cat', 'INTEGER PRIMARY KEY')] for col in para_ranges.keys(): cols.append((u'%s'%(col), 'DOUBLE PRECISION')) cols.append((u'result_mean', 'DOUBLE PRECISION')) # Apply fuzzy model on generated data. count = 0 result_all = [] for xml in model_list: out_name = basename + '_' + str(count) # Calculate fuzzy model values. mod_vfuzzy(input = name, parameter = xml, output = out_name) # Read result values from vector table. result = VectorTopo(out_name) #result.build() result.open('r') link = result.dblinks[0] conn = link.connection() cur = conn.cursor() cur.execute("SELECT result FROM %s" % result.name) print("SELECT result FROM %s" % result.name) result_vec = cur.fetchall() # Store results in table. if count == 0: result_all = result_vec else: result_all = [x+(y) for x,y in zip(result_all, result_vec)] cur.close() conn.close() result.close() count= count + 1 result_mean = [np.mean(i) for i in result_all] result_table = [x+(y,) for x,y in zip(data_product, result_mean)] # Open vector object in write mode. model_data.open('w', tab_cols=cols) # Add link to vector map. model_data.dblinks.add(link) # Write vector poitns and parameter data to table. for i in range(len(data_product)): point_i = Point(i, i) p_attr = data_product[i] model_data.write(point_i, (str(p_attr[0]),str(p_attr[1]),str(p_attr[2]), str(result_mean[i]), )) # Save the changes and close the map. model_data.table.conn.commit() model_data.close() return(result_table) def Plot_Fuzzy_Result(name, result, drivers): """!This function generates a csv file of the sensitivity analysis result in temporary directory and creates a 2D/3D plot of the results. @param name Name of the export csv file for input data. @param result Name of list containing results. @param drivers List of drivers for the fuzzy model. . @return File containing plotted results. """ csv_dir = tempfile.gettempdir() csv_name = str(name + '.csv') # Export result table as csv. o = open(str(csv_dir + '/' + csv_name), "w+") w = csv.writer(o) cols = [] for col in drivers: cols.append(col) cols.append('result_mean') w.writerow(cols) for row in result: w.writerow(row) print("Exporting " + str(csv_dir + '/' + csv_name)) # Close csv file. o.close() # Execute R-script. RScript = """ # Perform sensitivity analysis of fuzzy models for different land use categories. require(scatterplot3d) require(SDMTools) add_plots = FALSE # Export as pdf file. exportpdf <- paste("outputname", "_", Sys.Date(), '.pdf', sep = '') pdf(file = exportpdf) ############################################################################### # Fuzzy model sensitivity. # Model directory and file name. model_sensitive_dir = "temp_dir" model_sensitive_name = "fuzzy_result" # Import model sensitivity analysis data. modeldata <- read.csv(paste(model_sensitive_dir,'/',model_sensitive_name, sep='')) # Check number of columns. modellen <- length(modeldata) # Transform fluxes. modeldata$result_mean <- exp(modeldata$result_mean) - 0.5 # 3D plot. # Create a function to generate a continuous color palette. colPal <- colorRampPalette(c('yellow', 'green', 'cyan', 'blue', 'violet', 'red')) # This adds a column of color values based on the emission values. modeldata$col <- colPal(200)[as.numeric(cut(modeldata$result_mean,breaks = 200))] modeldata$cex <- as.numeric(cut(modeldata$result_mean,breaks = 10))/2 xlim <- range(modeldata[,1]) ylim <- range(modeldata[,2]) zlim <- range(modeldata[,3]) scatterplot3d(x = modeldata[,1], y = modeldata[,2], z = modeldata[,3], color = modeldata$col, cex.symbols = modeldata$cex, pch = 16, xlim=xlim, ylim=ylim, zlim=zlim) pnts = (cbind(x =c(max(modeldata[,1]),max(modeldata[,1]) + 0.5,max(modeldata[,1]) + 0.5,max(modeldata[,1])), y =c(max(modeldata[,3]) + 7.5,max(modeldata[,3]) + 5.5,max(modeldata[,3]) + 5.5,max(modeldata[,3]) + 2))) legend.gradient(pnts,cols=colPal(30),limits=round(range(modeldata$result_mean),2), title='Flux') if (add_plots) { # Extract high fluxes. modeldata_high <- subset(modeldata, result_mean > 0.8) with(modeldata_high,scatterplot3d(ph,rr_annual,wt, color = col, cex.symbols = cex, pch = 16, xlim=xlim, ylim=ylim, zlim=zlim)) modeldata_low <- subset(modeldata, result_mean <= 0.8) with(modeldata_low,scatterplot3d(ph,rr_annual,wt, color = col, cex.symbols = cex, pch = 16, xlim=xlim, ylim=ylim, zlim=zlim)) } print("Plotting Result") ############################################################################### """ RScript = RScript.replace("outputname", name) RScript = RScript.replace("temp_dir", csv_dir) RScript = RScript.replace("fuzzy_result", csv_name) inputlist = ["R", "--vanilla"] proc = subprocess.Popen(args=inputlist, stdin=subprocess.PIPE) proc.stdin.write(RScript) proc.communicate() def main(): input = options['input'] output = options['output'] parameter = options['parameter'] basename = options['basename'] filename = options['file'] driver = options['driver'] breaks = options['breaks'] plot = flags['p'] # Check if parameters and file name are both input. if parameter and filename: grass.fatal("Expected either parameter list or file with list of parameters. Got both.") # Convert inputs into correct format. input_list = input.split(',') driver_list = driver.split(',') breaks = float(breaks) if parameter: parameter_list = parameter.split(',') elif filename: parameter_list = [] with open(filename, 'rb') as xmlfile: xmlreader = csv.reader(xmlfile, delimiter=',') for row in xmlreader: parameter_list = parameter_list + (row) # Calculate parameter ranges. para_dict = Get_Parameter_Range(input_list, driver_list, breaks) # Calculate fuzzy models and create output vector file. result_list = Run_Fuzzy_Model(output, parameter_list, driver_list, para_dict, basename) # Plotting the results in R. if plot: Plot_Fuzzy_Result(output, result_list, driver_list) if __name__ == "__main__": if len(sys.argv) == 2 and sys.argv[1] == 'doctest': import doctest doctest.testmod() exit() options, flags = grass.parser() main()
Python
#!/usr/bin/env python ############################################################################ # # MODULE: m.ecad # AUTHOR: Thomas Leppelt # PURPOSE: Import, registration,aggregation and observation of ECA&D climate data. # ############################################################################# #%module #% description: Import, registration and observation of ECA&D climate data. #% keywords: Miscellaneous #% keywords: Climate data,ECA&D #%end #%option G_OPT_F_INPUT #% description: Name of input vector file for observation #% required : no #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Name of output vector file, merging vector map and observed ECAD climate data #% required : no #% guisection: Files & format #%end #%option #% key: aggregation #% type : string #% description: Select climate data granularity for aggregation #%options:monthly,seasonal,yearly #% required : no #% multiple: yes #% answer: seasonal,yearly #% guisection: Files & format #%end #%option #% key: startcolumn #% type : string #% description: Name of the start date column in input file (date format: 2011-01-01) #% required : no #% multiple: no #% answer: start_date #% guisection: Files & format #%end #%option #% key: endcolumn #% type : string #% description: Name of the end date column in input file (date format: 2011-12-31) #% required : no #% multiple: no #% answer: end_date #% guisection: Files & format #%end #%option #% key: location #% type : string #% description: Name of location for climate analysis (compatible Lat/Lon projection required) #% required : no #% multiple: no #% answer: $LOCATION_NAME #% guisection: Files & format #%end #%option #% key: observation #% type : string #% description: Select climate data granularity for observation #%options:monthly,seasonal,preseasonal,yearly,preyearly,period #% required : no #% multiple: yes #% answer: seasonal,yearly #% guisection: Files & format #%end #%option #% key: factor #% type : string #% description: Select climate factors, precipitation(rr), mean(tg)-, maximal(tx)- or minimal(tn) temperature #%options:tg,tn,tx,rr #% required : no #% multiple: yes #% answer: tg,tn,tx,rr #% guisection: Files & format #%end #%flag #% key: i #% description: Download, import and temporal reference the ECA&D datasets into given lat/lon location #% guisection: Projections #%end #%flag #% key: o #% description: Observe ECA&D dataset in given vector location #% guisection: Projections #%end import sys import os import threading import fnmatch import grass.script as grass from subprocess import call import datetime import collections climatefactorunitconverter = {'tg' : '100.0','tn' : '100.0','tx' : '100.0','rr' : '10.0'} calc_location = grass.gisenv()["LOCATION_NAME"] calc_mapset = grass.gisenv()["MAPSET"] # Download,import and temporal reference the ECA&D datasets def ecadimport(aggregation,location,factorlist): climatefactorlist = factorlist.split(',') aggregationtype = {'monthly' : '1 months','seasonal' : '3 months','yearly' : '1 years'} aggregationmethode = {'tg' : 'average','tn' : 'average','tx' : 'average', 'rr' : 'sum'} try: # Switch to given location name. grass.run_command('g.mapset', mapset = 'PERMANENT', location = location) except: # Create location for ECAD data processing. grass.run_command('g.proj', flags = 'c', epsg = 4326, location = location) for climatefactorname in climatefactorlist: try: # Download, unzip and import climate factors as grid ECA&D dataset in actual directory call(['wget', '-c', '-t', '5',str('http://eca.knmi.nl/download/ensembles/data/Grid_0.25deg_reg/'+ climatefactorname + '_0.25deg_reg_v9.0.nc.gz')]) call(['gunzip','-f', str(climatefactorname + '_0.25deg_reg_v9.0.nc.gz')]) # Set region to 0.25 degree resolution. grass.run_command('g.region', nsres = 0.25, ewres = 0.25) # Import climate data grass.run_command('r.in.gdal', input=str(climatefactorname + '_0.25deg_reg_v9.0.nc'), output=str('ecad_' + climatefactorname), flags='o', overwrite = grass.overwrite) # Create txt-files of containing climate raster maps maplist = open(str(climatefactorname + '_map_list.txt'), "w") mapliststring = (grass.read_command('g.list', type='rast',flags='f').replace(' ','').split()) del mapliststring[0:1+1] mapliststring = fnmatch.filter(mapliststring,str('ecad_' + climatefactorname + '*')) mapliststring = sorted(mapliststring,key= lambda a: float(a.split('.')[1])) print(mapliststring) for map_i in mapliststring: grass.run_command('r.mapcalc', expression = "%s = %s / %s" %(map_i, map_i, climatefactorunitconverter[climatefactorname]), overwrite = grass.overwrite) mapliststring = '\n'.join(mapliststring) maplist.write(mapliststring) maplist.close() # Create and register new space time raster data sets using txt-files for daily raster sets grass.run_command('t.create',type='strds', output=str(climatefactorname + '_1950_2012_daily'), temporal='absolute', title=str("European " + climatefactorname + " 1950-2012"), description=str("The european daily " + climatefactorname + " 1950 - 2012 from ECA&D"), overwrite = grass.overwrite) grass.run_command('t.register', flags='i', input=str(climatefactorname + '_1950_2012_daily'), file=str(climatefactorname + '_map_list.txt'), start='1950-01-01', increment="1 days") #Climate data aggregation to monthly, seasonal and yearly data sets for aggregationlevel in aggregation.split(','): wherestatement = {'monthly' : str("start_time > '1950-01-01'"), 'seasonal' : str("start_time >= '1950-03-01'"), 'yearly' : str("start_time > '1950-01-01'")} grass.run_command('t.rast.aggregate', input = str(climatefactorname + '_1950_2012_daily'), output = str(climatefactorname + '_1950_2012_' + aggregationlevel), method = aggregationmethode[climatefactorname], base = str(climatefactorname + '_' + aggregationlevel), granularity = aggregationtype[aggregationlevel], overwrite = grass.overwrite, where = wherestatement[aggregationlevel]) #Remove downloaded file from file system try: call(['rm', str(climatefactorname + '_0.25deg_reg_v9.0.nc')]) except: print("# ERROR: while deleting " + str(climatefactorname) + "_0.25deg_reg_v9.0.nc #") except: print("ERROR: while processing " + str(climatefactorname) + "_0.25deg_reg_v9.0.nc.gz ") sys.exit(0) return() def ecadobserve_new(input, output, location, startcolumn, endcolumn, observation, factorlist): climatefactorlist = factorlist.split(',') aggregationmethode = {'tg' : 'average','tn' : 'average','tx' : 'average', 'rr' : 'sum'} #Switch to ECAD location if calc_location != location: grass.run_command('g.mapset', mapset = 'PERMANENT', location = location) oblist = observation.split(',') cllist = factorlist.split(',') #Split vector input by date inputtimelist = grass.read_command('v.db.select', map = input, columns = str(startcolumn + ',' + endcolumn), flags = 'c') inputtimelist = inputtimelist.rstrip('\n').split('\n') print(inputtimelist) for clfactor in cllist: print(clfactor) for oblevel in oblist: print(oblevel) #grass.run_command('t.vect.observe.strds', input = input, # strds = str(clfactor + '_1950_2012_' + oblevel), # output = str(input + '_' + clfactor + '_' + oblevel), # vector_output = str(input + '_' + clfactor + '_' + oblevel), # col = str(clfactor + '_' + oblevel), # overwrite = grass.overwrite()) count = 1 for time in inputtimelist: start, end = time.split('|') start_str = str(start + ' 00:00:00') end_str = str(end + ' 00:00:00') time_str = str("start_time = '" + start_str + "'") print(time_str) grass.run_command('t.vect.db.select', col = str(clfactor + '_' + oblevel), input = str(input + '_' + clfactor + '_' + oblevel), t_where = time_str, where = str("cat = " + str(count))) count = count + 1 return() def ecadobserve(input, output, location, startcolumn = "start_date", endcolumn = "end_date", observation = "seasonal,yearly", factorlist = "tg,tn,tx,rr"): climatefactorlist = factorlist.split(',') aggregationmethode = {'tg' : 'average','tn' : 'average','tx' : 'average', 'rr' : 'sum'} #Switch to ECAD location grass.run_command('g.mapset', mapset = 'PERMANENT', location = location) #Create space time vector dataset for vector input grass.run_command('t.create', type = 'stvds', output = input, title = 'Vector input for climate analysis', description = 'Vector input for climate analysis',overwrite = grass.overwrite) #Split vector input by date inputstartlist = grass.read_command('v.db.select', map = input, columns = startcolumn, flags = 'c') inputstartlist = inputstartlist.rstrip('\n').split('\n') inputendlist = grass.read_command('v.db.select', map = input, columns = endcolumn, flags = 'c') inputendlist = inputendlist.rstrip('\n').split('\n') inputmergelist = zip(inputstartlist,inputendlist) inputmergelist = collections.OrderedDict.fromkeys(inputmergelist).keys() inputfilelist =[] nextract=0 for starti,endi in inputmergelist: grass.run_command('v.extract', input = input, where = str(startcolumn + " = '" + starti + "' AND " + endcolumn + " = '" + endi + "'"), output = str(input + "_" + str(nextract)), overwrite = grass.overwrite) inputfilelist.append(str(input + "_" + str(nextract))) nextract+=1 inputmaplist = open(str(input + '_map_list.txt'), "w") for iextract in range(0,nextract): registerinputline = str(inputfilelist[iextract] +'|' + '|'.join(inputmergelist[iextract]) + '\n') inputmaplist.writelines(registerinputline) inputmaplist.close() #Register vector data in space time vector dataset grass.run_command('t.register', input = input, type = 'vect', file = str(input + '_map_list.txt'), sep = '|', flags='i') #create maplist for previous year formatlist = [] formatlist[1:len(inputstartlist)] = ["%Y-%m-%d"] * len(inputstartlist) inputstartdatelist = map(datetime.datetime.strptime, inputstartlist, formatlist) for dateelement in range(0,len(inputstartdatelist)): inputstartdatelist[dateelement] = inputstartdatelist[dateelement].replace( year = inputstartdatelist[dateelement].year - 1) inputstartdatelist[dateelement] = datetime.datetime.strftime(inputstartdatelist[dateelement],"%Y-%m-%d") formatlist = [] formatlist[1:len(inputendlist)] = ["%Y-%m-%d"] * len(inputendlist) inputenddatelist = map(datetime.datetime.strptime, inputendlist, formatlist) for dateelement in range(0,len(inputenddatelist)): inputenddatelist[dateelement] = inputenddatelist[dateelement].replace( year = inputenddatelist[dateelement].year - 1) inputenddatelist[dateelement] = datetime.datetime.strftime(inputenddatelist[dateelement],"%Y-%m-%d") grass.run_command('t.create', type = 'stvds', output = str(input + '_previous'), title = 'Previous year vector input for climate analysis', description = 'Previous year vector input for climate analysis',overwrite = grass.overwrite) inputmergedatelist = zip(inputstartdatelist,inputenddatelist) inputmergedatelist = collections.OrderedDict.fromkeys(inputmergedatelist).keys() inputfiledatelist =[] nextract=0 for starti,endi in inputmergelist: grass.run_command('v.extract', input = input, where = str(startcolumn + " = '" + starti + "' AND " + endcolumn + " = '" + endi + "'"), output = str(input + "_previous_" + str(nextract)), overwrite = grass.overwrite) inputfiledatelist.append(str(input + "_previous_" + str(nextract))) nextract+=1 inputmapdatelist = open(str(input + '_map_list_previous.txt'), "w") for iextract in range(0,nextract): registerinputdateline = str(inputfiledatelist[iextract] +'|' + '|'.join(inputmergedatelist[iextract]) + '\n') inputmapdatelist.writelines(registerinputdateline) inputmapdatelist.close() #Register vector data in space time vector dataset for previous year grass.run_command('t.register', input = str(input + '_previous'), type = 'vect', file = str(input + '_map_list_previous.txt'), sep = '|', flags='i') for observationlevel in observation.split(','): for climatefactorname in climatefactorlist: #Observation of climatedata if observationlevel == 'seasonal': seasonstartmonth = {'spring' : "'2 months'",'summer' : "'5 months'",'autumn' : "'8 months'",'winter' : "'11 months'"} for seasonname in ['spring','summer','autumn','winter']: grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + seasonname), where = str("start_time = datetime(start_time,'start of year', " + seasonstartmonth[seasonname] + ")"), #expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + seasonname)) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + seasonname), overwrite = grass.overwrite, column = str(climatefactorname + '_' + seasonname), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_' + seasonname) if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatefactorname + '_' + seasonname + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_' + seasonname)) if observationlevel == 'preseasonal': seasonstartmonth = {'spring' : "'2 months'",'summer' : "'5 months'",'autumn' : "'8 months'",'winter' : "'11 months'"} for seasonname in ['spring','summer','autumn','winter']: grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + 'seasonal'), output = str(climatefactorname + '_1950_2012_' + seasonname), where = str("start_time = datetime(start_time,'start of year', " + seasonstartmonth[seasonname] + ")"), #expression = str(climatefactorname + '_1950_2012_' + 'seasonal' + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + seasonname)) grass.run_command('t.vect.what.strds', input = str(input + '_previous'), strds = str(climatefactorname + '_1950_2012_' + seasonname), overwrite = grass.overwrite, column = str(climatefactorname + '_pre' + seasonname), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_previous_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_pre' + seasonname) if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_previous_" + str(iextract)), columns = str(climatefactorname + '_pre' + seasonname + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_pre' + seasonname)) grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatecolumnname + ' double precision')) grass.run_command('db.execute', sql = str('UPDATE ' + input + "_" + str(iextract) + ' SET ' + climatecolumnname + '=(select ' + climatecolumnname + ' from ' + input + "_previous_" + str(iextract) + ' where ' + input + "_" + str(iextract) + '.cat=' + input + "_previous_" + str(iextract) + '.cat)')) if observationlevel == 'yearly': grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + 'annual'), #expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + 'annual')) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + 'annual'), overwrite = grass.overwrite, column = str(climatefactorname + '_annual'), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_annual') if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatefactorname + '_annual' + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_annual')) if observationlevel == 'preyearly': grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + 'yearly'), output = str(climatefactorname + '_1950_2012_' + 'annual'), #expression = str(climatefactorname + '_1950_2012_' + 'yearly' + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + 'annual')) grass.run_command('t.vect.what.strds', input = str(input + '_previous'), strds = str(climatefactorname + '_1950_2012_' + 'annual'), overwrite = grass.overwrite, column = str(climatefactorname + '_preannual'), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_previous_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_preannual') if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_previous_" + str(iextract)), columns = str(climatefactorname + '_preannual' + ' double precision')) grass.core.warning(str(input + "_previous_" + str(iextract) + ' missing value for ' + climatefactorname + '_preannual')) grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatecolumnname + ' double precision')) grass.run_command('db.execute', sql = str('UPDATE ' + input + "_" + str(iextract) + ' SET ' + climatecolumnname + '=(select ' + climatecolumnname + ' from ' + input + "_previous_" + str(iextract) + ' where ' + input + "_" + str(iextract) + '.cat=' + input + "_previous_" + str(iextract) + '.cat)')) if observationlevel == 'monthly': monthnamelist = {'january' : "'0 months'",'february' : "'1 months'",'march' : "'2 months'",'april' : "'3 months'",'may' : "'4 months'",'june' : "'5 months'",'july' : "'6 months'",'august' : "'7 months'",'september' : "'8 months'",'october' : "'9 months'",'november' : "'10 months'",'december' : "'11 months'"} for monthname in ['january','february','march','april','may','june','july','august','september','october','november','december']: grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + monthname), where = str("start_time = datetime(start_time,'start of year', " + monthnamelist[monthname] + ")"), # expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + monthname)) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + monthname), overwrite = grass.overwrite, column = str(climatefactorname + '_' + monthname), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_' + monthname) if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatefactorname + '_' + monthname + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_' + monthname)) if observationlevel == 'period': grass.run_command('t.rast.aggregate.ds', input = str(climatefactorname + '_1950_2012_daily'), output = str(climatefactorname + '_1950_2012_' + observationlevel), sample = input, type = 'stvds', method = aggregationmethode[climatefactorname], base = str(climatefactorname + '_' + observationlevel), overwrite = grass.overwrite) grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + 'periodical'), #expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + 'periodical')) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + 'periodical'), overwrite = grass.overwrite, column = str(climatefactorname + '_period')) if len(inputfilelist) != 1: grass.run_command('v.patch', input = ','.join(inputfilelist), output = output, flags = 'e', overwrite = grass.overwrite) else: grass.run_command('v.extract', input = inputfilelist, output = output, overwrite = grass.overwrite) return() def main(): input = options['input'] output = options['output'] aggregation = options['aggregation'] startcolumn = options['startcolumn'] endcolumn = options['endcolumn'] location = options['location'] observation = options['observation'] factorlist = options['factor'] ecadimpflag = flags['i'] ecadobservflag = flags['o'] if location == "$LOCATION_NAME": envdict = grass.gisenv() location = envdict["LOCATION_NAME"] if ecadimpflag: ecadimport(aggregation,location,factorlist) if ecadobservflag: ecadobserve(input,output,location,startcolumn,endcolumn,observation,factorlist) if __name__ == "__main__": options, flags = grass.parser() main()
Python
#!/usr/bin/env python ############################################################################ # # MODULE: m.ecad # AUTHOR: Thomas Leppelt # PURPOSE: Import, registration,aggregation and observation of ECA&D climate data. # ############################################################################# #%module #% description: Import, registration and observation of ECA&D climate data. #% keywords: Miscellaneous #% keywords: Climate data,ECA&D #%end #%option G_OPT_F_INPUT #% description: Name of input vector file for observation #% required : no #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Name of output vector file, merging vector map and observed ECAD climate data #% required : no #% guisection: Files & format #%end #%option #% key: aggregation #% type : string #% description: Select climate data granularity for aggregation #%options:monthly,seasonal,yearly #% required : no #% multiple: yes #% answer: seasonal,yearly #% guisection: Files & format #%end #%option #% key: startcolumn #% type : string #% description: Name of the start date column in input file (date format: 2011-01-01) #% required : no #% multiple: no #% answer: start_date #% guisection: Files & format #%end #%option #% key: endcolumn #% type : string #% description: Name of the end date column in input file (date format: 2011-12-31) #% required : no #% multiple: no #% answer: end_date #% guisection: Files & format #%end #%option #% key: location #% type : string #% description: Name of location for climate analysis (compatible Lat/Lon projection required) #% required : no #% multiple: no #% answer: $LOCATION_NAME #% guisection: Files & format #%end #%option #% key: observation #% type : string #% description: Select climate data granularity for observation #%options:monthly,seasonal,preseasonal,yearly,preyearly,period #% required : no #% multiple: yes #% answer: seasonal,yearly #% guisection: Files & format #%end #%option #% key: factor #% type : string #% description: Select climate factors, precipitation(rr), mean(tg)-, maximal(tx)- or minimal(tn) temperature #%options:tg,tn,tx,rr #% required : no #% multiple: yes #% answer: tg,tn,tx,rr #% guisection: Files & format #%end #%flag #% key: i #% description: Download, import and temporal reference the ECA&D datasets into given lat/lon location #% guisection: Projections #%end #%flag #% key: o #% description: Observe ECA&D dataset in given vector location #% guisection: Projections #%end import sys import os import threading import fnmatch import grass.script as grass from subprocess import call import datetime import collections climatefactorunitconverter = {'tg' : '100.0','tn' : '100.0','tx' : '100.0','rr' : '10.0'} calc_location = grass.gisenv()["LOCATION_NAME"] calc_mapset = grass.gisenv()["MAPSET"] # Download,import and temporal reference the ECA&D datasets def ecadimport(aggregation,location,factorlist): climatefactorlist = factorlist.split(',') aggregationtype = {'monthly' : '1 months','seasonal' : '3 months','yearly' : '1 years'} aggregationmethode = {'tg' : 'average','tn' : 'average','tx' : 'average', 'rr' : 'sum'} try: # Switch to given location name. grass.run_command('g.mapset', mapset = 'PERMANENT', location = location) except: # Create location for ECAD data processing. grass.run_command('g.proj', flags = 'c', epsg = 4326, location = location) for climatefactorname in climatefactorlist: try: # Download, unzip and import climate factors as grid ECA&D dataset in actual directory call(['wget', '-c', '-t', '5',str('http://eca.knmi.nl/download/ensembles/data/Grid_0.25deg_reg/'+ climatefactorname + '_0.25deg_reg_v9.0.nc.gz')]) call(['gunzip','-f', str(climatefactorname + '_0.25deg_reg_v9.0.nc.gz')]) # Set region to 0.25 degree resolution. grass.run_command('g.region', nsres = 0.25, ewres = 0.25) # Import climate data grass.run_command('r.in.gdal', input=str(climatefactorname + '_0.25deg_reg_v9.0.nc'), output=str('ecad_' + climatefactorname), flags='o', overwrite = grass.overwrite) # Create txt-files of containing climate raster maps maplist = open(str(climatefactorname + '_map_list.txt'), "w") mapliststring = (grass.read_command('g.list', type='rast',flags='f').replace(' ','').split()) del mapliststring[0:1+1] mapliststring = fnmatch.filter(mapliststring,str('ecad_' + climatefactorname + '*')) mapliststring = sorted(mapliststring,key= lambda a: float(a.split('.')[1])) print(mapliststring) for map_i in mapliststring: grass.run_command('r.mapcalc', expression = "%s = %s / %s" %(map_i, map_i, climatefactorunitconverter[climatefactorname]), overwrite = grass.overwrite) mapliststring = '\n'.join(mapliststring) maplist.write(mapliststring) maplist.close() # Create and register new space time raster data sets using txt-files for daily raster sets grass.run_command('t.create',type='strds', output=str(climatefactorname + '_1950_2012_daily'), temporal='absolute', title=str("European " + climatefactorname + " 1950-2012"), description=str("The european daily " + climatefactorname + " 1950 - 2012 from ECA&D"), overwrite = grass.overwrite) grass.run_command('t.register', flags='i', input=str(climatefactorname + '_1950_2012_daily'), file=str(climatefactorname + '_map_list.txt'), start='1950-01-01', increment="1 days") #Climate data aggregation to monthly, seasonal and yearly data sets for aggregationlevel in aggregation.split(','): wherestatement = {'monthly' : str("start_time > '1950-01-01'"), 'seasonal' : str("start_time >= '1950-03-01'"), 'yearly' : str("start_time > '1950-01-01'")} grass.run_command('t.rast.aggregate', input = str(climatefactorname + '_1950_2012_daily'), output = str(climatefactorname + '_1950_2012_' + aggregationlevel), method = aggregationmethode[climatefactorname], base = str(climatefactorname + '_' + aggregationlevel), granularity = aggregationtype[aggregationlevel], overwrite = grass.overwrite, where = wherestatement[aggregationlevel]) #Remove downloaded file from file system try: call(['rm', str(climatefactorname + '_0.25deg_reg_v9.0.nc')]) except: print("# ERROR: while deleting " + str(climatefactorname) + "_0.25deg_reg_v9.0.nc #") except: print("ERROR: while processing " + str(climatefactorname) + "_0.25deg_reg_v9.0.nc.gz ") sys.exit(0) return() def ecadobserve_new(input, output, location, startcolumn, endcolumn, observation, factorlist): climatefactorlist = factorlist.split(',') aggregationmethode = {'tg' : 'average','tn' : 'average','tx' : 'average', 'rr' : 'sum'} #Switch to ECAD location if calc_location != location: grass.run_command('g.mapset', mapset = 'PERMANENT', location = location) oblist = observation.split(',') cllist = factorlist.split(',') #Split vector input by date inputtimelist = grass.read_command('v.db.select', map = input, columns = str(startcolumn + ',' + endcolumn), flags = 'c') inputtimelist = inputtimelist.rstrip('\n').split('\n') print(inputtimelist) for clfactor in cllist: print(clfactor) for oblevel in oblist: print(oblevel) #grass.run_command('t.vect.observe.strds', input = input, # strds = str(clfactor + '_1950_2012_' + oblevel), # output = str(input + '_' + clfactor + '_' + oblevel), # vector_output = str(input + '_' + clfactor + '_' + oblevel), # col = str(clfactor + '_' + oblevel), # overwrite = grass.overwrite()) count = 1 for time in inputtimelist: start, end = time.split('|') start_str = str(start + ' 00:00:00') end_str = str(end + ' 00:00:00') time_str = str("start_time = '" + start_str + "'") print(time_str) grass.run_command('t.vect.db.select', col = str(clfactor + '_' + oblevel), input = str(input + '_' + clfactor + '_' + oblevel), t_where = time_str, where = str("cat = " + str(count))) count = count + 1 return() def ecadobserve(input, output, location, startcolumn = "start_date", endcolumn = "end_date", observation = "seasonal,yearly", factorlist = "tg,tn,tx,rr"): climatefactorlist = factorlist.split(',') aggregationmethode = {'tg' : 'average','tn' : 'average','tx' : 'average', 'rr' : 'sum'} #Switch to ECAD location grass.run_command('g.mapset', mapset = 'PERMANENT', location = location) #Create space time vector dataset for vector input grass.run_command('t.create', type = 'stvds', output = input, title = 'Vector input for climate analysis', description = 'Vector input for climate analysis',overwrite = grass.overwrite) #Split vector input by date inputstartlist = grass.read_command('v.db.select', map = input, columns = startcolumn, flags = 'c') inputstartlist = inputstartlist.rstrip('\n').split('\n') inputendlist = grass.read_command('v.db.select', map = input, columns = endcolumn, flags = 'c') inputendlist = inputendlist.rstrip('\n').split('\n') inputmergelist = zip(inputstartlist,inputendlist) inputmergelist = collections.OrderedDict.fromkeys(inputmergelist).keys() inputfilelist =[] nextract=0 for starti,endi in inputmergelist: grass.run_command('v.extract', input = input, where = str(startcolumn + " = '" + starti + "' AND " + endcolumn + " = '" + endi + "'"), output = str(input + "_" + str(nextract)), overwrite = grass.overwrite) inputfilelist.append(str(input + "_" + str(nextract))) nextract+=1 inputmaplist = open(str(input + '_map_list.txt'), "w") for iextract in range(0,nextract): registerinputline = str(inputfilelist[iextract] +'|' + '|'.join(inputmergelist[iextract]) + '\n') inputmaplist.writelines(registerinputline) inputmaplist.close() #Register vector data in space time vector dataset grass.run_command('t.register', input = input, type = 'vect', file = str(input + '_map_list.txt'), sep = '|', flags='i') #create maplist for previous year formatlist = [] formatlist[1:len(inputstartlist)] = ["%Y-%m-%d"] * len(inputstartlist) inputstartdatelist = map(datetime.datetime.strptime, inputstartlist, formatlist) for dateelement in range(0,len(inputstartdatelist)): inputstartdatelist[dateelement] = inputstartdatelist[dateelement].replace( year = inputstartdatelist[dateelement].year - 1) inputstartdatelist[dateelement] = datetime.datetime.strftime(inputstartdatelist[dateelement],"%Y-%m-%d") formatlist = [] formatlist[1:len(inputendlist)] = ["%Y-%m-%d"] * len(inputendlist) inputenddatelist = map(datetime.datetime.strptime, inputendlist, formatlist) for dateelement in range(0,len(inputenddatelist)): inputenddatelist[dateelement] = inputenddatelist[dateelement].replace( year = inputenddatelist[dateelement].year - 1) inputenddatelist[dateelement] = datetime.datetime.strftime(inputenddatelist[dateelement],"%Y-%m-%d") grass.run_command('t.create', type = 'stvds', output = str(input + '_previous'), title = 'Previous year vector input for climate analysis', description = 'Previous year vector input for climate analysis',overwrite = grass.overwrite) inputmergedatelist = zip(inputstartdatelist,inputenddatelist) inputmergedatelist = collections.OrderedDict.fromkeys(inputmergedatelist).keys() inputfiledatelist =[] nextract=0 for starti,endi in inputmergelist: grass.run_command('v.extract', input = input, where = str(startcolumn + " = '" + starti + "' AND " + endcolumn + " = '" + endi + "'"), output = str(input + "_previous_" + str(nextract)), overwrite = grass.overwrite) inputfiledatelist.append(str(input + "_previous_" + str(nextract))) nextract+=1 inputmapdatelist = open(str(input + '_map_list_previous.txt'), "w") for iextract in range(0,nextract): registerinputdateline = str(inputfiledatelist[iextract] +'|' + '|'.join(inputmergedatelist[iextract]) + '\n') inputmapdatelist.writelines(registerinputdateline) inputmapdatelist.close() #Register vector data in space time vector dataset for previous year grass.run_command('t.register', input = str(input + '_previous'), type = 'vect', file = str(input + '_map_list_previous.txt'), sep = '|', flags='i') for observationlevel in observation.split(','): for climatefactorname in climatefactorlist: #Observation of climatedata if observationlevel == 'seasonal': seasonstartmonth = {'spring' : "'2 months'",'summer' : "'5 months'",'autumn' : "'8 months'",'winter' : "'11 months'"} for seasonname in ['spring','summer','autumn','winter']: grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + seasonname), where = str("start_time = datetime(start_time,'start of year', " + seasonstartmonth[seasonname] + ")"), #expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + seasonname)) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + seasonname), overwrite = grass.overwrite, column = str(climatefactorname + '_' + seasonname), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_' + seasonname) if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatefactorname + '_' + seasonname + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_' + seasonname)) if observationlevel == 'preseasonal': seasonstartmonth = {'spring' : "'2 months'",'summer' : "'5 months'",'autumn' : "'8 months'",'winter' : "'11 months'"} for seasonname in ['spring','summer','autumn','winter']: grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + 'seasonal'), output = str(climatefactorname + '_1950_2012_' + seasonname), where = str("start_time = datetime(start_time,'start of year', " + seasonstartmonth[seasonname] + ")"), #expression = str(climatefactorname + '_1950_2012_' + 'seasonal' + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + seasonname)) grass.run_command('t.vect.what.strds', input = str(input + '_previous'), strds = str(climatefactorname + '_1950_2012_' + seasonname), overwrite = grass.overwrite, column = str(climatefactorname + '_pre' + seasonname), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_previous_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_pre' + seasonname) if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_previous_" + str(iextract)), columns = str(climatefactorname + '_pre' + seasonname + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_pre' + seasonname)) grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatecolumnname + ' double precision')) grass.run_command('db.execute', sql = str('UPDATE ' + input + "_" + str(iextract) + ' SET ' + climatecolumnname + '=(select ' + climatecolumnname + ' from ' + input + "_previous_" + str(iextract) + ' where ' + input + "_" + str(iextract) + '.cat=' + input + "_previous_" + str(iextract) + '.cat)')) if observationlevel == 'yearly': grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + 'annual'), #expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + 'annual')) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + 'annual'), overwrite = grass.overwrite, column = str(climatefactorname + '_annual'), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_annual') if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatefactorname + '_annual' + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_annual')) if observationlevel == 'preyearly': grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + 'yearly'), output = str(climatefactorname + '_1950_2012_' + 'annual'), #expression = str(climatefactorname + '_1950_2012_' + 'yearly' + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + 'annual')) grass.run_command('t.vect.what.strds', input = str(input + '_previous'), strds = str(climatefactorname + '_1950_2012_' + 'annual'), overwrite = grass.overwrite, column = str(climatefactorname + '_preannual'), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_previous_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_preannual') if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_previous_" + str(iextract)), columns = str(climatefactorname + '_preannual' + ' double precision')) grass.core.warning(str(input + "_previous_" + str(iextract) + ' missing value for ' + climatefactorname + '_preannual')) grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatecolumnname + ' double precision')) grass.run_command('db.execute', sql = str('UPDATE ' + input + "_" + str(iextract) + ' SET ' + climatecolumnname + '=(select ' + climatecolumnname + ' from ' + input + "_previous_" + str(iextract) + ' where ' + input + "_" + str(iextract) + '.cat=' + input + "_previous_" + str(iextract) + '.cat)')) if observationlevel == 'monthly': monthnamelist = {'january' : "'0 months'",'february' : "'1 months'",'march' : "'2 months'",'april' : "'3 months'",'may' : "'4 months'",'june' : "'5 months'",'july' : "'6 months'",'august' : "'7 months'",'september' : "'8 months'",'october' : "'9 months'",'november' : "'10 months'",'december' : "'11 months'"} for monthname in ['january','february','march','april','may','june','july','august','september','october','november','december']: grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + monthname), where = str("start_time = datetime(start_time,'start of year', " + monthnamelist[monthname] + ")"), # expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + monthname)) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + monthname), overwrite = grass.overwrite, column = str(climatefactorname + '_' + monthname), sampling='during,overlap,contain,equal') for iextract in range(0,nextract): columnlist = grass.vector_columns(str(input + "_" + str(iextract))).keys() climatecolumnname = str(climatefactorname + '_' + monthname) if climatecolumnname not in columnlist: grass.run_command('v.db.addcolumn', map = str(input + "_" + str(iextract)), columns = str(climatefactorname + '_' + monthname + ' double precision')) grass.core.warning(str(input + "_" + str(iextract) + ' missing value for ' + climatefactorname + '_' + monthname)) if observationlevel == 'period': grass.run_command('t.rast.aggregate.ds', input = str(climatefactorname + '_1950_2012_daily'), output = str(climatefactorname + '_1950_2012_' + observationlevel), sample = input, type = 'stvds', method = aggregationmethode[climatefactorname], base = str(climatefactorname + '_' + observationlevel), overwrite = grass.overwrite) grass.run_command('t.rast.extract', overwrite = grass.overwrite, input = str(climatefactorname + '_1950_2012_' + observationlevel), output = str(climatefactorname + '_1950_2012_' + 'periodical'), #expression = str(climatefactorname + '_1950_2012_' + observationlevel + '/' + climatefactorunitconverter[climatefactorname]), base = str(climatefactorname + '_1950_2012_' + 'periodical')) grass.run_command('t.vect.what.strds', input = input, strds = str(climatefactorname + '_1950_2012_' + 'periodical'), overwrite = grass.overwrite, column = str(climatefactorname + '_period')) if len(inputfilelist) != 1: grass.run_command('v.patch', input = ','.join(inputfilelist), output = output, flags = 'e', overwrite = grass.overwrite) else: grass.run_command('v.extract', input = inputfilelist, output = output, overwrite = grass.overwrite) return() def main(): input = options['input'] output = options['output'] aggregation = options['aggregation'] startcolumn = options['startcolumn'] endcolumn = options['endcolumn'] location = options['location'] observation = options['observation'] factorlist = options['factor'] ecadimpflag = flags['i'] ecadobservflag = flags['o'] if location == "$LOCATION_NAME": envdict = grass.gisenv() location = envdict["LOCATION_NAME"] if ecadimpflag: ecadimport(aggregation,location,factorlist) if ecadobservflag: ecadobserve(input,output,location,startcolumn,endcolumn,observation,factorlist) if __name__ == "__main__": options, flags = grass.parser() main()
Python
#!/usr/bin/env python ################################################################################################### # # MODULE: m.fuzzy.validation # AUTHOR: Thomas Leppelt # PURPOSE: Selection, calibration and validation of parameter combinations for fuzzy models. # ################################################################################################### #%module #% description: Selection, calibration and validation of parameter combinations for fuzzy models. #% keywords: Miscellaneous #% keywords: Fuzzy model,TAG2E #%end #%option G_OPT_F_INPUT #% description: Name of input vector map for fuzzy model input #% required : yes #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Name of output vector file #% required : no #% guisection: Files & format #%end #%option #% key: target #% type : string #% description: Select name for target variable #% required : yes #% multiple: no #% guisection: Files & format #%end #%option #% key: weightfactor #% type : string #% description: Select name for weighting variable #% required : no #% multiple: no #% guisection: Files & format #% answer: None #%end #%option #% key: splitfactor #% type : string #% description: Select factor name for dataset seperation #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: samplingfactor #% type : string #% description: The name of the column with ids for bootstrap aggregation selection #% required : no #% multiple: no #% guisection: Files & format #% answer: None #%end #%option #% key: parameters #% type : string #% description: List of driving parameters in input attribute table for selection #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option #% key: uncertainties #% type : double #% description: The uncertainty of parameters in same order to be used for monte carlo simulation #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: rulelimit #% type : double #% description: The rule limit specifies the minimum percentage of data that should be located in a single rule. #% required : no #% multiple: no #% guisection: Files & format #% answer: 20 #%end #%option #% key: ensembles #% type : integer #% description: Number of model ensembles extracted by bootstrapping #% required : no #% multiple: no #% guisection: Files & format #% answer: 50 #%end #%option #% key: iterations #% type : integer #% description: The maximum number of iterations #% required : no #% multiple: no #% guisection: Files & format #% answer: 50000 #%end #%option #% key: fuzzysets #% type : integer #% description: The number of fuzzy sets to be used for calibration for each factor: in case of 4 factors each of 2 fuzzy sets: 2,2,2,2 #% required : no #% multiple: yes #% guisection: Files & format #%end #%flag #% key: a #% description: Use all parameters in input attribute table for calibration #%end #%flag #% key: b #% description: Use boostrap aggregation (bagging) for input data selection #%end #%flag #% key: e #% description: Activate crossvalidation by given splitfactor #%end #%flag #% key: c #% description: Transform categorical variable to numerical weight factor for selection #%end #%flag #% key: w #% description: Using weight factor for calibration #%end #%flag #% key: m #% description: Activate Monte Carlo simulation for uncertainty estimation #%end import sys import os import grass.script as grass import numpy import subprocess import multiprocessing as multi import re import csv import string from vtk import * from libvtkTAG2ECommonPython import * from libvtkTAG2EFilteringPython import * from libvtkGRASSBridgeIOPython import * from libvtkGRASSBridgeCommonPython import * from libvtkGRASSBridgeRSpaceTimePython import * #from libvtkGRASSBridgeTemporalPython import * import MetaModel workers = multi.cpu_count() def ParameterXMLRange(input, weightfactor = 'None'): # Import model XML description file and create dictionary with model parameters # and their specific max and min values. fuzzyxml = open(input, 'r') fuzzylist = fuzzyxml.read() fuzzyxml.close() fuzzymodel = vtkXMLUtilities.ReadElementFromString(fuzzylist) element_number = fuzzymodel.GetNumberOfNestedElements() factor_dict = {} if weightfactor == 'None': for i in range(element_number - 1): element = fuzzymodel.GetNestedElement(i) element_name = element.GetAttribute('name') element_max = element.GetAttribute('max') element_min = element.GetAttribute('min') factor_dict[element_name] = [element_max,element_min] else: models = fuzzymodel.GetNestedElement(1) element_number = models.GetNumberOfNestedElements() for i in range(element_number - 1): element = models.GetNestedElement(i) element_name = element.GetAttribute('name') element_max = element.GetAttribute('max') element_min = element.GetAttribute('min') factor_dict[element_name] = [element_max,element_min] return(factor_dict) def ParameterComparisonFlag(index, xmldict, parameters, parameterdict): # Compute flags for validation data qualitiy. # Possibly values: # 0: At least one validation parameter is outside the model calibration # range and no missing values is detected. # 1: Validation parameters are inside the model calibration range and no # missing values are detected. # 2: At least one validation parameter is a missing values and no outliers # are detected. # 3: At least one validation parameter is a missing values and one outlier # is detected. parameter_list = parameters.split(',') flag_list = [] for para in parameter_list: max = float(xmldict[para][0]) min = float(xmldict[para][1]) values = parameterdict[index] para_index = parameter_list.index(para) value_index = float(values[para_index]) if (value_index > max or value_index < min) and value_index != 9999: flag = 0 elif value_index == 9999: flag = 2 else: flag = 1 flag_list.append(flag) outlier_values = sum(i < 1 for i in flag_list) missing_values = sum(i > 1 for i in flag_list) if missing_values == 0 and outlier_values != 0: validation_flag = 0 elif missing_values != 0 and outlier_values == 0: validation_flag = 2 elif missing_values != 0 and outlier_values != 0: validation_flag = 3 else: validation_flag = 1 return(validation_flag) #m.fuzzy.validation input=moorprojekt_ghg_europe_ecad splitfactor=landuse target=n2oaverage parameters=wt,cn20,ninput,tg_annual fuzzysets=3,2,2,3 iterations=1000 ensembles=2 -e #m.fuzzy.validation input=moorprojekt_ghg_europe_ecad_weight splitfactor=landuse target=n2oaverage parameters=wt,cn20,ninput,tg_annual fuzzysets=3,2,2,3 iterations=1000 ensembles=2 -e def MonteCarloSim(key, parameters, parametername, resultvalidationdictpara, uncertainties, na_value = 9999, weightfactor = 'None', weightnum = 0): # Application of Monte Carlo Simulation for uncertainty estimation of model results. # Set up dummy data points to select object type. points = vtkPoints() for i in range(5): for j in range(5): points.InsertNextPoint(i, j, 0) data = vtkDoubleArray() data.SetNumberOfTuples(25) data.SetName("data") data.FillComponent(0,3) ds = vtkPolyData() ds.Allocate(5,5) ds.GetPointData().SetScalars(data) ds.SetPoints(points) # Import fuzzy model XML representation file as object. fuzzyxml = open(parametername, 'r') fuzzylist = fuzzyxml.read() fuzzyxml.close() fuzzymodel = vtkXMLUtilities.ReadElementFromString(fuzzylist) if weightfactor == 'None': fisc = vtkTAG2EFuzzyInferenceModelParameter() fisc.SetXMLRepresentation(fuzzymodel) model = vtkTAG2EFuzzyInferenceModel() model.SetModelParameter(fisc) else: fisc = vtkTAG2EFuzzyInferenceModelParameter() weight = vtkTAG2EWeightingModelParameter() weight_model = fuzzymodel.GetNestedElement(0) weight_model.GetName() fisc_model = fuzzymodel.GetNestedElement(1) fisc_model.GetName() fisc.SetXMLRepresentation(fisc_model) weight.SetXMLRepresentation(weight_model) model = vtkTAG2EFuzzyInferenceModel() model.SetModelParameter(fisc) modelW = vtkTAG2EWeightingModel() modelW.SetModelParameter(weight) meta = MetaModel.MetaModel() meta.InsertModelParameter(model, fisc_model, "vtkTAG2EFuzzyInferenceModel") meta.InsertModelParameter(modelW, weight, "vtkTAG2EWeightingModel") meta.SetLastModelParameterInPipeline(modelW, weight, "vtkTAG2EWeightingModel") # Split parameter list. parameter_list = parameters.split(',') # Split parameter list. uncertainties_list = uncertainties.split(',') if len(uncertainties) != 0: [float(i) for i in uncertainties_list] para_num = resultvalidationdictpara[key] # Compute means, median, standard deviation for model parameters. para_mean = list() para_median = list() para_sd = list() para_val = resultvalidationdictpara.values() para_list = [list([float(i) for i in item]) for item in para_val] para_split = zip(*para_list) para_split_narem = [[i for i in list(item) if i != na_value] for item in para_split] for i in para_split_narem: para_mean.append(numpy.mean(i)) para_median.append(numpy.median(i)) para_sd.append(numpy.std(i)) # Create data distribution xml representation file. root = vtk.vtkXMLDataElement() root.SetName("DataDistributionDescription") root.SetAttribute("xmlns", "http://tag2e.googlecode.com/files/DataDistributionDescription") root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") root.SetAttribute("xsi:schemaLocation", "http://tag2e.googlecode.com/files/DataDistributionDescription http://tag2e.googlecode.com/files/DataDistributionDescription.xsd") root.SetAttribute("name", "Simulation") for para in parameter_list: para_index = parameter_list.index(para) dfn = vtkXMLDataElement() dfn.SetName("Norm") if (float(para_num[para_index]) == na_value): mean_val = para_mean[para_index] if len(uncertainties) != 0: sd_val = float(uncertainties_list[para_index]) else: sd_val = para_sd[para_index] else: mean_val = float(para_num[para_index]) if len(uncertainties) != 0: sd_val = float(uncertainties_list[para_index]) else: sd_val = para_sd[para_index] dfn.SetDoubleAttribute("mean", mean_val) dfn.SetDoubleAttribute("sd", sd_val) varn = vtkXMLDataElement() varn.SetName("Variable") varn.SetAttribute("name", para) varn.SetAttribute("type", "norm") varn.AddNestedElement(dfn) root.AddNestedElement(varn) if weightfactor != 'None': dfn = vtkXMLDataElement() dfn.SetName("Unif") dfn.SetDoubleAttribute("min", int(weightnum)) dfn.SetDoubleAttribute("max", int(weightnum)) varn = vtkXMLDataElement() varn.SetName("Variable") varn.SetAttribute("name", str(weightfactor)) varn.SetAttribute("type", "unif") varn.AddNestedElement(dfn) root.AddNestedElement(varn) # Create data distribution xml file. ddd = vtkTAG2EAbstractModelParameter() ddd.SetFileName("/tmp/MCWFISSimpleDataDistributionDescription1.xml") ddd.SetXMLRepresentation(root) ddd.Write() # Create Monte Carlo analyser object. analyser = vtkTAG2EModelMonteCarloVariationAnalyser() analyser.SetDataDistributionDescription(ddd) analyser.SetModel(model) analyser.SetNumberOfRandomValues(1000) analyser.SetMaxNumberOfIterations(2000) analyser.SetBreakCriterion(0.001) analyser.SetInput(ds) analyser.Update() output = analyser.GetOutput() output_range = output.GetFieldData().GetArray(model.GetResultArrayName()).GetRange() output_min = output_range[0] output_max = output_range[1] # Create R interface. riface = vtkRInterfaceSpatial() riface.AssignVTKDataArrayToRVariable(output.GetFieldData().\ GetArray(model.GetResultArrayName()), model.GetResultArrayName()) # Save the workspace for testing script = "quant <- quantile(result,c(0, 0.05, 0.25, 0.5, 0.75, 0.95, 1))" #print script riface.EvalRscript(script, True) result = riface.AssignRVariableToVTKDataArray("quant") result_array = list() for i in range(7): result_array.append(result.GetValue(i)) return(result_array) def crosscalibration(input, inputvector, validation, parameters, uncertainties, target, ensembles, iterations, fuzzysets, weightfactor = 'None', weightnum = 0, mcsim = False, boot = False, samplingfactor = 'None', rulelimit = '20'): resultlistcalibration = [] resultlistvalidation = [] execstringcalibration = '' execstringvalidation = '' resultlistcalibration = {} resultlistvalidation = {} inputtable = grass.read_command('v.db.select', map = input, columns = 'cat', \ flags = 'c', sep= ';') inputtable = re.split('\n',inputtable.strip('\n')) emptyinputdict = {} resultcalibrationdictcomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictcomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictflagscomplete = emptyinputdict.fromkeys(inputtable, []) if mcsim: resultvalidationdictmincomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq05complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq25complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq50complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq75complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq95complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmaxcomplete = emptyinputdict.fromkeys(inputtable, []) resultcalibrationdictmean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmean = emptyinputdict.fromkeys(inputtable, []) resultcalibrationdictsd = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictsd = emptyinputdict.fromkeys(inputtable, []) if mcsim: resultvalidationdictminmean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq05mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq25mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq50mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq75mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq95mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmaxmean = emptyinputdict.fromkeys(inputtable, []) calibrationproclist = [] calibrationmodelnproclist = [] validationmodelnproclist = [] proc_count = 0 #Parallel model runs for calibrations for ensemblenum in range(int(ensembles)): parametername = str(inputvector + '_' + str(ensemblenum) + '.xml') logname = str(inputvector + '_' + str(ensemblenum) + '.log') if weightfactor == 'None' and samplingfactor == 'None' and boot == False: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ overwrite = True, rulelimit = rulelimit)) elif weightfactor == 'None' and samplingfactor == 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ overwrite = True, flags = 'b', rulelimit = rulelimit)) elif weightfactor == 'None' and samplingfactor != 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ overwrite = True, samplingfactor = samplingfactor, flags = 'b', \ rulelimit = rulelimit)) elif weightfactor != 'None' and samplingfactor != 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ weightfactor = weightfactor, weightnum = weightnum, \ overwrite = True, samplingfactor = samplingfactor, flags = 'wb', \ rulelimit = rulelimit)) elif weightfactor != 'None' and samplingfactor == 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ weightfactor = weightfactor, weightnum = weightnum, \ overwrite = True, flags = 'wb', rulelimit = rulelimit)) else: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, \ weightfactor = weightfactor, weightnum = weightnum, \ log = logname, overwrite = True, flags = 'w', rulelimit = rulelimit)) proc_count += 1 #check for maximum number of parallel processes defined by cpu count if (proc_count == workers) or (proc_count == int(ensembles)): for process in calibrationproclist: process.wait() #empty process list and reset counter calibrationproclist = [] proc_count = 0 #model evaluation and output dictionary creation for ensembles for ensemblenum in range(int(ensembles)): #set names for output files outputcalibrationname = str(inputvector + '_calibration_' + str(ensemblenum)) outputvalidationname = str(inputvector + '_validation_' + str(ensemblenum)) parametername = str(inputvector + '_' + str(ensemblenum) + '.xml') if weightfactor == 'None': grass.run_command('v.fuzzy.model', input = input, parameter = parametername, \ output = outputcalibrationname, overwrite = True) grass.run_command('v.fuzzy.model', input = validation, parameter = parametername, \ output = outputvalidationname, overwrite = True) else: grass.run_command('v.fuzzy.model', input = input, parameter = parametername, \ output = outputcalibrationname, overwrite = True, flags = 'w') grass.run_command('v.fuzzy.model', input = validation, parameter = parametername, \ output = outputvalidationname, overwrite = True, flags = 'w') resultcalibration = grass.read_command('v.db.select', map = outputcalibrationname, columns = str('cat,result,' + parameters), flags = 'c', sep= ';') resultvalidation = grass.read_command('v.db.select', map = outputvalidationname, columns = str('cat,result,' + parameters), flags = 'c', sep= ';') if weightfactor != 'None': resultweight = grass.read_command('v.db.select', map = outputvalidationname, columns = str('cat,' + weightfactor), flags = 'c', sep= ';') resultweight = re.split('\n|;',resultweight.strip('\n')) resultweightdict = dict(zip(resultweight[::2], resultweight[1::2])) resultcalibration = re.split('\n|;',resultcalibration.strip('\n')) resultvalidation = re.split('\n|;',resultvalidation.strip('\n')) var_dist = 2 + len(parameters.split(',')) parameter_validation = [] for i in range(2, var_dist): parameter_validation.append(resultcalibration[i::var_dist]) parameter_validation = zip(*parameter_validation) resultcalibrationdict = dict(zip(resultcalibration[::var_dist], resultcalibration[1::var_dist])) resultvalidationdict = dict(zip(resultvalidation[::var_dist], resultvalidation[1::var_dist])) resultvalidationdictpara = dict(zip(resultcalibration[::var_dist], parameter_validation)) factor_dict = ParameterXMLRange(parametername, weightfactor) for l in resultcalibrationdict: resultcalibrationdictcomplete[l] = resultcalibrationdictcomplete[l] + [resultcalibrationdict[l]] {i:j for i,j in resultcalibrationdictcomplete.items() if j != []} for l in resultvalidationdict: resultvalidationdictcomplete[l] = resultvalidationdictcomplete[l] + [resultvalidationdict[l]] validation_flag = ParameterComparisonFlag(l, factor_dict, parameters, resultvalidationdictpara) validation_flag_dict = {l:validation_flag} resultvalidationdictflagscomplete[l] = resultvalidationdictflagscomplete[l] + [validation_flag_dict[l]] if mcsim: if weightfactor == 'None': mc_result = MonteCarloSim(l, parameters, parametername, resultvalidationdictpara, uncertainties) else: mc_result = MonteCarloSim(l, parameters, parametername, resultvalidationdictpara, uncertainties, weightfactor = weightfactor, weightnum = resultweightdict[l]) validation_min_dict = {l:mc_result[0]} validation_q05_dict = {l:mc_result[1]} validation_q25_dict = {l:mc_result[2]} validation_q50_dict = {l:mc_result[3]} validation_q75_dict = {l:mc_result[4]} validation_q95_dict = {l:mc_result[5]} validation_max_dict = {l:mc_result[6]} resultvalidationdictmincomplete[l] = resultvalidationdictmincomplete[l] + [validation_min_dict[l]] resultvalidationdictq05complete[l] = resultvalidationdictq05complete[l] + [validation_q05_dict[l]] resultvalidationdictq25complete[l] = resultvalidationdictq25complete[l] + [validation_q25_dict[l]] resultvalidationdictq50complete[l] = resultvalidationdictq50complete[l] + [validation_q50_dict[l]] resultvalidationdictq75complete[l] = resultvalidationdictq75complete[l] + [validation_q75_dict[l]] resultvalidationdictq95complete[l] = resultvalidationdictq95complete[l] + [validation_q95_dict[l]] resultvalidationdictmaxcomplete[l] = resultvalidationdictmaxcomplete[l] + [validation_max_dict[l]] {i:j for i,j in resultvalidationdictcomplete.items() if j != []} resultvalidationdictflagscomplete = {i:j for i,j in resultvalidationdictflagscomplete.items() if j != []} if mcsim: resultvalidationdictmincomplete = {i:j for i,j in resultvalidationdictmincomplete.items() if j != []} resultvalidationdictq05complete = {i:j for i,j in resultvalidationdictq05complete.items() if j != []} resultvalidationdictq25complete = {i:j for i,j in resultvalidationdictq25complete.items() if j != []} resultvalidationdictq50complete = {i:j for i,j in resultvalidationdictq50complete.items() if j != []} resultvalidationdictq75complete = {i:j for i,j in resultvalidationdictq75complete.items() if j != []} resultvalidationdictq95complete = {i:j for i,j in resultvalidationdictq95complete.items() if j != []} resultvalidationdictmaxcomplete = {i:j for i,j in resultvalidationdictmaxcomplete.items() if j != []} # Create dicionaries with mean calibration and mean, min and max validation model result values. for j in resultcalibrationdictcomplete: resultcalibrationdictmean[j] = resultcalibrationdictmean[j] + [numpy.mean(map(float,resultcalibrationdictcomplete[j]))] for j in resultvalidationdictcomplete: resultvalidationdictmean[j] = resultvalidationdictmean[j] + [numpy.mean(map(float,resultvalidationdictcomplete[j]))] for j in resultcalibrationdictcomplete: resultcalibrationdictsd[j] = resultcalibrationdictsd[j] + [numpy.std(map(float,resultcalibrationdictcomplete[j]))] for j in resultvalidationdictcomplete: resultvalidationdictsd[j] = resultvalidationdictsd[j] + [numpy.std(map(float,resultvalidationdictcomplete[j]))] if mcsim: for j in resultvalidationdictmincomplete: resultvalidationdictminmean[j] = resultvalidationdictminmean[j] + [numpy.min(map(float,resultvalidationdictmincomplete[j]))] for j in resultvalidationdictq05complete: resultvalidationdictq05mean[j] = resultvalidationdictq05mean[j] + [numpy.mean(map(float,resultvalidationdictq05complete[j]))] for j in resultvalidationdictq25complete: resultvalidationdictq25mean[j] = resultvalidationdictq25mean[j] + [numpy.mean(map(float,resultvalidationdictq25complete[j]))] for j in resultvalidationdictq50complete: resultvalidationdictq50mean[j] = resultvalidationdictq50mean[j] + [numpy.mean(map(float,resultvalidationdictq50complete[j]))] for j in resultvalidationdictq75complete: resultvalidationdictq75mean[j] = resultvalidationdictq75mean[j] + [numpy.mean(map(float,resultvalidationdictq75complete[j]))] for j in resultvalidationdictq95complete: resultvalidationdictq95mean[j] = resultvalidationdictq95mean[j] + [numpy.mean(map(float,resultvalidationdictq95complete[j]))] for j in resultvalidationdictmaxcomplete: resultvalidationdictmaxmean[j] = resultvalidationdictmaxmean[j] + [numpy.max(map(float,resultvalidationdictmaxcomplete[j]))] # Remove emtpy values from dictionaries {i:j for i,j in resultcalibrationdictmean.items() if j != []} {i:j for i,j in resultvalidationdictmean.items() if j != []} {i:j for i,j in resultcalibrationdictsd.items() if j != []} {i:j for i,j in resultvalidationdictsd.items() if j != 0.} if mcsim: {i:j for i,j in resultvalidationdictminmean.items() if j != []} {i:j for i,j in resultvalidationdictq05mean.items() if j != []} {i:j for i,j in resultvalidationdictq25mean.items() if j != []} {i:j for i,j in resultvalidationdictq50mean.items() if j != []} {i:j for i,j in resultvalidationdictq75mean.items() if j != []} {i:j for i,j in resultvalidationdictq95mean.items() if j != []} {i:j for i,j in resultvalidationdictmaxmean.items() if j != []} if mcsim: return(resultcalibrationdictcomplete, resultvalidationdictcomplete, resultcalibrationdictmean, resultvalidationdictmean, resultvalidationdictsd, resultvalidationdictflagscomplete, resultvalidationdictminmean, resultvalidationdictq05mean, resultvalidationdictq25mean, resultvalidationdictq50mean, resultvalidationdictq75mean, resultvalidationdictq95mean, resultvalidationdictmaxmean) else: return(resultcalibrationdictcomplete, resultvalidationdictcomplete, resultcalibrationdictmean, resultvalidationdictmean, resultvalidationdictsd, resultvalidationdictflagscomplete) def transformfactorweighting(input, weightfactor): # Get list of weights from vector column, transformation to numerical values weightfactorlist = grass.read_command('v.db.select', map = input, columns = weightfactor, flags = 'c') weightfactorlist = weightfactorlist.rstrip('\n').split('\n') weightfactorkeylist = dict.fromkeys(weightfactorlist).keys() weightiternum = range(len(weightfactorkeylist)) weightfactorkeydict = dict(zip(weightfactorkeylist, weightiternum)) #add numerical values of weighting factor as new column to vector table weightfactorcolumnname = str(weightfactor + '_num') grass.run_command('v.db.addcolumn', map = input, columns = str(weightfactorcolumnname + ' double precision')) for weightfactorkey in weightfactorkeylist: cmd = "UPDATE %s SET %s=%s WHERE %s='%s'" % (input, weightfactorcolumnname, weightfactorkeydict[weightfactorkey],weightfactor, weightfactorkey) grass.write_command('db.execute', input = '-', stdin = cmd) return(weightfactorcolumnname, weightiternum) def splitvectordata(input, splitfactor): splitfactorlist = grass.read_command('v.db.select', map = input, columns = splitfactor, flags = 'c') splitfactorlist = splitfactorlist.rstrip('\n').split('\n') splitfactorkeylist = dict.fromkeys(splitfactorlist).keys() splitvectorlist =[] excludedvectorlist =[] splitcount = 0 for splitfactorname in splitfactorkeylist: grass.run_command('v.extract', input = input, output = str(input + '_' + str(splitcount)), overwrite = True, where = str(splitfactor + " != '" + splitfactorname + "'")) grass.run_command('v.extract', input = input, output = str(input + '_' + str(splitcount) + '_extract'), overwrite = True, where = str(splitfactor + " = '" + splitfactorname + "'")) splitvectorlist.append(str(input + '_' + str(splitcount))) excludedvectorlist.append(str(input + '_' + str(splitcount) + '_extract')) splitcount += 1 return(splitvectorlist,excludedvectorlist) #extraction and visualisation of parameters for the fuzzysets of calibrated ensembles and def xmlparse(vinputfile, ensemblenum): reader = vtk.vtkXMLDataParser() xmlstringall = [] for i in range(int(ensemblenum)): reader.SetFileName(str(vinputfile + '_' + str(i) + '.xml')) reader.Parse() xmltable = [] root = reader.GetRootElement() if root.GetName() == "FuzzyInferenceScheme": elenum = root.GetNumberOfNestedElements() for e in range(0,elenum,1): element = root.GetNestedElement(e) if element.GetName() == 'Factor': setnum = element.GetNumberOfNestedElements() for s in range(0,setnum): set = element.GetNestedElement(s) if set.GetAttribute('type') == 'Triangular': trianglenum = set.GetNumberOfNestedElements() triangle = set.GetNestedElement(0) xmldict = {} xmldict['ensemble'] = str(i) xmldict['factor'] = element.GetAttribute('name') xmldict['min'] = element.GetAttribute('min') xmldict['max'] = element.GetAttribute('max') xmldict['set'] = set.GetAttribute('position') xmldict['center'] = triangle.GetAttribute('center') xmldict['left'] = triangle.GetAttribute('left') xmldict['right'] = triangle.GetAttribute('right') xmltable.append(xmldict) xmlstring = [] xmlstring.append(string.join(xmltable[0].keys(),',')) if i == 0: xmlstringall.append(string.join(xmltable[0].keys(),',')) for data in xmltable: xmlstring.append(string.join(data.values(),',')) xmlstringall.append(string.join(data.values(),',')) xmlstringfinal = string.join(xmlstringall,'\n') #print(xmlstringfinal) file = open(str('/tmp/' + vinputfile + '_fuzzysets' + '.txt'),'w') file.write(xmlstringfinal) file.close() # Run R visualise the fuzzy sets auomtatically and store the result in pdf file RScript = """ PlotFuzzysets <- function(input, dir = '/tmp/') { # Plot Fuzzysets imported from XML Fuzzy Interference Scheme created by TAG2E. # An PDF document will be created. # # args: # input: Name of input text file created by m.fuzzy.validation, containing # fuzzy set positions. # dir: Name of directory containing input file. Default is /tmp. # Import input file. data = read.csv(file = paste(dir, input, sep = ''), header = TRUE, sep = ",") # Get number of factors. factor_amount <- length(levels(data$factor)) # Create pdf document. pdf(file = paste(substr(input, 1, nchar(input) - 4), ".pdf", sep = ''), width = 12, height = 8) par(lwd = 2, cex = 1.5, mar = c(5, 5, 5, 5)) # Loop through fuzzy sets for different factors. for (f in 1:length(levels(data$factor))) { # Create subset for each factor. setfactor = levels(data$factor)[f] set = subset(data,factor == setfactor) # Compute fuzzy set amount and position statistics for ensembles. factor_length <- nrow(subset(set, ensemble == 0, select = set)) factor_labels <- subset(set, ensemble == 0, select = set)[,1] center_labels <- subset(set, ensemble == 0, select = center)[,1] maximum <- max(set$max) minimum <- max(set$min) if (factor_length == 2) { plot(1, type='n', ylim = c(0,1), xlim = c(minimum, maximum), xlab = paste(setfactor), ylab = "Membership grade", main = paste('Fuzzysets for Factor ', setfactor)) axis(side = 3, labels = factor_labels, at = center_labels, cex.axis = 1, tick = FALSE) for ( i in seq(0, max(set$ensemble))) { center_sub <- as.vector(subset(set, ensemble == i, select = center)) right_sub <- subset(set, ensemble == i, select = right) left_sub <- subset(set, ensemble == i, select = left) segments(center_sub[1, 1], 1, center_sub[1, 1] + right_sub[1, 1], 0, col = 'blue') segments(minimum, 1, center_sub[1, 1], 1, col = 'blue') segments(center_sub[1, 1] + right_sub[1, 1], 0, maximum, 0, col = 'blue') segments(center_sub[2, 1] - left_sub[2, 1], 0, minimum, 0, col = 'green') segments(center_sub[2, 1] - left_sub[2, 1], 0, center_sub[2, 1], 1, col = 'green') segments(center_sub[2, 1], 1, maximum, 1, col = 'green') } } else if (factor_length == 3) { plot(1, type='n', ylim = c(0, 1), xlim = c(minimum, maximum), xlab = paste(setfactor), ylab = "Membership grade", main = paste('Fuzzysets for Factor ', setfactor)) axis(side = 3, labels = factor_labels, at = center_labels, cex.axis = 1, tick = FALSE) for ( i in seq(0, max(set$ensemble))) { center_sub <- subset(set, ensemble == i, select = center) right_sub <- subset(set, ensemble == i, select = right) left_sub <- subset(set, ensemble == i, select = left) segments(center_sub[1, 1], 1, center_sub[1, 1] + right_sub[1, 1], 0, col = 'blue') segments(minimum, 1, center_sub[1, 1], 1, col = 'blue') segments(center_sub[1, 1] + right_sub[1, 1], 0, maximum, 0, col = 'blue') segments(minimum, 0, center_sub[2, 1] - left_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] - left_sub[2, 1], 0, center_sub[2, 1], 1, col = 'red') segments(center_sub[2, 1], 1, center_sub[2, 1] + right_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] + right_sub[2, 1], 0, maximum, 0, col = 'red') segments(center_sub[3, 1] - left_sub[3, 1], 0, minimum, 0, col = 'green') segments(center_sub[3, 1] - left_sub[3, 1], 0, center_sub[3, 1], 1, col = 'green') segments(center_sub[3, 1], 1, maximum, 1, col = 'green') } } else if (factor_length == 4) { plot(1, type='n', ylim = c(0, 1), xlim = c(minimum, maximum), xlab = paste(setfactor), ylab = "Membership grade", main = paste('Fuzzysets for Factor ', setfactor)) axis(side = 3, labels = factor_labels, at = center_labels, cex.axis = 1, tick = FALSE) for ( i in seq(0, max(set$ensemble))) { center_sub <- subset(set, ensemble == i, select = center) right_sub <- subset(set, ensemble == i, select = right) left_sub <- subset(set, ensemble == i, select = left) segments(center_sub[1, 1], 1, center_sub[1, 1] + right_sub[1, 1], 0, col = 'blue') segments(minimum, 1, center_sub[1, 1], 1, col = 'blue') segments(center_sub[1, 1] + right_sub[1, 1], 0, maximum, 0, col = 'blue') segments(minimum, 0, center_sub[2, 1] - left_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] - left_sub[2, 1], 0, center_sub[2, 1], 1, col = 'red') segments(center_sub[2, 1], 1, center_sub[2, 1] + right_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] + right_sub[2, 1], 0, maximum, 0, col = 'red') segments(center_sub[3, 1] - left_sub[3, 1], 0, center_sub[3, 1], 1, col = 'black') segments(center_sub[3, 1], 1, center_sub[3, 1] + right_sub[3, 1], 0, col = 'black') segments(center_sub[3, 1] + right_sub[3, 1], 0, maximum, 0, col = 'black') segments(center_sub[4, 1] - left_sub[4, 1], 0, minimum, 0, col = 'green') segments(center_sub[4, 1] - left_sub[4, 1], 0, center_sub[4, 1], 1, col = 'green') segments(center_sub[4, 1], 1, maximum, 1, col = 'green') } } } dev.off() } PlotFuzzysets(input = "inputfilename") """ RScript = RScript.replace("inputfilename", str(vinputfile + '_fuzzysets' + '.txt')) inputlist = ["R", "--vanilla"] proc = subprocess.Popen(args=inputlist, stdin=subprocess.PIPE) proc.stdin.write(RScript) proc.communicate() def ValidationPlot(input, target, montecarloflag, parainput): RScript = """ ## Script for evaluating cross validation of fuzzy model. require(Hmisc) # Function to calculate rsquared for two vector list elements (x,y) rsquaredcalc <- function(x, y){ # Compute coefficient of determination. totalsumofsquares = sum((x - mean(x))^2) residualsumofsquares = sum((x - y)^2) rsquared = 1 - residualsumofsquares / totalsumofsquares return(rsquared) } EvalFuzzyValidation <- function(file.name, target, parameters, file.dir = getwd(), missing = TRUE, outlier = TRUE, na.value = 9999, montecarlo = TRUE) { # Import valdiation file created by m.fuzzy.validation(fmta) and create # calibration and valdiation plots. # # args: # file.name: Name of m.fuzzy.validation result file. # target: Column name of target variable in crossvalidation. # parameters: Name of the parameters used for model calibration. # file.dir: Path to directory containing file.name. # missing: Boolean if missing values should be included. Default is TRUE. # outlier: Boolean if outlier for calibration range should be colored. # Default is TRUE. # na.value: Value used as no data representation. # montecarlo: Boolean if montecarlo simulation flag is set. Default is TRUE. # Import m.fuzzy.validation result file. file.location <- paste(file.dir, '/', file.name, sep = '') validata = read.csv(file.location, header = T, sep = ",") # Processing data formats. validata[validata == na.value] = NA # Check if NA values should be excluded. if (missing == FALSE) validata = na.omit(validata) # Set axis label names for output graphics. ylabname <- expression(paste(N[2],'O-N in [g' %.% m^-2 %.% a^-1, ']', sep = '')) #target <- 'n2oaverage_flux' xlab <- expression(paste('Measured ', N[2],'O-N in [g' %.% m^-2 %.% a^-1, ']', sep = '')) ylab <- expression(paste('Modelled ', N[2],'O-N in [g' %.% m^-2 %.% a^-1, ']', sep = '')) if (!is.vector(validata[[target]])) { target <- 'n2oaverage_log' xlab <- expression(paste('Measured ', N[2],'O-N in log [g' %.% m^-2 %.% a^-1, ']', sep = '')) ylab <- expression(paste('Modelled ', N[2],'O-N in log [g' %.% m^-2 %.% a^-1, ']', sep = '')) } vali.title <- "Flux Validation Plot" cali.title <- "Flux Calibration Plot" axis.lim <- range(validata[[target]]) leg.factors <- levels(as.factor(validata$flag_0)) # Set color palette for plotting. if (outlier) { palette(c("orange", "black", "grey", "red")) } else { palette(c("black", "black")) } if (missing) { plot_val_name <- 'Validation_all_' } else { palette(c("black", "black")) plot_val_name <- 'Validation_narm_' } #figure.dir <- "./figures/" figure.dir <- file.dir valicolor = factor(validata$flag_0, levels = c("0", "1", "2", "3")) # Create validation plot. pdf(file = paste(figure.dir, '/', plot_val_name, nrow(validata), '_', Sys.Date(), '.pdf', sep = '')) par(mar = c(5, 5, 4, 2), bty = 'o', tck = 0.01, cex.axis = 1.25, cex.lab = 1.25, cex.main = 1.25, cex = 1.25, lwd = 1.25, pch = 20, las = 1) plot(validata[[target]], validata$validation_mean, ylab = ylab, xlab = xlab, xlim = axis.lim, ylim = axis.lim, col = valicolor, cex = 1, main = vali.title) errbar(x= validata[[target]], y = validata$validation_mean, yplus = validata$validation_mean + validata$validation_sd, yminus = validata$validation_mean - validata$validation_sd, add = T, pch = 20, col = valicolor) mtext(paste('Direct comparison NSE: ', round(rsquaredcalc(validata[[target]], validata$validation_mean), 2))) abline(0, 1) if (missing & outlier) { legend(axis.lim[1], axis.lim[2], c("Outlier", "Valide", "Missing", "Missing + Outlier") , col = c("orange", "black", "grey", "red"), pch = 20) } else if (outlier) { legend(axis.lim[1], axis.lim[2], c("Outlier", "Valide") , col = c("orange", "black"), pch = 20) } dev.off() # Set color palette for plotting. if (missing) { palette(c("black", "grey")) plot_cal_name <- 'Calibration_all_' } else { palette(c("black", "black")) plot_cal_name <- 'Calibration_narm_' } calicol <- grep(substr(file.name, 1, nchar(file.name) - 22), names(validata)) calidata <- sapply(validata[calicol], function(x) x != validata[2]) if (sum(calidata) != 0) { calimean <- rowMeans(validata[calicol][calidata[1, ]]) calisd <- apply(validata[calicol][calidata[1, ]], MAR = 1, sd) } else { calimean <- rowMeans(validata[calicol]) calisd <- apply(validata[calicol], MAR=1, function(x) x = 0) } # Create calibration plot. pdf(file = paste(figure.dir, '/', plot_cal_name, nrow(validata), '_', Sys.Date(), '.pdf', sep = '')) par(mar = c(5, 5, 4, 2), bty = 'o', tck = 0.01, cex.axis = 1.25, cex.lab = 1.25, cex.main = 1.25, cex = 1.25, lwd = 1.25, pch = 20, las = 1) plot(validata[[target]], calimean, ylab = ylab, xlab = xlab, xlim = axis.lim, ylim = axis.lim, col = as.factor(validata$flag_0 == 2 | validata$flag_0 == 3 ), cex = 1, main = cali.title) errbar(x= validata[[target]], y = calimean, yplus = calimean + calisd, yminus = calimean - calisd, add = T, pch = 20, col = as.factor(validata$flag_0 == 2 | validata$flag_0 == 3 )) mtext(paste('Direct comparison NSE: ', round(rsquaredcalc(validata[[target]], calimean), 2))) abline(0, 1) if (missing) { legend(axis.lim[1], axis.lim[2], c("Valide", "Missing"), col = c("black", "grey"), pch = 20) } dev.off() # Create Monte Carlo simulation plots for all parameters and outcome. if (montecarlo) { paralist <- strsplit(parameters,',') paralist <- c(unlist(paralist), target) for (element in paralist) { # Sort data frame by parameter. validata_sort <- validata[order(validata[[element]]), ] validata_sort = na.omit(validata_sort) plot_mc_name <- paste('MC_result_', element, '_', sep = '') mc.title <- "Monte Carlo Simulation Plot" para.lim <- range(validata_sort[[element]]) if (element == target) paralab <- xlab else paralab <- element # Create parameter plot. pdf(file = paste(figure.dir, '/', plot_mc_name, nrow(validata_sort), '_', Sys.Date(), '.pdf', sep = '')) par(mar = c(5, 5, 4, 2), bty = 'o', tck = 0.01, cex.axis = 1.25, cex.lab = 1.25, cex.main = 1.25, cex = 1.25, lwd = 1.25, pch = 20, las = 1) plot(validata_sort[[element]], validata_sort$q50, type = 'n', ylim = axis.lim, ylab = ylab, xlim = para.lim, xlab = paralab, pch = 20, cex = 0.5, main = mc.title) polygon(x = c(validata_sort[[element]], rev(validata_sort[[element]])), y = c(validata_sort$q95, rev(validata_sort$q5)), col = 'grey', border = "white") lines(validata_sort[[element]], validata_sort$q50, lwd = 2) #with(validata_sort, errbar(x = validata_sort[[element]], y = q50, yplus = q75, # yminus = q25, add = T, type = 'n', lwd = 1)) dev.off() } } } if (as.numeric(montesim) == 1) { EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput") EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput", missing = F, outlier = F) } else { EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput", montecarlo = F) EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput", missing = F, outlier = F, montecarlo = F) } """ RScript = RScript.replace("inputfilename", str(input + '_validation_result.csv')) RScript = RScript.replace("targetname", str(target)) RScript = RScript.replace("parainput", str(parainput)) if montecarloflag: RScript = RScript.replace("montesim", "1") else: RScript = RScript.replace("montesim", "0") inputlist = ["R", "--vanilla"] proc = subprocess.Popen(args=inputlist, stdin=subprocess.PIPE) proc.stdin.write(RScript) proc.communicate() def main(): input = options['input'] output = options['output'] target = options['target'] weightfactor = options['weightfactor'] splitfactor = options['splitfactor'] samplingfactor = options['samplingfactor'] parameters = options['parameters'] uncertainties = options['uncertainties'] ensembles = options['ensembles'] iterations = options['iterations'] fuzzysets = options['fuzzysets'] allparameterflag = flags['a'] bootflag = flags['b'] splitfactorflag = flags['e'] categoricalflag = flags['c'] weightingflag = flags['w'] montecarloflag = flags['m'] inputrule = options['rulelimit'] if montecarloflag: if len(parameters.split(',')) != len(uncertainties.split(',')) \ and len(uncertainties) != 0: print("ERROR: Parameter and Uncertainty length differs") sys.exit() if splitfactorflag: splitvectorinputlist, splitvectorexcludedlist = splitvectordata(input, splitfactor) else: splitvectorinputlist = list() splitvectorinputlist.append(input) splitvectorexcludedlist = list() splitvectorexcludedlist.append(input) if weightingflag: if categoricalflag: weightfactorcolumnname, weightiternum = transformfactorweighting(input, weightfactor) else: weightfactorcolumnname = weightfactor weightfactorlist = grass.read_command('v.db.select', map = input, columns = weightfactor, flags = 'c') weightfactorlist = weightfactorlist.rstrip('\n').split('\n') weightfactorkeylist = dict.fromkeys(weightfactorlist).keys() weightiternum = len(weightfactorkeylist) #splitvectorinputlist = ','.join(splitvectorinputlist) #splitvectorexcludedlist = ','.join(splitvectorexcludedlist) #create empty dictionaries with list items and vector input category keys inputtable = grass.read_command('v.db.select', map = input, columns = 'cat', flags = 'c', sep= ';') inputtable = re.split('\n',inputtable.strip('\n')) emptyinputdict = {} calibrationresultlistcomplete = emptyinputdict.fromkeys(inputtable, []) validationresultlistcomplete = emptyinputdict.fromkeys(inputtable, []) validationresultsdcomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictflagscomplete = emptyinputdict.fromkeys(inputtable, []) if montecarloflag: resultvalidationdictmincomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq05complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq25complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq50complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq75complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq95complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmaxcomplete = emptyinputdict.fromkeys(inputtable, []) calibrationresultmeanlistcomplete = emptyinputdict.fromkeys(inputtable, []) parameterdictcomplete = emptyinputdict.fromkeys(inputtable, []) targettable = grass.read_command('v.db.select', map = input, columns = str('cat,' + target), flags = 'c', sep= ';') targettable = re.split('\n|;',targettable.strip('\n')) targetdict = dict(zip(targettable[::2],targettable[1::2])) if splitfactorflag: splitfactortable = grass.read_command('v.db.select', map = input, columns = str('cat,' + splitfactor), flags = 'c', sep= ';') splitfactortable = re.split('\n|;',splitfactortable.strip('\n')) splitfactordict = dict(zip(splitfactortable[::2],splitfactortable[1::2])) for l in targetdict: parameterdictcomplete[l] = parameterdictcomplete[l] + [targetdict[l]] + [splitfactordict[l]] else: for l in targetdict: parameterdictcomplete[l] = parameterdictcomplete[l] + [targetdict[l]] parameternamelist = parameters.split(',') colnum = len(parameternamelist) for parameter in parameternamelist: parametertable = grass.read_command('v.db.select', map = input, columns = str('cat,' + parameter), flags = 'c', sep= ';') parametertable = re.split('\n|;',parametertable.strip('\n')) parameterdict = dict(zip(parametertable[::2],parametertable[1::2])) for l in parameterdict: parameterdictcomplete[l] = parameterdictcomplete[l] + [parameterdict[l]] calibrationnamecomplete = [] for inputvector in splitvectorinputlist: if splitfactorflag: excludedvector = str(inputvector + '_extract') else: excludedvector = inputvector calibrationnamecomplete.append(inputvector) if weightfactor == 'None' and montecarloflag: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, resultvalidationdictmin, \ resultvalidationdictq05, resultvalidationdictq25, resultvalidationdictq50, \ resultvalidationdictq75, resultvalidationdictq95, resultvalidationdictmax \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, mcsim = True, boot = bootflag, \ samplingfactor = samplingfactor, rulelimit = inputrule) elif weightfactor == 'None' and montecarloflag == False: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, mcsim = False, boot = bootflag, \ samplingfactor = samplingfactor, rulelimit = inputrule) elif weightfactor != 'None' and montecarloflag: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, resultvalidationdictmin, \ resultvalidationdictq05, resultvalidationdictq25, resultvalidationdictq50, \ resultvalidationdictq75, resultvalidationdictq95, resultvalidationdictmax \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, weightfactorcolumnname, weightiternum, \ mcsim = True, boot = bootflag, samplingfactor = samplingfactor, rulelimit = inputrule) else: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, weightfactorcolumnname, weightiternum, \ mcsim = False, boot = bootflag, samplingfactor = samplingfactor, rulelimit = inputrule) # Create Fuzzyset plots. xmlparse(inputvector, ensembles) for l in calibrationresultmeandict: calibrationresultmeanlistcomplete[l] = calibrationresultmeanlistcomplete[l] + [calibrationresultmeandict[l]] for l in validationresultmeandict: validationresultlistcomplete[l] = validationresultlistcomplete[l] + [validationresultmeandict[l]] for l in validationresultsddict: validationresultsdcomplete[l] = validationresultsdcomplete[l] + [validationresultsddict[l]] for l in resultvalidationdictflags: resultvalidationdictflagscomplete[l] = resultvalidationdictflagscomplete[l] + resultvalidationdictflags[l] if montecarloflag: for l in resultvalidationdictmin: resultvalidationdictmincomplete[l] = resultvalidationdictmincomplete[l] + resultvalidationdictmin[l] for l in resultvalidationdictq05: resultvalidationdictq05complete[l] = resultvalidationdictq05complete[l] + resultvalidationdictq05[l] for l in resultvalidationdictq25: resultvalidationdictq25complete[l] = resultvalidationdictq25complete[l] + resultvalidationdictq25[l] for l in resultvalidationdictq50: resultvalidationdictq50complete[l] = resultvalidationdictq50complete[l] + resultvalidationdictq50[l] for l in resultvalidationdictq75: resultvalidationdictq75complete[l] = resultvalidationdictq75complete[l] + resultvalidationdictq75[l] for l in resultvalidationdictq95: resultvalidationdictq95complete[l] = resultvalidationdictq95complete[l] + resultvalidationdictq95[l] for l in resultvalidationdictmax: resultvalidationdictmaxcomplete[l] = resultvalidationdictmaxcomplete[l] + resultvalidationdictmax[l] if montecarloflag: for l in parameterdictcomplete: validationresultlistcomplete[l] = [i[0] for i in validationresultlistcomplete[l] if not numpy.isnan(i)] + \ [i[0] for i in validationresultsdcomplete[l] if not i == [0]] + \ resultvalidationdictmincomplete[l] + \ resultvalidationdictq05complete[l]+ \ resultvalidationdictq25complete[l] + \ resultvalidationdictq50complete[l] + \ resultvalidationdictq75complete[l] + \ resultvalidationdictq95complete[l] + \ resultvalidationdictmaxcomplete[l] + \ parameterdictcomplete[l] + \ resultvalidationdictflagscomplete[l] + \ [i[0] for i in calibrationresultmeanlistcomplete[l]] else: for l in parameterdictcomplete: validationresultlistcomplete[l] = [i[0] for i in validationresultlistcomplete[l] if not numpy.isnan(i)] + \ [i[0] for i in validationresultsdcomplete[l] if not i == [0]] + \ parameterdictcomplete[l] + \ resultvalidationdictflagscomplete[l] + \ [i[0] for i in calibrationresultmeanlistcomplete[l]] flag_list = [] for ensemblenum in range(int(ensembles)): flag_list.append(str('flag_' + str(ensemblenum))) if montecarloflag: quantile_list = [] for i in (5,25,50,75,95): quantile_list.append(str('q'+str(i))) o = open(str(input + '_validation_result.csv'), "w+") w = csv.writer(o) if splitfactorflag and montecarloflag: w.writerow(['cat'] + \ ['validation_mean'] + \ ['validation_sd'] + \ ['validation_min'] + \ quantile_list + \ ['validation_max'] + \ [target] + \ [splitfactor] + \ parameternamelist + \ flag_list + \ calibrationnamecomplete) elif splitfactorflag and montecarloflag == False: w.writerow(['cat'] + \ ['validation_mean'] + \ ['validation_sd'] + \ [target] + \ [splitfactor] + \ parameternamelist + \ flag_list + \ calibrationnamecomplete) else: w.writerow(['cat'] + \ ['validation_mean'] + \ ['validation_sd'] + \ [target] + \ parameternamelist + \ flag_list + \ calibrationnamecomplete) for key, val in validationresultlistcomplete.items(): w.writerow([key] + val) o.close() # Create Validation and Calibration Plots. ValidationPlot(input, target, montecarloflag, parameters) if __name__ == "__main__": options, flags = grass.parser() main()
Python
#!/usr/bin/env python ################################################################################################### # # MODULE: m.fuzzy.validation # AUTHOR: Thomas Leppelt # PURPOSE: Selection, calibration and validation of parameter combinations for fuzzy models. # ################################################################################################### #%module #% description: Selection, calibration and validation of parameter combinations for fuzzy models. #% keywords: Miscellaneous #% keywords: Fuzzy model,TAG2E #%end #%option G_OPT_F_INPUT #% description: Name of input vector map for fuzzy model input #% required : yes #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Name of output vector file #% required : no #% guisection: Files & format #%end #%option #% key: target #% type : string #% description: Select name for target variable #% required : yes #% multiple: no #% guisection: Files & format #%end #%option #% key: weightfactor #% type : string #% description: Select name for weighting variable #% required : no #% multiple: no #% guisection: Files & format #% answer: None #%end #%option #% key: splitfactor #% type : string #% description: Select factor name for dataset seperation #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: samplingfactor #% type : string #% description: The name of the column with ids for bootstrap aggregation selection #% required : no #% multiple: no #% guisection: Files & format #% answer: None #%end #%option #% key: parameters #% type : string #% description: List of driving parameters in input attribute table for selection #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option #% key: uncertainties #% type : double #% description: The uncertainty of parameters in same order to be used for monte carlo simulation #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: rulelimit #% type : double #% description: The rule limit specifies the minimum percentage of data that should be located in a single rule. #% required : no #% multiple: no #% guisection: Files & format #% answer: 20 #%end #%option #% key: ensembles #% type : integer #% description: Number of model ensembles extracted by bootstrapping #% required : no #% multiple: no #% guisection: Files & format #% answer: 50 #%end #%option #% key: iterations #% type : integer #% description: The maximum number of iterations #% required : no #% multiple: no #% guisection: Files & format #% answer: 50000 #%end #%option #% key: fuzzysets #% type : integer #% description: The number of fuzzy sets to be used for calibration for each factor: in case of 4 factors each of 2 fuzzy sets: 2,2,2,2 #% required : no #% multiple: yes #% guisection: Files & format #%end #%flag #% key: a #% description: Use all parameters in input attribute table for calibration #%end #%flag #% key: b #% description: Use boostrap aggregation (bagging) for input data selection #%end #%flag #% key: e #% description: Activate crossvalidation by given splitfactor #%end #%flag #% key: c #% description: Transform categorical variable to numerical weight factor for selection #%end #%flag #% key: w #% description: Using weight factor for calibration #%end #%flag #% key: m #% description: Activate Monte Carlo simulation for uncertainty estimation #%end import sys import os import grass.script as grass import numpy import subprocess import multiprocessing as multi import re import csv import string from vtk import * from libvtkTAG2ECommonPython import * from libvtkTAG2EFilteringPython import * from libvtkGRASSBridgeIOPython import * from libvtkGRASSBridgeCommonPython import * from libvtkGRASSBridgeRSpaceTimePython import * #from libvtkGRASSBridgeTemporalPython import * import MetaModel workers = multi.cpu_count() def ParameterXMLRange(input, weightfactor = 'None'): # Import model XML description file and create dictionary with model parameters # and their specific max and min values. fuzzyxml = open(input, 'r') fuzzylist = fuzzyxml.read() fuzzyxml.close() fuzzymodel = vtkXMLUtilities.ReadElementFromString(fuzzylist) element_number = fuzzymodel.GetNumberOfNestedElements() factor_dict = {} if weightfactor == 'None': for i in range(element_number - 1): element = fuzzymodel.GetNestedElement(i) element_name = element.GetAttribute('name') element_max = element.GetAttribute('max') element_min = element.GetAttribute('min') factor_dict[element_name] = [element_max,element_min] else: models = fuzzymodel.GetNestedElement(1) element_number = models.GetNumberOfNestedElements() for i in range(element_number - 1): element = models.GetNestedElement(i) element_name = element.GetAttribute('name') element_max = element.GetAttribute('max') element_min = element.GetAttribute('min') factor_dict[element_name] = [element_max,element_min] return(factor_dict) def ParameterComparisonFlag(index, xmldict, parameters, parameterdict): # Compute flags for validation data qualitiy. # Possibly values: # 0: At least one validation parameter is outside the model calibration # range and no missing values is detected. # 1: Validation parameters are inside the model calibration range and no # missing values are detected. # 2: At least one validation parameter is a missing values and no outliers # are detected. # 3: At least one validation parameter is a missing values and one outlier # is detected. parameter_list = parameters.split(',') flag_list = [] for para in parameter_list: max = float(xmldict[para][0]) min = float(xmldict[para][1]) values = parameterdict[index] para_index = parameter_list.index(para) value_index = float(values[para_index]) if (value_index > max or value_index < min) and value_index != 9999: flag = 0 elif value_index == 9999: flag = 2 else: flag = 1 flag_list.append(flag) outlier_values = sum(i < 1 for i in flag_list) missing_values = sum(i > 1 for i in flag_list) if missing_values == 0 and outlier_values != 0: validation_flag = 0 elif missing_values != 0 and outlier_values == 0: validation_flag = 2 elif missing_values != 0 and outlier_values != 0: validation_flag = 3 else: validation_flag = 1 return(validation_flag) #m.fuzzy.validation input=moorprojekt_ghg_europe_ecad splitfactor=landuse target=n2oaverage parameters=wt,cn20,ninput,tg_annual fuzzysets=3,2,2,3 iterations=1000 ensembles=2 -e #m.fuzzy.validation input=moorprojekt_ghg_europe_ecad_weight splitfactor=landuse target=n2oaverage parameters=wt,cn20,ninput,tg_annual fuzzysets=3,2,2,3 iterations=1000 ensembles=2 -e def MonteCarloSim(key, parameters, parametername, resultvalidationdictpara, uncertainties, na_value = 9999, weightfactor = 'None', weightnum = 0): # Application of Monte Carlo Simulation for uncertainty estimation of model results. # Set up dummy data points to select object type. points = vtkPoints() for i in range(5): for j in range(5): points.InsertNextPoint(i, j, 0) data = vtkDoubleArray() data.SetNumberOfTuples(25) data.SetName("data") data.FillComponent(0,3) ds = vtkPolyData() ds.Allocate(5,5) ds.GetPointData().SetScalars(data) ds.SetPoints(points) # Import fuzzy model XML representation file as object. fuzzyxml = open(parametername, 'r') fuzzylist = fuzzyxml.read() fuzzyxml.close() fuzzymodel = vtkXMLUtilities.ReadElementFromString(fuzzylist) if weightfactor == 'None': fisc = vtkTAG2EFuzzyInferenceModelParameter() fisc.SetXMLRepresentation(fuzzymodel) model = vtkTAG2EFuzzyInferenceModel() model.SetModelParameter(fisc) else: fisc = vtkTAG2EFuzzyInferenceModelParameter() weight = vtkTAG2EWeightingModelParameter() weight_model = fuzzymodel.GetNestedElement(0) weight_model.GetName() fisc_model = fuzzymodel.GetNestedElement(1) fisc_model.GetName() fisc.SetXMLRepresentation(fisc_model) weight.SetXMLRepresentation(weight_model) model = vtkTAG2EFuzzyInferenceModel() model.SetModelParameter(fisc) modelW = vtkTAG2EWeightingModel() modelW.SetModelParameter(weight) meta = MetaModel.MetaModel() meta.InsertModelParameter(model, fisc_model, "vtkTAG2EFuzzyInferenceModel") meta.InsertModelParameter(modelW, weight, "vtkTAG2EWeightingModel") meta.SetLastModelParameterInPipeline(modelW, weight, "vtkTAG2EWeightingModel") # Split parameter list. parameter_list = parameters.split(',') # Split parameter list. uncertainties_list = uncertainties.split(',') if len(uncertainties) != 0: [float(i) for i in uncertainties_list] para_num = resultvalidationdictpara[key] # Compute means, median, standard deviation for model parameters. para_mean = list() para_median = list() para_sd = list() para_val = resultvalidationdictpara.values() para_list = [list([float(i) for i in item]) for item in para_val] para_split = zip(*para_list) para_split_narem = [[i for i in list(item) if i != na_value] for item in para_split] for i in para_split_narem: para_mean.append(numpy.mean(i)) para_median.append(numpy.median(i)) para_sd.append(numpy.std(i)) # Create data distribution xml representation file. root = vtk.vtkXMLDataElement() root.SetName("DataDistributionDescription") root.SetAttribute("xmlns", "http://tag2e.googlecode.com/files/DataDistributionDescription") root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") root.SetAttribute("xsi:schemaLocation", "http://tag2e.googlecode.com/files/DataDistributionDescription http://tag2e.googlecode.com/files/DataDistributionDescription.xsd") root.SetAttribute("name", "Simulation") for para in parameter_list: para_index = parameter_list.index(para) dfn = vtkXMLDataElement() dfn.SetName("Norm") if (float(para_num[para_index]) == na_value): mean_val = para_mean[para_index] if len(uncertainties) != 0: sd_val = float(uncertainties_list[para_index]) else: sd_val = para_sd[para_index] else: mean_val = float(para_num[para_index]) if len(uncertainties) != 0: sd_val = float(uncertainties_list[para_index]) else: sd_val = para_sd[para_index] dfn.SetDoubleAttribute("mean", mean_val) dfn.SetDoubleAttribute("sd", sd_val) varn = vtkXMLDataElement() varn.SetName("Variable") varn.SetAttribute("name", para) varn.SetAttribute("type", "norm") varn.AddNestedElement(dfn) root.AddNestedElement(varn) if weightfactor != 'None': dfn = vtkXMLDataElement() dfn.SetName("Unif") dfn.SetDoubleAttribute("min", int(weightnum)) dfn.SetDoubleAttribute("max", int(weightnum)) varn = vtkXMLDataElement() varn.SetName("Variable") varn.SetAttribute("name", str(weightfactor)) varn.SetAttribute("type", "unif") varn.AddNestedElement(dfn) root.AddNestedElement(varn) # Create data distribution xml file. ddd = vtkTAG2EAbstractModelParameter() ddd.SetFileName("/tmp/MCWFISSimpleDataDistributionDescription1.xml") ddd.SetXMLRepresentation(root) ddd.Write() # Create Monte Carlo analyser object. analyser = vtkTAG2EModelMonteCarloVariationAnalyser() analyser.SetDataDistributionDescription(ddd) analyser.SetModel(model) analyser.SetNumberOfRandomValues(1000) analyser.SetMaxNumberOfIterations(2000) analyser.SetBreakCriterion(0.001) analyser.SetInput(ds) analyser.Update() output = analyser.GetOutput() output_range = output.GetFieldData().GetArray(model.GetResultArrayName()).GetRange() output_min = output_range[0] output_max = output_range[1] # Create R interface. riface = vtkRInterfaceSpatial() riface.AssignVTKDataArrayToRVariable(output.GetFieldData().\ GetArray(model.GetResultArrayName()), model.GetResultArrayName()) # Save the workspace for testing script = "quant <- quantile(result,c(0, 0.05, 0.25, 0.5, 0.75, 0.95, 1))" #print script riface.EvalRscript(script, True) result = riface.AssignRVariableToVTKDataArray("quant") result_array = list() for i in range(7): result_array.append(result.GetValue(i)) return(result_array) def crosscalibration(input, inputvector, validation, parameters, uncertainties, target, ensembles, iterations, fuzzysets, weightfactor = 'None', weightnum = 0, mcsim = False, boot = False, samplingfactor = 'None', rulelimit = '20'): resultlistcalibration = [] resultlistvalidation = [] execstringcalibration = '' execstringvalidation = '' resultlistcalibration = {} resultlistvalidation = {} inputtable = grass.read_command('v.db.select', map = input, columns = 'cat', \ flags = 'c', sep= ';') inputtable = re.split('\n',inputtable.strip('\n')) emptyinputdict = {} resultcalibrationdictcomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictcomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictflagscomplete = emptyinputdict.fromkeys(inputtable, []) if mcsim: resultvalidationdictmincomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq05complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq25complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq50complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq75complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq95complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmaxcomplete = emptyinputdict.fromkeys(inputtable, []) resultcalibrationdictmean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmean = emptyinputdict.fromkeys(inputtable, []) resultcalibrationdictsd = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictsd = emptyinputdict.fromkeys(inputtable, []) if mcsim: resultvalidationdictminmean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq05mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq25mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq50mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq75mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq95mean = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmaxmean = emptyinputdict.fromkeys(inputtable, []) calibrationproclist = [] calibrationmodelnproclist = [] validationmodelnproclist = [] proc_count = 0 #Parallel model runs for calibrations for ensemblenum in range(int(ensembles)): parametername = str(inputvector + '_' + str(ensemblenum) + '.xml') logname = str(inputvector + '_' + str(ensemblenum) + '.log') if weightfactor == 'None' and samplingfactor == 'None' and boot == False: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ overwrite = True, rulelimit = rulelimit)) elif weightfactor == 'None' and samplingfactor == 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ overwrite = True, flags = 'b', rulelimit = rulelimit)) elif weightfactor == 'None' and samplingfactor != 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ overwrite = True, samplingfactor = samplingfactor, flags = 'b', \ rulelimit = rulelimit)) elif weightfactor != 'None' and samplingfactor != 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ weightfactor = weightfactor, weightnum = weightnum, \ overwrite = True, samplingfactor = samplingfactor, flags = 'wb', \ rulelimit = rulelimit)) elif weightfactor != 'None' and samplingfactor == 'None' and boot == True: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, log = logname, \ weightfactor = weightfactor, weightnum = weightnum, \ overwrite = True, flags = 'wb', rulelimit = rulelimit)) else: calibrationproclist.append(grass.start_command('v.fuzzy.calibrator', input = inputvector, \ target = target, factors = parameters, iterations = iterations, \ fuzzysets = fuzzysets, parameter = parametername, \ weightfactor = weightfactor, weightnum = weightnum, \ log = logname, overwrite = True, flags = 'w', rulelimit = rulelimit)) proc_count += 1 #check for maximum number of parallel processes defined by cpu count if (proc_count == workers) or (proc_count == int(ensembles)): for process in calibrationproclist: process.wait() #empty process list and reset counter calibrationproclist = [] proc_count = 0 #model evaluation and output dictionary creation for ensembles for ensemblenum in range(int(ensembles)): #set names for output files outputcalibrationname = str(inputvector + '_calibration_' + str(ensemblenum)) outputvalidationname = str(inputvector + '_validation_' + str(ensemblenum)) parametername = str(inputvector + '_' + str(ensemblenum) + '.xml') if weightfactor == 'None': grass.run_command('v.fuzzy.model', input = input, parameter = parametername, \ output = outputcalibrationname, overwrite = True) grass.run_command('v.fuzzy.model', input = validation, parameter = parametername, \ output = outputvalidationname, overwrite = True) else: grass.run_command('v.fuzzy.model', input = input, parameter = parametername, \ output = outputcalibrationname, overwrite = True, flags = 'w') grass.run_command('v.fuzzy.model', input = validation, parameter = parametername, \ output = outputvalidationname, overwrite = True, flags = 'w') resultcalibration = grass.read_command('v.db.select', map = outputcalibrationname, columns = str('cat,result,' + parameters), flags = 'c', sep= ';') resultvalidation = grass.read_command('v.db.select', map = outputvalidationname, columns = str('cat,result,' + parameters), flags = 'c', sep= ';') if weightfactor != 'None': resultweight = grass.read_command('v.db.select', map = outputvalidationname, columns = str('cat,' + weightfactor), flags = 'c', sep= ';') resultweight = re.split('\n|;',resultweight.strip('\n')) resultweightdict = dict(zip(resultweight[::2], resultweight[1::2])) resultcalibration = re.split('\n|;',resultcalibration.strip('\n')) resultvalidation = re.split('\n|;',resultvalidation.strip('\n')) var_dist = 2 + len(parameters.split(',')) parameter_validation = [] for i in range(2, var_dist): parameter_validation.append(resultcalibration[i::var_dist]) parameter_validation = zip(*parameter_validation) resultcalibrationdict = dict(zip(resultcalibration[::var_dist], resultcalibration[1::var_dist])) resultvalidationdict = dict(zip(resultvalidation[::var_dist], resultvalidation[1::var_dist])) resultvalidationdictpara = dict(zip(resultcalibration[::var_dist], parameter_validation)) factor_dict = ParameterXMLRange(parametername, weightfactor) for l in resultcalibrationdict: resultcalibrationdictcomplete[l] = resultcalibrationdictcomplete[l] + [resultcalibrationdict[l]] {i:j for i,j in resultcalibrationdictcomplete.items() if j != []} for l in resultvalidationdict: resultvalidationdictcomplete[l] = resultvalidationdictcomplete[l] + [resultvalidationdict[l]] validation_flag = ParameterComparisonFlag(l, factor_dict, parameters, resultvalidationdictpara) validation_flag_dict = {l:validation_flag} resultvalidationdictflagscomplete[l] = resultvalidationdictflagscomplete[l] + [validation_flag_dict[l]] if mcsim: if weightfactor == 'None': mc_result = MonteCarloSim(l, parameters, parametername, resultvalidationdictpara, uncertainties) else: mc_result = MonteCarloSim(l, parameters, parametername, resultvalidationdictpara, uncertainties, weightfactor = weightfactor, weightnum = resultweightdict[l]) validation_min_dict = {l:mc_result[0]} validation_q05_dict = {l:mc_result[1]} validation_q25_dict = {l:mc_result[2]} validation_q50_dict = {l:mc_result[3]} validation_q75_dict = {l:mc_result[4]} validation_q95_dict = {l:mc_result[5]} validation_max_dict = {l:mc_result[6]} resultvalidationdictmincomplete[l] = resultvalidationdictmincomplete[l] + [validation_min_dict[l]] resultvalidationdictq05complete[l] = resultvalidationdictq05complete[l] + [validation_q05_dict[l]] resultvalidationdictq25complete[l] = resultvalidationdictq25complete[l] + [validation_q25_dict[l]] resultvalidationdictq50complete[l] = resultvalidationdictq50complete[l] + [validation_q50_dict[l]] resultvalidationdictq75complete[l] = resultvalidationdictq75complete[l] + [validation_q75_dict[l]] resultvalidationdictq95complete[l] = resultvalidationdictq95complete[l] + [validation_q95_dict[l]] resultvalidationdictmaxcomplete[l] = resultvalidationdictmaxcomplete[l] + [validation_max_dict[l]] {i:j for i,j in resultvalidationdictcomplete.items() if j != []} resultvalidationdictflagscomplete = {i:j for i,j in resultvalidationdictflagscomplete.items() if j != []} if mcsim: resultvalidationdictmincomplete = {i:j for i,j in resultvalidationdictmincomplete.items() if j != []} resultvalidationdictq05complete = {i:j for i,j in resultvalidationdictq05complete.items() if j != []} resultvalidationdictq25complete = {i:j for i,j in resultvalidationdictq25complete.items() if j != []} resultvalidationdictq50complete = {i:j for i,j in resultvalidationdictq50complete.items() if j != []} resultvalidationdictq75complete = {i:j for i,j in resultvalidationdictq75complete.items() if j != []} resultvalidationdictq95complete = {i:j for i,j in resultvalidationdictq95complete.items() if j != []} resultvalidationdictmaxcomplete = {i:j for i,j in resultvalidationdictmaxcomplete.items() if j != []} # Create dicionaries with mean calibration and mean, min and max validation model result values. for j in resultcalibrationdictcomplete: resultcalibrationdictmean[j] = resultcalibrationdictmean[j] + [numpy.mean(map(float,resultcalibrationdictcomplete[j]))] for j in resultvalidationdictcomplete: resultvalidationdictmean[j] = resultvalidationdictmean[j] + [numpy.mean(map(float,resultvalidationdictcomplete[j]))] for j in resultcalibrationdictcomplete: resultcalibrationdictsd[j] = resultcalibrationdictsd[j] + [numpy.std(map(float,resultcalibrationdictcomplete[j]))] for j in resultvalidationdictcomplete: resultvalidationdictsd[j] = resultvalidationdictsd[j] + [numpy.std(map(float,resultvalidationdictcomplete[j]))] if mcsim: for j in resultvalidationdictmincomplete: resultvalidationdictminmean[j] = resultvalidationdictminmean[j] + [numpy.min(map(float,resultvalidationdictmincomplete[j]))] for j in resultvalidationdictq05complete: resultvalidationdictq05mean[j] = resultvalidationdictq05mean[j] + [numpy.mean(map(float,resultvalidationdictq05complete[j]))] for j in resultvalidationdictq25complete: resultvalidationdictq25mean[j] = resultvalidationdictq25mean[j] + [numpy.mean(map(float,resultvalidationdictq25complete[j]))] for j in resultvalidationdictq50complete: resultvalidationdictq50mean[j] = resultvalidationdictq50mean[j] + [numpy.mean(map(float,resultvalidationdictq50complete[j]))] for j in resultvalidationdictq75complete: resultvalidationdictq75mean[j] = resultvalidationdictq75mean[j] + [numpy.mean(map(float,resultvalidationdictq75complete[j]))] for j in resultvalidationdictq95complete: resultvalidationdictq95mean[j] = resultvalidationdictq95mean[j] + [numpy.mean(map(float,resultvalidationdictq95complete[j]))] for j in resultvalidationdictmaxcomplete: resultvalidationdictmaxmean[j] = resultvalidationdictmaxmean[j] + [numpy.max(map(float,resultvalidationdictmaxcomplete[j]))] # Remove emtpy values from dictionaries {i:j for i,j in resultcalibrationdictmean.items() if j != []} {i:j for i,j in resultvalidationdictmean.items() if j != []} {i:j for i,j in resultcalibrationdictsd.items() if j != []} {i:j for i,j in resultvalidationdictsd.items() if j != 0.} if mcsim: {i:j for i,j in resultvalidationdictminmean.items() if j != []} {i:j for i,j in resultvalidationdictq05mean.items() if j != []} {i:j for i,j in resultvalidationdictq25mean.items() if j != []} {i:j for i,j in resultvalidationdictq50mean.items() if j != []} {i:j for i,j in resultvalidationdictq75mean.items() if j != []} {i:j for i,j in resultvalidationdictq95mean.items() if j != []} {i:j for i,j in resultvalidationdictmaxmean.items() if j != []} if mcsim: return(resultcalibrationdictcomplete, resultvalidationdictcomplete, resultcalibrationdictmean, resultvalidationdictmean, resultvalidationdictsd, resultvalidationdictflagscomplete, resultvalidationdictminmean, resultvalidationdictq05mean, resultvalidationdictq25mean, resultvalidationdictq50mean, resultvalidationdictq75mean, resultvalidationdictq95mean, resultvalidationdictmaxmean) else: return(resultcalibrationdictcomplete, resultvalidationdictcomplete, resultcalibrationdictmean, resultvalidationdictmean, resultvalidationdictsd, resultvalidationdictflagscomplete) def transformfactorweighting(input, weightfactor): # Get list of weights from vector column, transformation to numerical values weightfactorlist = grass.read_command('v.db.select', map = input, columns = weightfactor, flags = 'c') weightfactorlist = weightfactorlist.rstrip('\n').split('\n') weightfactorkeylist = dict.fromkeys(weightfactorlist).keys() weightiternum = range(len(weightfactorkeylist)) weightfactorkeydict = dict(zip(weightfactorkeylist, weightiternum)) #add numerical values of weighting factor as new column to vector table weightfactorcolumnname = str(weightfactor + '_num') grass.run_command('v.db.addcolumn', map = input, columns = str(weightfactorcolumnname + ' double precision')) for weightfactorkey in weightfactorkeylist: cmd = "UPDATE %s SET %s=%s WHERE %s='%s'" % (input, weightfactorcolumnname, weightfactorkeydict[weightfactorkey],weightfactor, weightfactorkey) grass.write_command('db.execute', input = '-', stdin = cmd) return(weightfactorcolumnname, weightiternum) def splitvectordata(input, splitfactor): splitfactorlist = grass.read_command('v.db.select', map = input, columns = splitfactor, flags = 'c') splitfactorlist = splitfactorlist.rstrip('\n').split('\n') splitfactorkeylist = dict.fromkeys(splitfactorlist).keys() splitvectorlist =[] excludedvectorlist =[] splitcount = 0 for splitfactorname in splitfactorkeylist: grass.run_command('v.extract', input = input, output = str(input + '_' + str(splitcount)), overwrite = True, where = str(splitfactor + " != '" + splitfactorname + "'")) grass.run_command('v.extract', input = input, output = str(input + '_' + str(splitcount) + '_extract'), overwrite = True, where = str(splitfactor + " = '" + splitfactorname + "'")) splitvectorlist.append(str(input + '_' + str(splitcount))) excludedvectorlist.append(str(input + '_' + str(splitcount) + '_extract')) splitcount += 1 return(splitvectorlist,excludedvectorlist) #extraction and visualisation of parameters for the fuzzysets of calibrated ensembles and def xmlparse(vinputfile, ensemblenum): reader = vtk.vtkXMLDataParser() xmlstringall = [] for i in range(int(ensemblenum)): reader.SetFileName(str(vinputfile + '_' + str(i) + '.xml')) reader.Parse() xmltable = [] root = reader.GetRootElement() if root.GetName() == "FuzzyInferenceScheme": elenum = root.GetNumberOfNestedElements() for e in range(0,elenum,1): element = root.GetNestedElement(e) if element.GetName() == 'Factor': setnum = element.GetNumberOfNestedElements() for s in range(0,setnum): set = element.GetNestedElement(s) if set.GetAttribute('type') == 'Triangular': trianglenum = set.GetNumberOfNestedElements() triangle = set.GetNestedElement(0) xmldict = {} xmldict['ensemble'] = str(i) xmldict['factor'] = element.GetAttribute('name') xmldict['min'] = element.GetAttribute('min') xmldict['max'] = element.GetAttribute('max') xmldict['set'] = set.GetAttribute('position') xmldict['center'] = triangle.GetAttribute('center') xmldict['left'] = triangle.GetAttribute('left') xmldict['right'] = triangle.GetAttribute('right') xmltable.append(xmldict) xmlstring = [] xmlstring.append(string.join(xmltable[0].keys(),',')) if i == 0: xmlstringall.append(string.join(xmltable[0].keys(),',')) for data in xmltable: xmlstring.append(string.join(data.values(),',')) xmlstringall.append(string.join(data.values(),',')) xmlstringfinal = string.join(xmlstringall,'\n') #print(xmlstringfinal) file = open(str('/tmp/' + vinputfile + '_fuzzysets' + '.txt'),'w') file.write(xmlstringfinal) file.close() # Run R visualise the fuzzy sets auomtatically and store the result in pdf file RScript = """ PlotFuzzysets <- function(input, dir = '/tmp/') { # Plot Fuzzysets imported from XML Fuzzy Interference Scheme created by TAG2E. # An PDF document will be created. # # args: # input: Name of input text file created by m.fuzzy.validation, containing # fuzzy set positions. # dir: Name of directory containing input file. Default is /tmp. # Import input file. data = read.csv(file = paste(dir, input, sep = ''), header = TRUE, sep = ",") # Get number of factors. factor_amount <- length(levels(data$factor)) # Create pdf document. pdf(file = paste(substr(input, 1, nchar(input) - 4), ".pdf", sep = ''), width = 12, height = 8) par(lwd = 2, cex = 1.5, mar = c(5, 5, 5, 5)) # Loop through fuzzy sets for different factors. for (f in 1:length(levels(data$factor))) { # Create subset for each factor. setfactor = levels(data$factor)[f] set = subset(data,factor == setfactor) # Compute fuzzy set amount and position statistics for ensembles. factor_length <- nrow(subset(set, ensemble == 0, select = set)) factor_labels <- subset(set, ensemble == 0, select = set)[,1] center_labels <- subset(set, ensemble == 0, select = center)[,1] maximum <- max(set$max) minimum <- max(set$min) if (factor_length == 2) { plot(1, type='n', ylim = c(0,1), xlim = c(minimum, maximum), xlab = paste(setfactor), ylab = "Membership grade", main = paste('Fuzzysets for Factor ', setfactor)) axis(side = 3, labels = factor_labels, at = center_labels, cex.axis = 1, tick = FALSE) for ( i in seq(0, max(set$ensemble))) { center_sub <- as.vector(subset(set, ensemble == i, select = center)) right_sub <- subset(set, ensemble == i, select = right) left_sub <- subset(set, ensemble == i, select = left) segments(center_sub[1, 1], 1, center_sub[1, 1] + right_sub[1, 1], 0, col = 'blue') segments(minimum, 1, center_sub[1, 1], 1, col = 'blue') segments(center_sub[1, 1] + right_sub[1, 1], 0, maximum, 0, col = 'blue') segments(center_sub[2, 1] - left_sub[2, 1], 0, minimum, 0, col = 'green') segments(center_sub[2, 1] - left_sub[2, 1], 0, center_sub[2, 1], 1, col = 'green') segments(center_sub[2, 1], 1, maximum, 1, col = 'green') } } else if (factor_length == 3) { plot(1, type='n', ylim = c(0, 1), xlim = c(minimum, maximum), xlab = paste(setfactor), ylab = "Membership grade", main = paste('Fuzzysets for Factor ', setfactor)) axis(side = 3, labels = factor_labels, at = center_labels, cex.axis = 1, tick = FALSE) for ( i in seq(0, max(set$ensemble))) { center_sub <- subset(set, ensemble == i, select = center) right_sub <- subset(set, ensemble == i, select = right) left_sub <- subset(set, ensemble == i, select = left) segments(center_sub[1, 1], 1, center_sub[1, 1] + right_sub[1, 1], 0, col = 'blue') segments(minimum, 1, center_sub[1, 1], 1, col = 'blue') segments(center_sub[1, 1] + right_sub[1, 1], 0, maximum, 0, col = 'blue') segments(minimum, 0, center_sub[2, 1] - left_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] - left_sub[2, 1], 0, center_sub[2, 1], 1, col = 'red') segments(center_sub[2, 1], 1, center_sub[2, 1] + right_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] + right_sub[2, 1], 0, maximum, 0, col = 'red') segments(center_sub[3, 1] - left_sub[3, 1], 0, minimum, 0, col = 'green') segments(center_sub[3, 1] - left_sub[3, 1], 0, center_sub[3, 1], 1, col = 'green') segments(center_sub[3, 1], 1, maximum, 1, col = 'green') } } else if (factor_length == 4) { plot(1, type='n', ylim = c(0, 1), xlim = c(minimum, maximum), xlab = paste(setfactor), ylab = "Membership grade", main = paste('Fuzzysets for Factor ', setfactor)) axis(side = 3, labels = factor_labels, at = center_labels, cex.axis = 1, tick = FALSE) for ( i in seq(0, max(set$ensemble))) { center_sub <- subset(set, ensemble == i, select = center) right_sub <- subset(set, ensemble == i, select = right) left_sub <- subset(set, ensemble == i, select = left) segments(center_sub[1, 1], 1, center_sub[1, 1] + right_sub[1, 1], 0, col = 'blue') segments(minimum, 1, center_sub[1, 1], 1, col = 'blue') segments(center_sub[1, 1] + right_sub[1, 1], 0, maximum, 0, col = 'blue') segments(minimum, 0, center_sub[2, 1] - left_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] - left_sub[2, 1], 0, center_sub[2, 1], 1, col = 'red') segments(center_sub[2, 1], 1, center_sub[2, 1] + right_sub[2, 1], 0, col = 'red') segments(center_sub[2, 1] + right_sub[2, 1], 0, maximum, 0, col = 'red') segments(center_sub[3, 1] - left_sub[3, 1], 0, center_sub[3, 1], 1, col = 'black') segments(center_sub[3, 1], 1, center_sub[3, 1] + right_sub[3, 1], 0, col = 'black') segments(center_sub[3, 1] + right_sub[3, 1], 0, maximum, 0, col = 'black') segments(center_sub[4, 1] - left_sub[4, 1], 0, minimum, 0, col = 'green') segments(center_sub[4, 1] - left_sub[4, 1], 0, center_sub[4, 1], 1, col = 'green') segments(center_sub[4, 1], 1, maximum, 1, col = 'green') } } } dev.off() } PlotFuzzysets(input = "inputfilename") """ RScript = RScript.replace("inputfilename", str(vinputfile + '_fuzzysets' + '.txt')) inputlist = ["R", "--vanilla"] proc = subprocess.Popen(args=inputlist, stdin=subprocess.PIPE) proc.stdin.write(RScript) proc.communicate() def ValidationPlot(input, target, montecarloflag, parainput): RScript = """ ## Script for evaluating cross validation of fuzzy model. require(Hmisc) # Function to calculate rsquared for two vector list elements (x,y) rsquaredcalc <- function(x, y){ # Compute coefficient of determination. totalsumofsquares = sum((x - mean(x))^2) residualsumofsquares = sum((x - y)^2) rsquared = 1 - residualsumofsquares / totalsumofsquares return(rsquared) } EvalFuzzyValidation <- function(file.name, target, parameters, file.dir = getwd(), missing = TRUE, outlier = TRUE, na.value = 9999, montecarlo = TRUE) { # Import valdiation file created by m.fuzzy.validation(fmta) and create # calibration and valdiation plots. # # args: # file.name: Name of m.fuzzy.validation result file. # target: Column name of target variable in crossvalidation. # parameters: Name of the parameters used for model calibration. # file.dir: Path to directory containing file.name. # missing: Boolean if missing values should be included. Default is TRUE. # outlier: Boolean if outlier for calibration range should be colored. # Default is TRUE. # na.value: Value used as no data representation. # montecarlo: Boolean if montecarlo simulation flag is set. Default is TRUE. # Import m.fuzzy.validation result file. file.location <- paste(file.dir, '/', file.name, sep = '') validata = read.csv(file.location, header = T, sep = ",") # Processing data formats. validata[validata == na.value] = NA # Check if NA values should be excluded. if (missing == FALSE) validata = na.omit(validata) # Set axis label names for output graphics. ylabname <- expression(paste(N[2],'O-N in [g' %.% m^-2 %.% a^-1, ']', sep = '')) #target <- 'n2oaverage_flux' xlab <- expression(paste('Measured ', N[2],'O-N in [g' %.% m^-2 %.% a^-1, ']', sep = '')) ylab <- expression(paste('Modelled ', N[2],'O-N in [g' %.% m^-2 %.% a^-1, ']', sep = '')) if (!is.vector(validata[[target]])) { target <- 'n2oaverage_log' xlab <- expression(paste('Measured ', N[2],'O-N in log [g' %.% m^-2 %.% a^-1, ']', sep = '')) ylab <- expression(paste('Modelled ', N[2],'O-N in log [g' %.% m^-2 %.% a^-1, ']', sep = '')) } vali.title <- "Flux Validation Plot" cali.title <- "Flux Calibration Plot" axis.lim <- range(validata[[target]]) leg.factors <- levels(as.factor(validata$flag_0)) # Set color palette for plotting. if (outlier) { palette(c("orange", "black", "grey", "red")) } else { palette(c("black", "black")) } if (missing) { plot_val_name <- 'Validation_all_' } else { palette(c("black", "black")) plot_val_name <- 'Validation_narm_' } #figure.dir <- "./figures/" figure.dir <- file.dir valicolor = factor(validata$flag_0, levels = c("0", "1", "2", "3")) # Create validation plot. pdf(file = paste(figure.dir, '/', plot_val_name, nrow(validata), '_', Sys.Date(), '.pdf', sep = '')) par(mar = c(5, 5, 4, 2), bty = 'o', tck = 0.01, cex.axis = 1.25, cex.lab = 1.25, cex.main = 1.25, cex = 1.25, lwd = 1.25, pch = 20, las = 1) plot(validata[[target]], validata$validation_mean, ylab = ylab, xlab = xlab, xlim = axis.lim, ylim = axis.lim, col = valicolor, cex = 1, main = vali.title) errbar(x= validata[[target]], y = validata$validation_mean, yplus = validata$validation_mean + validata$validation_sd, yminus = validata$validation_mean - validata$validation_sd, add = T, pch = 20, col = valicolor) mtext(paste('Direct comparison NSE: ', round(rsquaredcalc(validata[[target]], validata$validation_mean), 2))) abline(0, 1) if (missing & outlier) { legend(axis.lim[1], axis.lim[2], c("Outlier", "Valide", "Missing", "Missing + Outlier") , col = c("orange", "black", "grey", "red"), pch = 20) } else if (outlier) { legend(axis.lim[1], axis.lim[2], c("Outlier", "Valide") , col = c("orange", "black"), pch = 20) } dev.off() # Set color palette for plotting. if (missing) { palette(c("black", "grey")) plot_cal_name <- 'Calibration_all_' } else { palette(c("black", "black")) plot_cal_name <- 'Calibration_narm_' } calicol <- grep(substr(file.name, 1, nchar(file.name) - 22), names(validata)) calidata <- sapply(validata[calicol], function(x) x != validata[2]) if (sum(calidata) != 0) { calimean <- rowMeans(validata[calicol][calidata[1, ]]) calisd <- apply(validata[calicol][calidata[1, ]], MAR = 1, sd) } else { calimean <- rowMeans(validata[calicol]) calisd <- apply(validata[calicol], MAR=1, function(x) x = 0) } # Create calibration plot. pdf(file = paste(figure.dir, '/', plot_cal_name, nrow(validata), '_', Sys.Date(), '.pdf', sep = '')) par(mar = c(5, 5, 4, 2), bty = 'o', tck = 0.01, cex.axis = 1.25, cex.lab = 1.25, cex.main = 1.25, cex = 1.25, lwd = 1.25, pch = 20, las = 1) plot(validata[[target]], calimean, ylab = ylab, xlab = xlab, xlim = axis.lim, ylim = axis.lim, col = as.factor(validata$flag_0 == 2 | validata$flag_0 == 3 ), cex = 1, main = cali.title) errbar(x= validata[[target]], y = calimean, yplus = calimean + calisd, yminus = calimean - calisd, add = T, pch = 20, col = as.factor(validata$flag_0 == 2 | validata$flag_0 == 3 )) mtext(paste('Direct comparison NSE: ', round(rsquaredcalc(validata[[target]], calimean), 2))) abline(0, 1) if (missing) { legend(axis.lim[1], axis.lim[2], c("Valide", "Missing"), col = c("black", "grey"), pch = 20) } dev.off() # Create Monte Carlo simulation plots for all parameters and outcome. if (montecarlo) { paralist <- strsplit(parameters,',') paralist <- c(unlist(paralist), target) for (element in paralist) { # Sort data frame by parameter. validata_sort <- validata[order(validata[[element]]), ] validata_sort = na.omit(validata_sort) plot_mc_name <- paste('MC_result_', element, '_', sep = '') mc.title <- "Monte Carlo Simulation Plot" para.lim <- range(validata_sort[[element]]) if (element == target) paralab <- xlab else paralab <- element # Create parameter plot. pdf(file = paste(figure.dir, '/', plot_mc_name, nrow(validata_sort), '_', Sys.Date(), '.pdf', sep = '')) par(mar = c(5, 5, 4, 2), bty = 'o', tck = 0.01, cex.axis = 1.25, cex.lab = 1.25, cex.main = 1.25, cex = 1.25, lwd = 1.25, pch = 20, las = 1) plot(validata_sort[[element]], validata_sort$q50, type = 'n', ylim = axis.lim, ylab = ylab, xlim = para.lim, xlab = paralab, pch = 20, cex = 0.5, main = mc.title) polygon(x = c(validata_sort[[element]], rev(validata_sort[[element]])), y = c(validata_sort$q95, rev(validata_sort$q5)), col = 'grey', border = "white") lines(validata_sort[[element]], validata_sort$q50, lwd = 2) #with(validata_sort, errbar(x = validata_sort[[element]], y = q50, yplus = q75, # yminus = q25, add = T, type = 'n', lwd = 1)) dev.off() } } } if (as.numeric(montesim) == 1) { EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput") EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput", missing = F, outlier = F) } else { EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput", montecarlo = F) EvalFuzzyValidation(file.name = "inputfilename", target = "targetname", parameters = "parainput", missing = F, outlier = F, montecarlo = F) } """ RScript = RScript.replace("inputfilename", str(input + '_validation_result.csv')) RScript = RScript.replace("targetname", str(target)) RScript = RScript.replace("parainput", str(parainput)) if montecarloflag: RScript = RScript.replace("montesim", "1") else: RScript = RScript.replace("montesim", "0") inputlist = ["R", "--vanilla"] proc = subprocess.Popen(args=inputlist, stdin=subprocess.PIPE) proc.stdin.write(RScript) proc.communicate() def main(): input = options['input'] output = options['output'] target = options['target'] weightfactor = options['weightfactor'] splitfactor = options['splitfactor'] samplingfactor = options['samplingfactor'] parameters = options['parameters'] uncertainties = options['uncertainties'] ensembles = options['ensembles'] iterations = options['iterations'] fuzzysets = options['fuzzysets'] allparameterflag = flags['a'] bootflag = flags['b'] splitfactorflag = flags['e'] categoricalflag = flags['c'] weightingflag = flags['w'] montecarloflag = flags['m'] inputrule = options['rulelimit'] if montecarloflag: if len(parameters.split(',')) != len(uncertainties.split(',')) \ and len(uncertainties) != 0: print("ERROR: Parameter and Uncertainty length differs") sys.exit() if splitfactorflag: splitvectorinputlist, splitvectorexcludedlist = splitvectordata(input, splitfactor) else: splitvectorinputlist = list() splitvectorinputlist.append(input) splitvectorexcludedlist = list() splitvectorexcludedlist.append(input) if weightingflag: if categoricalflag: weightfactorcolumnname, weightiternum = transformfactorweighting(input, weightfactor) else: weightfactorcolumnname = weightfactor weightfactorlist = grass.read_command('v.db.select', map = input, columns = weightfactor, flags = 'c') weightfactorlist = weightfactorlist.rstrip('\n').split('\n') weightfactorkeylist = dict.fromkeys(weightfactorlist).keys() weightiternum = len(weightfactorkeylist) #splitvectorinputlist = ','.join(splitvectorinputlist) #splitvectorexcludedlist = ','.join(splitvectorexcludedlist) #create empty dictionaries with list items and vector input category keys inputtable = grass.read_command('v.db.select', map = input, columns = 'cat', flags = 'c', sep= ';') inputtable = re.split('\n',inputtable.strip('\n')) emptyinputdict = {} calibrationresultlistcomplete = emptyinputdict.fromkeys(inputtable, []) validationresultlistcomplete = emptyinputdict.fromkeys(inputtable, []) validationresultsdcomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictflagscomplete = emptyinputdict.fromkeys(inputtable, []) if montecarloflag: resultvalidationdictmincomplete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq05complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq25complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq50complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq75complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictq95complete = emptyinputdict.fromkeys(inputtable, []) resultvalidationdictmaxcomplete = emptyinputdict.fromkeys(inputtable, []) calibrationresultmeanlistcomplete = emptyinputdict.fromkeys(inputtable, []) parameterdictcomplete = emptyinputdict.fromkeys(inputtable, []) targettable = grass.read_command('v.db.select', map = input, columns = str('cat,' + target), flags = 'c', sep= ';') targettable = re.split('\n|;',targettable.strip('\n')) targetdict = dict(zip(targettable[::2],targettable[1::2])) if splitfactorflag: splitfactortable = grass.read_command('v.db.select', map = input, columns = str('cat,' + splitfactor), flags = 'c', sep= ';') splitfactortable = re.split('\n|;',splitfactortable.strip('\n')) splitfactordict = dict(zip(splitfactortable[::2],splitfactortable[1::2])) for l in targetdict: parameterdictcomplete[l] = parameterdictcomplete[l] + [targetdict[l]] + [splitfactordict[l]] else: for l in targetdict: parameterdictcomplete[l] = parameterdictcomplete[l] + [targetdict[l]] parameternamelist = parameters.split(',') colnum = len(parameternamelist) for parameter in parameternamelist: parametertable = grass.read_command('v.db.select', map = input, columns = str('cat,' + parameter), flags = 'c', sep= ';') parametertable = re.split('\n|;',parametertable.strip('\n')) parameterdict = dict(zip(parametertable[::2],parametertable[1::2])) for l in parameterdict: parameterdictcomplete[l] = parameterdictcomplete[l] + [parameterdict[l]] calibrationnamecomplete = [] for inputvector in splitvectorinputlist: if splitfactorflag: excludedvector = str(inputvector + '_extract') else: excludedvector = inputvector calibrationnamecomplete.append(inputvector) if weightfactor == 'None' and montecarloflag: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, resultvalidationdictmin, \ resultvalidationdictq05, resultvalidationdictq25, resultvalidationdictq50, \ resultvalidationdictq75, resultvalidationdictq95, resultvalidationdictmax \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, mcsim = True, boot = bootflag, \ samplingfactor = samplingfactor, rulelimit = inputrule) elif weightfactor == 'None' and montecarloflag == False: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, mcsim = False, boot = bootflag, \ samplingfactor = samplingfactor, rulelimit = inputrule) elif weightfactor != 'None' and montecarloflag: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, resultvalidationdictmin, \ resultvalidationdictq05, resultvalidationdictq25, resultvalidationdictq50, \ resultvalidationdictq75, resultvalidationdictq95, resultvalidationdictmax \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, weightfactorcolumnname, weightiternum, \ mcsim = True, boot = bootflag, samplingfactor = samplingfactor, rulelimit = inputrule) else: calibrationresultdict, validationresultdict, calibrationresultmeandict, validationresultmeandict, \ validationresultsddict, resultvalidationdictflags, \ = crosscalibration(input, inputvector, excludedvector, parameters, uncertainties, \ target, ensembles, iterations, fuzzysets, weightfactorcolumnname, weightiternum, \ mcsim = False, boot = bootflag, samplingfactor = samplingfactor, rulelimit = inputrule) # Create Fuzzyset plots. xmlparse(inputvector, ensembles) for l in calibrationresultmeandict: calibrationresultmeanlistcomplete[l] = calibrationresultmeanlistcomplete[l] + [calibrationresultmeandict[l]] for l in validationresultmeandict: validationresultlistcomplete[l] = validationresultlistcomplete[l] + [validationresultmeandict[l]] for l in validationresultsddict: validationresultsdcomplete[l] = validationresultsdcomplete[l] + [validationresultsddict[l]] for l in resultvalidationdictflags: resultvalidationdictflagscomplete[l] = resultvalidationdictflagscomplete[l] + resultvalidationdictflags[l] if montecarloflag: for l in resultvalidationdictmin: resultvalidationdictmincomplete[l] = resultvalidationdictmincomplete[l] + resultvalidationdictmin[l] for l in resultvalidationdictq05: resultvalidationdictq05complete[l] = resultvalidationdictq05complete[l] + resultvalidationdictq05[l] for l in resultvalidationdictq25: resultvalidationdictq25complete[l] = resultvalidationdictq25complete[l] + resultvalidationdictq25[l] for l in resultvalidationdictq50: resultvalidationdictq50complete[l] = resultvalidationdictq50complete[l] + resultvalidationdictq50[l] for l in resultvalidationdictq75: resultvalidationdictq75complete[l] = resultvalidationdictq75complete[l] + resultvalidationdictq75[l] for l in resultvalidationdictq95: resultvalidationdictq95complete[l] = resultvalidationdictq95complete[l] + resultvalidationdictq95[l] for l in resultvalidationdictmax: resultvalidationdictmaxcomplete[l] = resultvalidationdictmaxcomplete[l] + resultvalidationdictmax[l] if montecarloflag: for l in parameterdictcomplete: validationresultlistcomplete[l] = [i[0] for i in validationresultlistcomplete[l] if not numpy.isnan(i)] + \ [i[0] for i in validationresultsdcomplete[l] if not i == [0]] + \ resultvalidationdictmincomplete[l] + \ resultvalidationdictq05complete[l]+ \ resultvalidationdictq25complete[l] + \ resultvalidationdictq50complete[l] + \ resultvalidationdictq75complete[l] + \ resultvalidationdictq95complete[l] + \ resultvalidationdictmaxcomplete[l] + \ parameterdictcomplete[l] + \ resultvalidationdictflagscomplete[l] + \ [i[0] for i in calibrationresultmeanlistcomplete[l]] else: for l in parameterdictcomplete: validationresultlistcomplete[l] = [i[0] for i in validationresultlistcomplete[l] if not numpy.isnan(i)] + \ [i[0] for i in validationresultsdcomplete[l] if not i == [0]] + \ parameterdictcomplete[l] + \ resultvalidationdictflagscomplete[l] + \ [i[0] for i in calibrationresultmeanlistcomplete[l]] flag_list = [] for ensemblenum in range(int(ensembles)): flag_list.append(str('flag_' + str(ensemblenum))) if montecarloflag: quantile_list = [] for i in (5,25,50,75,95): quantile_list.append(str('q'+str(i))) o = open(str(input + '_validation_result.csv'), "w+") w = csv.writer(o) if splitfactorflag and montecarloflag: w.writerow(['cat'] + \ ['validation_mean'] + \ ['validation_sd'] + \ ['validation_min'] + \ quantile_list + \ ['validation_max'] + \ [target] + \ [splitfactor] + \ parameternamelist + \ flag_list + \ calibrationnamecomplete) elif splitfactorflag and montecarloflag == False: w.writerow(['cat'] + \ ['validation_mean'] + \ ['validation_sd'] + \ [target] + \ [splitfactor] + \ parameternamelist + \ flag_list + \ calibrationnamecomplete) else: w.writerow(['cat'] + \ ['validation_mean'] + \ ['validation_sd'] + \ [target] + \ parameternamelist + \ flag_list + \ calibrationnamecomplete) for key, val in validationresultlistcomplete.items(): w.writerow([key] + val) o.close() # Create Validation and Calibration Plots. ValidationPlot(input, target, montecarloflag, parameters) if __name__ == "__main__": options, flags = grass.parser() main()
Python
#!/usr/bin/env python ############################################################################### # # MODULE: m.fuzzy.upscale # AUTHOR: Thomas Leppelt # PURPOSE: Application of calibrated fuzzy models on raster maps with option # to use empirical distribution function as input maps to generate # models from. # ############################################################################### #%module #% description: Application of calibrated fuzzy models on raster maps with optional use of empirical distribution function. #% keywords: Miscellaneous #% keywords: Fuzzy model,TAG2E, ecdf #%end #%option G_OPT_F_INPUT #% description: List of input raster maps or function names for fuzzy model input. Function options: ecdf() #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Basename of output raster files. #% required : no #% guisection: Files & format #%end #%option #% key: parameter #% type : string #% description: List of XML fuzzy inference parameter file names. #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: file #% type : string #% description: File name containing XML fuzzy inference parameter file names as list. #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: alias #% type : string #% description: Alias name of the input raster maps in the XML fuzzy inference scheme file. #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option #% key: sample #% type : double #% description: Number of random samples taken from distributions. #% required : no #% multiple: no #% answer: 100 #% guisection: Files & format #%end #%option #% key: population #% type : string #% description: List of vector maps containing data used to generate specified functions. Must be provided in same order as the functions occure in input. #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: column #% type : string #% description: List of column names containing data used to generate specified functions. Must be provided in same order as the functions occure in input. #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: null #% type : double #% description: The value used for no data. Default: 9999 #% required : no #% multiple: no #% answer: 9999 #% guisection: Files & format #%end #%flag #% key: a #% description: Calculate additional statistics (Stdev, Var, Quantiles). Attention: Very slow computation for big sample numbers. #%end #%flag #% key: s #% description: Compute the cell specific standard deviation based on the rule standard deviation. #%end #%flag #% key: p #% description: Activate parallel model computing based on number of CPU cores. #%end """ # Test 1: ParallelSeries. @code >>> test_list = [] >>> grass.run_command('g.region', n = 1000000, s = 0, e = 1000000, w = 0, overwrite = True) 0 >>> for i in range(1,1001): ... stat = grass.run_command('r.mapcalc', expression = "test_%s = %s" %(str(i), str(i)), ... overwrite = True, quiet = True) ... test_list.append(str('test_' + str(i))) ... >>> ParallelSeries(map_list = test_list, output = "test_out") Created result map: test_out_average >>> result = grass.raster.raster_info('test_out_average') >>> print(result['max']) 500.5 >>> grass.run_command('g.mremove', rast="test_[0-9]*", flags = 'f', quiet = True) 0 >>> grass.run_command('g.mremove', rast="test_out_average", flags = 'f', quiet = True) 0 @endcode """ import random import grass.script as grass import multiprocessing as multi import re import itertools import sys class EmpiricalCDF: # Object for empirical cumulative distribution functions. # The expected value, or mean, of the empirical CDF is the true underlying CDF. # That is, the empirical CDF is an unbiased estimate of the population CDF. # The empirical CDF is a consistent estimator of the true CDF at any value of x. # https://onlinecourses.science.psu.edu/stat464/node/84 def __init__(self, data): # Constructor for basic ECDF properties. self.input_dataset = data self.input_sorted_set = set(data) self.input_count_set = [data.count(i) for i in set(data)] self.input_step_set = [ float(i) / len(data) for i in self.input_count_set] self.random_var = list() def random_sample(self, number): # Function for creating random samples. self.random_var = list() self.input_len = len(self.input_dataset) for i in range(0,number): self.random_var.append(self.input_dataset[random.randrange(self.input_len)]) def __str__(self): # Print method gives list of random sample. return str(self.random_var) def ParallelRun(map_list, output, function, parallel = False): if parallel: # Get number of CPU cores. workers = multi.cpu_count() else: workers = 1 # Set iteration variable for parallel processes. proc_count = 0 # Set iteration variable for temporary raster maps. out_count = 0 # Create empty list for model evaluations. model_eval_list = [] # Create empty model output list. result_list = [] for maps in map_list: # Convert input sub lists iteratively into strings. inmaps = ','.join(maps) # Create temporary output files. outmaps = str(output + '_' + str(out_count)) # Evaluate list by r.series in parallel processing. model_eval_list.append(grass.start_command('r.series', input = inmaps, \ output = outmaps, method = function, \ overwrite = grass.overwrite, flags = "z")) # Save created raster map name to result list and print status. result_list.append(outmaps) # Increase iteration variables. out_count += 1 proc_count += 1 # Check for maximum number of parallel processes defined by cpu count. if (proc_count == workers) or (proc_count == int(len(map_list))): for process in model_eval_list: process.wait() # Empty process list and reset counter. model_eval_list = [] proc_count = 0 # Wait for remaining processes. for process in model_eval_list: process.wait() # Return result map list. return(result_list) def ParallelSeries(map_list, output, function = "average", sublen = 50, parallel = False): # Evaluate raster maps by division into subsets with parallel processing. # Create empty remove list for computed maps. remove_temp = [] # Create sub lists of given length. chunks = [map_list[i : i + sublen] for i in range(0, len(map_list), sublen)] # Compute statistics for result map list with r.series. result_list = ParallelRun(chunks, str(output + '_tempI'), function, parallel = parallel) # Add result to remove list. remove_temp.append(result_list) # Conditional repeated parallel processing. if len(result_list) > int(sublen): chunks = [result_list[i : i + sublen] for i in range(0, len(result_list), sublen)] result_list = ParallelRun(chunks, str(output + '_tempII'), function) remove_temp.append(result_list) # Compute final output map. outmap = str(output + '_' + function) inmaps = ','.join(result_list) grass.run_command('r.series', input = inmaps, output = outmap, method = function, \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_" + function)) # Format list with raster maps for removal. remove_temp = [",".join(l) for l in remove_temp] # Remove created random variable raster maps. for rast_list in remove_temp: grass.read_command('g.mremove', rast = rast_list, flags = 'f') def EvalFuzzyModelSet(map_list, parameter, alias, output_base, sample_num, sd = False, \ parallel = False): # Evaluate Fuzzy models by given raster maps or distribution functions. if parallel: # Get number of CPU cores. workers = multi.cpu_count() else: workers = 1 # Set iteration variable for parellel processes. proc_count = 0 # Set iteration variable for output raster maps. out_count = 0 # Create empty list for model evaluations. model_eval_list = [] # Create empty model output list and sd output list. result_list = [] sd_list = [] # Convert map list elemets to sub lists. map_list = [[i] if not isinstance(i, list) else i for i in map_list] # Create map combinations for fuzzy model input. iter_list = list(itertools.product(*map_list)) # Loop over parameter files in parameter list. for p in parameter: # Loop over maps in given map_list. for i in iter_list: input_maps = ','.join(list(i)) output_name = str(output_base + "_" + str(out_count)) if sd: sd_name = str(output_base + "_sd_" + str(out_count)) model_eval_list.append(grass.start_command('r.fuzzy.model', \ input = input_maps, \ output = output_name, \ parameter = p, \ alias = alias, \ overwrite = grass.overwrite, \ sd = sd_name)) sd_list.append(sd_name) else: model_eval_list.append(grass.start_command('r.fuzzy.model', \ input = input_maps, \ output = output_name, \ parameter = p, \ alias = alias, \ overwrite = grass.overwrite)) # Save created raster map name to result list and print status. result_list.append(output_name) print(str("Created model output: " + output_name)) # Increase iteration variables. out_count += 1 proc_count += 1 # Check for maximum number of parallel processes defined by cpu count. if (proc_count == workers) or (proc_count == int(sample_num)): for process in model_eval_list: process.wait() # Empty process list and reset counter. model_eval_list = [] proc_count = 0 # Wait for remaining processes. for process in model_eval_list: process.wait() if sd: return(result_list, sd_list) else: return(result_list) def main(): input = options['input'] output = options['output'] parameter = options['parameter'] alias = options['alias'] sample = options['sample'] population = options['population'] column = options['column'] filename = options['file'] navalue = options['null'] statistics = flags['a'] sd = flags['s'] parallel = flags['p'] # List of optional input functions to calculate random values. function_list = ["ecdf()", "cdf()", "norm()"] # Check if parameters or file list is given. try: file_list = open(str(filename)) d = file_list.read() parameter_list = d.split() file_list.close() except: parameter_list = parameter.split(',') if parameter_list == [""]: grass.fatal(("Parameter files not given.")) # Format input parameter string. input_parameter = input.split(',') input_parameter = [i.strip() for i in input_parameter] # Check if input raster maps exists in actual mapset. input_list = [i for i in input_parameter if i not in function_list] for map in input_list: if grass.find_file(map)['file'] == "": grass.fatal(("Raster map <%s> not exists.") % map) # Format input population string. popu_input = population.split(',') popu_input = [i.strip() for i in popu_input] # Format input population string. col_input = column.split(',') col_input = [i.strip() for i in col_input] # Create list of boolean expressions for functions input list. function_bool = [[i == j for j in function_list] for i in input_parameter] # Loop through input parameters and evaluate given function statements and # return raster map list. # Create empty list for input maps. map_list = list() # Create empty list for maps that will be removed after computations. remove_list = list() # Set iteration variable for population number. popu_index = 0 for i in range(0, len(input_parameter)): if True in function_bool[i]: # Get function index and type. function_index = function_bool[i].index(True) function_type = function_list[function_index] # Create list from vector map column with population data. popu_table = grass.read_command('v.db.select', \ map = popu_input[popu_index], \ columns = col_input[popu_index], \ flags = 'c', sep= ';') # Format population data. popu_table = re.split('\n', popu_table.strip('\n')) # Remove NA values from population data. popu_table = [item for item in popu_table if item != str(navalue)] # Create random values for selected function of given population. if function_type == "ecdf()": popu_function = EmpiricalCDF(popu_table) popu_function.random_sample(int(sample)) popu_sample = popu_function.random_var # Create raster maps based on sampled random variable. raster_list = [] # Loop through number of sample random variables. for i in range(0, int(sample)): raster_name = str(popu_input[popu_index] + '_' + \ col_input[popu_index] + '_' + str(i)) # Create raster maps with random variables sampled from given # distribution function. grass.read_command('r.mapcalc', \ expression = str(raster_name + '=' + \ popu_sample[i]), overwrite = grass.overwrite) raster_list.append(raster_name) print(str("Created sample raster map: " + raster_name)) # Add raster map names to result lists. map_list.append(raster_list) remove_list.append(raster_list) popu_index += 1 else: map_list.append(input_parameter[i]) # Use raster map list to compute fuzzy models. if sd: result_list, sd_list = EvalFuzzyModelSet(map_list, parameter_list, \ alias, output, sample, sd, \ parallel) else: result_list = EvalFuzzyModelSet(map_list, parameter_list, alias, output, \ sample, sd, parallel) # Compute statistics for result map list with r.series. # Average output raster map. ParallelSeries(result_list, output, "average", parallel = parallel) ParallelSeries(result_list, output, "maximum", parallel = parallel) ParallelSeries(result_list, output, "minimum", parallel = parallel) if sd: ParallelSeries(sd_list, output + "_sd", "average", parallel = parallel) ParallelSeries(sd_list, output + "_sd", "maximum", parallel = parallel) ParallelSeries(sd_list, output + "_sd", "minimum", parallel = parallel) # Additional statistics. if statistics: # Format result raster map list. result_str = '\n'.join(result_list) # Create new file in temporary directory with result list as input for r.series. result_path = "/tmp/m_fuzzy_upscale_result_list.txt" result_file = open(result_path, "w") result_file.write(result_str) result_file.close() # Standard deviation output raster map. grass.read_command('r.series', file = result_path, \ output = str(output + "_stdev"), method = "stddev", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_stdev")) # Variance output raster map. grass.read_command('r.series', file = result_path, \ output = str(output + "_var"), method = "variance", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_var")) # Q05 output raster map. grass.read_command('r.series', file = result_path, quantile = "0.05", \ output = str(output + "_q05"), method = "quantile", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_q05")) # Q95 output raster map. grass.read_command('r.series', file = result_path, quantile = "0.95", \ output = str(output + "_q95"), method = "quantile", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_q95")) # Q50 output raster map. grass.read_command('r.series', file = result_path, quantile = "0.5", \ output = str(output + "_q50"), method = "quantile", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_q50")) # Format list with raster maps for removal. remove_list = [",".join(l) for l in remove_list] # Remove fuzzy model raster maps. grass.read_command('g.mremove', rast = str(output + '_' + '[0-9]'), flags = 'rf') # Remove created random variable raster maps. for rast_list in remove_list: grass.read_command('g.mremove', rast = rast_list, flags = 'f') if __name__ == "__main__": if len(sys.argv) == 2 and sys.argv[1] == 'doctest': import doctest doctest.testmod() exit() options, flags = grass.parser() main()
Python
#!/usr/bin/env python ############################################################################### # # MODULE: m.fuzzy.upscale # AUTHOR: Thomas Leppelt # PURPOSE: Application of calibrated fuzzy models on raster maps with option # to use empirical distribution function as input maps to generate # models from. # ############################################################################### #%module #% description: Application of calibrated fuzzy models on raster maps with optional use of empirical distribution function. #% keywords: Miscellaneous #% keywords: Fuzzy model,TAG2E, ecdf #%end #%option G_OPT_F_INPUT #% description: List of input raster maps or function names for fuzzy model input. Function options: ecdf() #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option G_OPT_F_OUTPUT #% description: Basename of output raster files. #% required : no #% guisection: Files & format #%end #%option #% key: parameter #% type : string #% description: List of XML fuzzy inference parameter file names. #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: file #% type : string #% description: File name containing XML fuzzy inference parameter file names as list. #% required : no #% multiple: no #% guisection: Files & format #%end #%option #% key: alias #% type : string #% description: Alias name of the input raster maps in the XML fuzzy inference scheme file. #% required : yes #% multiple: yes #% guisection: Files & format #%end #%option #% key: sample #% type : double #% description: Number of random samples taken from distributions. #% required : no #% multiple: no #% answer: 100 #% guisection: Files & format #%end #%option #% key: population #% type : string #% description: List of vector maps containing data used to generate specified functions. Must be provided in same order as the functions occure in input. #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: column #% type : string #% description: List of column names containing data used to generate specified functions. Must be provided in same order as the functions occure in input. #% required : no #% multiple: yes #% guisection: Files & format #%end #%option #% key: null #% type : double #% description: The value used for no data. Default: 9999 #% required : no #% multiple: no #% answer: 9999 #% guisection: Files & format #%end #%flag #% key: a #% description: Calculate additional statistics (Stdev, Var, Quantiles). Attention: Very slow computation for big sample numbers. #%end #%flag #% key: s #% description: Compute the cell specific standard deviation based on the rule standard deviation. #%end #%flag #% key: p #% description: Activate parallel model computing based on number of CPU cores. #%end """ # Test 1: ParallelSeries. @code >>> test_list = [] >>> grass.run_command('g.region', n = 1000000, s = 0, e = 1000000, w = 0, overwrite = True) 0 >>> for i in range(1,1001): ... stat = grass.run_command('r.mapcalc', expression = "test_%s = %s" %(str(i), str(i)), ... overwrite = True, quiet = True) ... test_list.append(str('test_' + str(i))) ... >>> ParallelSeries(map_list = test_list, output = "test_out") Created result map: test_out_average >>> result = grass.raster.raster_info('test_out_average') >>> print(result['max']) 500.5 >>> grass.run_command('g.mremove', rast="test_[0-9]*", flags = 'f', quiet = True) 0 >>> grass.run_command('g.mremove', rast="test_out_average", flags = 'f', quiet = True) 0 @endcode """ import random import grass.script as grass import multiprocessing as multi import re import itertools import sys class EmpiricalCDF: # Object for empirical cumulative distribution functions. # The expected value, or mean, of the empirical CDF is the true underlying CDF. # That is, the empirical CDF is an unbiased estimate of the population CDF. # The empirical CDF is a consistent estimator of the true CDF at any value of x. # https://onlinecourses.science.psu.edu/stat464/node/84 def __init__(self, data): # Constructor for basic ECDF properties. self.input_dataset = data self.input_sorted_set = set(data) self.input_count_set = [data.count(i) for i in set(data)] self.input_step_set = [ float(i) / len(data) for i in self.input_count_set] self.random_var = list() def random_sample(self, number): # Function for creating random samples. self.random_var = list() self.input_len = len(self.input_dataset) for i in range(0,number): self.random_var.append(self.input_dataset[random.randrange(self.input_len)]) def __str__(self): # Print method gives list of random sample. return str(self.random_var) def ParallelRun(map_list, output, function, parallel = False): if parallel: # Get number of CPU cores. workers = multi.cpu_count() else: workers = 1 # Set iteration variable for parallel processes. proc_count = 0 # Set iteration variable for temporary raster maps. out_count = 0 # Create empty list for model evaluations. model_eval_list = [] # Create empty model output list. result_list = [] for maps in map_list: # Convert input sub lists iteratively into strings. inmaps = ','.join(maps) # Create temporary output files. outmaps = str(output + '_' + str(out_count)) # Evaluate list by r.series in parallel processing. model_eval_list.append(grass.start_command('r.series', input = inmaps, \ output = outmaps, method = function, \ overwrite = grass.overwrite, flags = "z")) # Save created raster map name to result list and print status. result_list.append(outmaps) # Increase iteration variables. out_count += 1 proc_count += 1 # Check for maximum number of parallel processes defined by cpu count. if (proc_count == workers) or (proc_count == int(len(map_list))): for process in model_eval_list: process.wait() # Empty process list and reset counter. model_eval_list = [] proc_count = 0 # Wait for remaining processes. for process in model_eval_list: process.wait() # Return result map list. return(result_list) def ParallelSeries(map_list, output, function = "average", sublen = 50, parallel = False): # Evaluate raster maps by division into subsets with parallel processing. # Create empty remove list for computed maps. remove_temp = [] # Create sub lists of given length. chunks = [map_list[i : i + sublen] for i in range(0, len(map_list), sublen)] # Compute statistics for result map list with r.series. result_list = ParallelRun(chunks, str(output + '_tempI'), function, parallel = parallel) # Add result to remove list. remove_temp.append(result_list) # Conditional repeated parallel processing. if len(result_list) > int(sublen): chunks = [result_list[i : i + sublen] for i in range(0, len(result_list), sublen)] result_list = ParallelRun(chunks, str(output + '_tempII'), function) remove_temp.append(result_list) # Compute final output map. outmap = str(output + '_' + function) inmaps = ','.join(result_list) grass.run_command('r.series', input = inmaps, output = outmap, method = function, \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_" + function)) # Format list with raster maps for removal. remove_temp = [",".join(l) for l in remove_temp] # Remove created random variable raster maps. for rast_list in remove_temp: grass.read_command('g.mremove', rast = rast_list, flags = 'f') def EvalFuzzyModelSet(map_list, parameter, alias, output_base, sample_num, sd = False, \ parallel = False): # Evaluate Fuzzy models by given raster maps or distribution functions. if parallel: # Get number of CPU cores. workers = multi.cpu_count() else: workers = 1 # Set iteration variable for parellel processes. proc_count = 0 # Set iteration variable for output raster maps. out_count = 0 # Create empty list for model evaluations. model_eval_list = [] # Create empty model output list and sd output list. result_list = [] sd_list = [] # Convert map list elemets to sub lists. map_list = [[i] if not isinstance(i, list) else i for i in map_list] # Create map combinations for fuzzy model input. iter_list = list(itertools.product(*map_list)) # Loop over parameter files in parameter list. for p in parameter: # Loop over maps in given map_list. for i in iter_list: input_maps = ','.join(list(i)) output_name = str(output_base + "_" + str(out_count)) if sd: sd_name = str(output_base + "_sd_" + str(out_count)) model_eval_list.append(grass.start_command('r.fuzzy.model', \ input = input_maps, \ output = output_name, \ parameter = p, \ alias = alias, \ overwrite = grass.overwrite, \ sd = sd_name)) sd_list.append(sd_name) else: model_eval_list.append(grass.start_command('r.fuzzy.model', \ input = input_maps, \ output = output_name, \ parameter = p, \ alias = alias, \ overwrite = grass.overwrite)) # Save created raster map name to result list and print status. result_list.append(output_name) print(str("Created model output: " + output_name)) # Increase iteration variables. out_count += 1 proc_count += 1 # Check for maximum number of parallel processes defined by cpu count. if (proc_count == workers) or (proc_count == int(sample_num)): for process in model_eval_list: process.wait() # Empty process list and reset counter. model_eval_list = [] proc_count = 0 # Wait for remaining processes. for process in model_eval_list: process.wait() if sd: return(result_list, sd_list) else: return(result_list) def main(): input = options['input'] output = options['output'] parameter = options['parameter'] alias = options['alias'] sample = options['sample'] population = options['population'] column = options['column'] filename = options['file'] navalue = options['null'] statistics = flags['a'] sd = flags['s'] parallel = flags['p'] # List of optional input functions to calculate random values. function_list = ["ecdf()", "cdf()", "norm()"] # Check if parameters or file list is given. try: file_list = open(str(filename)) d = file_list.read() parameter_list = d.split() file_list.close() except: parameter_list = parameter.split(',') if parameter_list == [""]: grass.fatal(("Parameter files not given.")) # Format input parameter string. input_parameter = input.split(',') input_parameter = [i.strip() for i in input_parameter] # Check if input raster maps exists in actual mapset. input_list = [i for i in input_parameter if i not in function_list] for map in input_list: if grass.find_file(map)['file'] == "": grass.fatal(("Raster map <%s> not exists.") % map) # Format input population string. popu_input = population.split(',') popu_input = [i.strip() for i in popu_input] # Format input population string. col_input = column.split(',') col_input = [i.strip() for i in col_input] # Create list of boolean expressions for functions input list. function_bool = [[i == j for j in function_list] for i in input_parameter] # Loop through input parameters and evaluate given function statements and # return raster map list. # Create empty list for input maps. map_list = list() # Create empty list for maps that will be removed after computations. remove_list = list() # Set iteration variable for population number. popu_index = 0 for i in range(0, len(input_parameter)): if True in function_bool[i]: # Get function index and type. function_index = function_bool[i].index(True) function_type = function_list[function_index] # Create list from vector map column with population data. popu_table = grass.read_command('v.db.select', \ map = popu_input[popu_index], \ columns = col_input[popu_index], \ flags = 'c', sep= ';') # Format population data. popu_table = re.split('\n', popu_table.strip('\n')) # Remove NA values from population data. popu_table = [item for item in popu_table if item != str(navalue)] # Create random values for selected function of given population. if function_type == "ecdf()": popu_function = EmpiricalCDF(popu_table) popu_function.random_sample(int(sample)) popu_sample = popu_function.random_var # Create raster maps based on sampled random variable. raster_list = [] # Loop through number of sample random variables. for i in range(0, int(sample)): raster_name = str(popu_input[popu_index] + '_' + \ col_input[popu_index] + '_' + str(i)) # Create raster maps with random variables sampled from given # distribution function. grass.read_command('r.mapcalc', \ expression = str(raster_name + '=' + \ popu_sample[i]), overwrite = grass.overwrite) raster_list.append(raster_name) print(str("Created sample raster map: " + raster_name)) # Add raster map names to result lists. map_list.append(raster_list) remove_list.append(raster_list) popu_index += 1 else: map_list.append(input_parameter[i]) # Use raster map list to compute fuzzy models. if sd: result_list, sd_list = EvalFuzzyModelSet(map_list, parameter_list, \ alias, output, sample, sd, \ parallel) else: result_list = EvalFuzzyModelSet(map_list, parameter_list, alias, output, \ sample, sd, parallel) # Compute statistics for result map list with r.series. # Average output raster map. ParallelSeries(result_list, output, "average", parallel = parallel) ParallelSeries(result_list, output, "maximum", parallel = parallel) ParallelSeries(result_list, output, "minimum", parallel = parallel) if sd: ParallelSeries(sd_list, output + "_sd", "average", parallel = parallel) ParallelSeries(sd_list, output + "_sd", "maximum", parallel = parallel) ParallelSeries(sd_list, output + "_sd", "minimum", parallel = parallel) # Additional statistics. if statistics: # Format result raster map list. result_str = '\n'.join(result_list) # Create new file in temporary directory with result list as input for r.series. result_path = "/tmp/m_fuzzy_upscale_result_list.txt" result_file = open(result_path, "w") result_file.write(result_str) result_file.close() # Standard deviation output raster map. grass.read_command('r.series', file = result_path, \ output = str(output + "_stdev"), method = "stddev", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_stdev")) # Variance output raster map. grass.read_command('r.series', file = result_path, \ output = str(output + "_var"), method = "variance", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_var")) # Q05 output raster map. grass.read_command('r.series', file = result_path, quantile = "0.05", \ output = str(output + "_q05"), method = "quantile", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_q05")) # Q95 output raster map. grass.read_command('r.series', file = result_path, quantile = "0.95", \ output = str(output + "_q95"), method = "quantile", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_q95")) # Q50 output raster map. grass.read_command('r.series', file = result_path, quantile = "0.5", \ output = str(output + "_q50"), method = "quantile", \ overwrite = grass.overwrite, flags = "z") print(str("Created result map: " + output + "_q50")) # Format list with raster maps for removal. remove_list = [",".join(l) for l in remove_list] # Remove fuzzy model raster maps. grass.read_command('g.mremove', rast = str(output + '_' + '[0-9]'), flags = 'rf') # Remove created random variable raster maps. for rast_list in remove_list: grass.read_command('g.mremove', rast = rast_list, flags = 'f') if __name__ == "__main__": if len(sys.argv) == 2 and sys.argv[1] == 'doctest': import doctest doctest.testmod() exit() options, flags = grass.parser() main()
Python
import unittest import os import getpass import warnings import ConfigParser import ast import csv import filecmp import pyfmdb import re import psycopg2 import code, traceback def create_tests(host, port, admin, password, test_update, source_dir, test_dir): class FMDBTestCase(unittest.TestCase): def setUp(self): """ sets database related attributes taken from the containing factory function returns True or False based on whether the test should test the latest database update script """ self.test_database_update = test_update self.host = host self.port = port self.admin = admin self.password = password self.source_dir = source_dir self.test_dir = test_dir if test_update: # load repo info from the source directory repo = git.Repo(self.source_dir) # extract the list of version tags from the repo. assumes all version tags start with 'v'. version_tags = [tag for tag in repo.tags if tag.name.startswith('v')] # if there are no version tags, rasise an exception if not version_tags: raise Exception("Can't test updates. No version tags in git repository.") # version tags are expected in the format vx.x.x, where x are integers and there is at least one x. # sort the tags by their numbers version_tags = sorted(version_tags, key=lambda vtag: tuple([int(n) for n in vtag.name[1:].split('.')])) # get the latest tag last_tag = version_tags_sorted[-1] old_version = {} try: # read the contents of VERSION.py from the version associated with the last tag old_versions_def = repo.git.execute('git show ' + last_tag.name + ':VERSION.py') except git.GitCommandError: raise Exception("Database update test requested, but git could not retrieve prior version information.") else: # extract each version number into old_version for component_version in old_versions_def.split('\n'): component, version = component_version.split('=') old_version[component.strip()] = ast.literal_eval(version) # check that the version of the database in the last version is not the same as the current # version of the database. if VERSION.db == old_versions['db']: exc = "Database update test requested, but the database version number has not " + \ "changed from the last version." raise Exception(exc) try: # get the database setup file from the prior version old_db_setup = repo.git.execute('git show ' + tag.name + ':database_setup.sql') except git.GitCommandError: raise Exception("Database update test requested, but could not retrieve prior database setup file.") else: # create a temporary file and write the old database setup file temp_path = tempfile.mktemp() with open(temp_path, 'w') as f: f.write(old_db_setup.decode('string-escape')) # build the old database pyfmdb.build_database(script=temp_path, host=self.host, port=self.port, admin=self.admin, password=self.password, delete_existing=True, make_test_user=True) # execute the latest update script update_dir = os.path.join(self.source_dir, 'updates') updates = [name for name in os.listdir(update_dir) if name.startswith('v')] updates = sorted(updates, key=lambda name: [int(x) for x in name.strip('.vsql').split('.')]) update = updates[-1] update_path = os.path.join(update_dir, update) pyfmdb.update_database(host=self.host, port=self.port, admin=admin, password=password) else: pyfmdb.build_database(script=os.path.join(source_dir, 'database_setup.sql'), host=self.host, port=self.port, admin=admin, password=password, delete_existing=True, make_test_user=True) def inputdir(self): if hasattr(self, 'testdir'): return os.path.join(self.testdir, 'input') def expectdir(self): if hasattr(self, 'testdir'): return os.path.join(self.testdir, 'expectations') test_cases = [] @test_cases.append class TestCase01(FMDBTestCase): name = 'test_import' def runTest(self): self.testdir = os.path.join(self.test_dir, self.name) stage_dirs = ['FlowMonitoring' + str(i) for i in range(6)] with pyfmdb.connect(self.host, port=self.port, user='fmdb_tester', password='fmdb_tester') as cnxn: for stagedir in stage_dirs: cnxn.batch_update(os.path.join(self.inputdir(), stagedir)) outdir = os.path.join(self.expectdir(), stagedir) allflows_exported_path = os.path.join(outdir, 'allflows_exported.csv') with open(allflows_exported_path, 'w') as f: batch = 5000 cnxn.execute("SELECT * FROM export_allflows(1)") writer = csv.DictWriter(f, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() while True: rows = cnxn.fetchmany(size=batch, dicts=True) if rows: writer.writerows(rows) else: break allflows_expected_path = os.path.join(outdir, 'allflows_expected.csv') self.assertTrue(filecmp.cmp(allflows_expected_path, allflows_exported_path)) eventstats_exported_path = os.path.join(outdir, 'eventstats_exported.csv') with open(eventstats_exported_path, 'w') as f: cnxn.execute("SELECT * FROM export_eventstats(1)") writer = csv.DictWriter(f, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() writer.writerows(cnxn.fetchall(dicts=True)) eventstats_expected_path = os.path.join(outdir, 'eventstats_expected.csv') self.assertTrue(filecmp.cmp(eventstats_expected_path, eventstats_exported_path)) filesum_exported_path = os.path.join(outdir, 'filesum_exported.csv') with open(filesum_exported_path, 'w') as f: cnxn.execute("SELECT * FROM get_filesummary()") writer = csv.DictWriter(f, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() writer.writerows(cnxn.fetchall(dicts=True)) filesum_expected_path = os.path.join(outdir, 'filesum_expected.csv') self.assertTrue(filecmp.cmp(filesum_exported_path, filesum_expected_path)) sites_exported_path = os.path.join(outdir, 'sites_exported.csv') with open(sites_exported_path, 'w') as f: cnxn.execute("SELECT * FROM get_sites()") writer = csv.DictWriter(f, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() writer.writerows(cnxn.fetchall(dicts=True)) sites_expected_path = os.path.join(outdir, 'sites_expected.csv') @test_cases.append class TestCase02(FMDBTestCase): name = 'test_file_summary' def runTest(self): self.testdir = os.path.join(self.test_dir, self.name) exported_path = os.path.join(self.expectdir(), 'file_summary_exported.csv') with pyfmdb.connect(self.host, port=self.port, user='fmdb_tester', password='fmdb_tester') as cnxn: cnxn.batch_update(self.inputdir()) with open(exported_path, 'w') as out: cnxn.execute("SELECT * FROM get_filesummary()") writer = csv.DictWriter(out, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() writer.writerows(cnxn.fetchall(dicts=True)) expected_path = os.path.join(self.expectdir(), 'file_summary_expected.csv') self.assertTrue(filecmp.cmp(exported_path, expected_path)) @test_cases.append class TestCase03(FMDBTestCase): name = 'test_excel_formatted' def runTest(self): self.testdir = os.path.join(self.test_dir, self.name) with pyfmdb.connect(self.host, port=self.port, user='fmdb_tester', password='fmdb_tester') as cnxn: cnxn.batch_update(os.path.join(self.inputdir(), 'FlowMonitoring')) allflows_exported_path = os.path.join(self.expectdir(), 'allflows_exported.csv') with open(allflows_exported_path, 'w') as f: batch = 5000 cnxn.execute("SELECT * FROM export_allflows(1)") writer = csv.DictWriter(f, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() while True: rows = cnxn.fetchmany(size=batch, dicts=True) if rows: writer.writerows(rows) else: break allflows_expected_path = os.path.join(self.expectdir(), 'allflows_expected.csv') self.assertTrue(filecmp.cmp(allflows_expected_path, allflows_exported_path)) eventstats_exported_path = os.path.join(self.expectdir(), 'eventstats_exported.csv') with open(eventstats_exported_path, 'w') as f: cnxn.execute("SELECT * FROM export_eventstats(1)") writer = csv.DictWriter(f, fieldnames=cnxn.cursor_columns, lineterminator='\n') writer.writeheader() writer.writerows(cnxn.fetchall(dicts=True)) eventstats_expected_path = os.path.join(self.expectdir(), 'eventstats_expected.csv') self.assertTrue(filecmp.cmp(eventstats_expected_path, eventstats_exported_path)) @test_cases.append class TestCase04(FMDBTestCase): name = 'test_user_privileges' def runTest(self): self.testdir = os.path.join(self.test_dir, self.name) outsider_login = 'outsider' with pyfmdb.connect(self.host, port=self.port, user=self.admin, password=self.password) as cnxn: try: cnxn.execute("DROP USER " + outsider_login) except: pass cnxn.execute("CREATE ROLE " + outsider_login + " WITH LOGIN PASSWORD '" + outsider_login + "'") try: cnxn2 = pyfmdb.connect(self.host, port=self.port, user=outsider_login, password=outsider_login) except: outsider_cant_connect = True else: outsider_cant_connect = False cnxn2.close() self.assertTrue(outsider_cant_connect) with pyfmdb.connect(self.host, port=self.port, user='fmdb_tester', password='fmdb_tester') as cnxn: cnxn.batch_update(os.path.join(self.inputdir(), 'FlowMonitoring')) #print 'bacon' #code.interact(local=locals()) #cnxn.execute("REVOKE CONNECT ON DATABASE fmdb FROM fmdb_user") #cnxn.execute("REVOKE CONNECT ON DATABASE fmdb FROM PUBLIC") with pyfmdb.connect(self.host, port=self.port, user='fmdb_guest', password='fmdb_guest') as cnxn: try: cnxn.execute("SELECT * FROM allflows") cnxn.execute("SELECT * FROM eventstatistics") cnxn.execute("SELECT * FROM filesummary") except: traceback.print_exc() can_select = False else: can_select = True self.assertTrue(can_select) try: cnxn.execute("SELECT * FROM private.sites_type") except: cant_select_meta = True else: cant_select_meta = False self.assertTrue(cant_select_meta) try: cnxn.execute("SELECT * FROM export_eventstats(1)") except: can_execute = False else: can_execute = True self.assertTrue(can_execute) return test_cases def main(): source_dir = os.path.dirname(__file__) if '__file__' in globals() else os.path.abspath('.') test_dir = os.path.join(source_dir, 'tests') cfg_path = os.path.join(test_dir, 'testsuite.ini') if os.path.exists(cfg_path): parser = ConfigParser.SafeConfigParser() parser.read(cfg_path) host = ast.literal_eval(parser.get('main', 'host')) admin = ast.literal_eval(parser.get('main', 'admin')) port = ast.literal_eval(parser.get('main', 'port')) test_update = ast.literal_eval(parser.get('main', 'test_update')) else: host = raw_input('Testing host: ') admin = raw_input('Admin login: ') while True: port = raw_input('Port Number:') try: port = int(port) except: print("Invalid input. Port should be an integer.") else: break while True: test_update = raw_input('Test latest database update [y/n] >> ').lower() if test_update.startswith('y'): test_update = True elif test_update.startswith('n'): test_update = False else: continue break password = getpass.getpass('Password for ' + admin + ' on ' + host + ':' + str(port) + ': ') tests = create_tests(host=host, port=port, admin=admin, password=password, test_update=test_update, source_dir=source_dir, test_dir=test_dir) suite = unittest.TestSuite() for test in tests: suite.addTest(test()) return unittest.TextTestRunner(verbosity=2).run(suite)
Python
fmdb = '0.0.0' api = '0.0.0' db = '0.0.0'
Python
import os import sys import csv import psycopg2 as pg import pyodbc import traceback, code import VERSION import itertools import StringIO import glob import stat from datetime import datetime import fnmatch import xlrd import string import re import shutil import pyfmdb import pyodbc from collections import OrderedDict import collections from contextlib import closing __version__ = VERSION.api __doc__ = '' __dir__ = os.path.dirname(__file__) if '__file__' in globals() else os.path.abspath(os.curdir) __resources__ = sys._MEIPASS if hasattr(sys, '_MEIPASS') else __dir__ # TODO make sure that when you filter for xls files, you ignore locks, which start with a tilde #exec("""from fmdb.pyfmdb import * #build_database(host='localhost', admin='postgres', password='watershed.123', port=5433, delete_existing=True) #cnxn = connection('localhost', user='postgres', password='watershed.123', port=5433) #cnxn.batch_update(r'D:\Data\Flow Monitoring by ManholeID', is_sses=True)""") #exec("""from fmdb.pyfmdb import * #cnxn = connect('localhost', 'postgres', 'watershed.123') #cnxn.batch_update(r'D:\Data\Flow Monitoring by ManholeID', is_sses=False)""") #cnxn.batch_update(r'D:\Data\Flow Monitoring by ManholeID', is_sses=False)""") # exec("""from fmdb.pyfmdb import * #build_database(host='localhost', admin='postgres', password='watershed.123', port=5434, delete_existing=True) #cnxn = connection('localhost', user='postgres', password='watershed.123', port=5434) #cnxn.batch_update(r'D:\Data\FM_bugs', is_sses=False)""") _port = 5432 def mysetup(): build_database(host='localhost', port=_port, admin='postgres', password='watershed.123', delete_existing=True) cnxn = connect(host='localhost', port=_port, user='postgres', password='watershed.123') cnxn.make_user('matthew.plourde', 'sunnyday.1') cnxn.add_admin('matthew.plourde') def loaddata(): cnxn = connect(host='localhost', port=_port, user='matthew.plourde', password='sunnyday.1') cnxn.batch_update(r'D:\Data\FlowMonitoring') #cnxn.batch_update(r'\\pwdoows1\Modeling\Data\Temporary Monitors\Flow Monitoring\Flow Monitoring by ManholeID') #cnxn.batch_update(r'D:\Data\FM_tests') class ColumnError(Exception): def __init__(self, col): super(ColumnError, self).__init__("Column '" + col + "' couldn't be found.") def yesno_prompt(prompt): while True: print(prompt) ans = raw_input("[y/n] >> ") try: ans = ans.lower()[0] if ans == 'y': return True elif ans == 'n': return False else: raise ValueError() except IndexError, ValueError: print('Invalid input.') def matches_pat(v, pat): return isinstance(v, basestring) and re.match(pat + '$', str(v), re.IGNORECASE) def identify_struck_out_events(wb, sheetname, id_col, title=None): ws = wb.sheet_by_name(sheetname) if title: for i in range(ws.nrows): title_vals = [j for j, v in enumerate(ws.row_values(i)) if matches_pat(v, title)] if title_vals: rows_lb = i + 1 cols_lb = title_vals[0] try: rows_lb except: raise Exception('Could not find worksheet table title.') else: rows_lb = 0 cols_lb = 0 for i in range(cols_lb, ws.ncols): header_vals = [j for j, v in enumerate(ws.col_values(i, rows_lb)) if matches_pat(v, id_col)] if header_vals: header_row = rows_lb + header_vals[0] start_col = i break is_strike_out = [] for i in range(header_row + 1, ws.nrows): cell_value = ws.cell_value(i, start_col) if isinstance(cell_value, basestring): break else: cell_ix = ws.cell_xf_index(i, start_col) xf = wb.xf_list[cell_ix] font = wb.font_list[xf.font_index] is_strike_out.append(font.struck_out) return is_strike_out def query_worksheet(ws, id_col, cols, title=None, return_rows=False, return_full_names=True, max_cols_hint=None, browse=False, return_cols=False): if not max_cols_hint: max_cols_hint = ws.ncols if title: for i in range(ws.nrows): title_vals = [j for j, v in enumerate(ws.row_values(i)) if matches_pat(v, title)] if title_vals: rows_lb = i + 1 cols_lb = title_vals[0] try: rows_lb except: raise Exception('Could not find worksheet table title.') else: rows_lb = 0 cols_lb = 0 for i in range(cols_lb, ws.ncols): header_vals = [j for j, v in enumerate(ws.col_values(i, rows_lb)) if matches_pat(v, id_col)] if header_vals: header_row = rows_lb + header_vals[0] start_col = i break try: header_row except: raise Exception("Could not find worksheet table.") header_values = ws.row_values(header_row, start_col) for i, h in enumerate(header_values): if i == max_cols_hint or not h or not isinstance(h, basestring): break else: table_ncol = i + 1 id_coltypes = ws.col_types(start_col, header_row + 1) id_values = ws.col_values(start_col, header_row + 1) rows_to_determine_idtype = 6 id_coltype = max(set([x for x in id_coltypes[:rows_to_determine_idtype] if x != xlrd.XL_CELL_BLANK]), key=id_coltypes.count) coltypes_enum = enumerate(id_coltypes) for i, coltype in coltypes_enum: if coltype == id_coltype: start_row = i + header_row + 1 break try: start_row except: raise Exception("Could not find worksheet table starting row.") for i, coltype, value in zip(itertools.count(), id_coltypes, id_values): if coltype != id_coltype or value == '' or value is None: table_nrow = i break try: table_nrow except: table_nrow = ws.nrows - start_row header = header_values[:table_ncol] if browse: print 'browsing' code.interact(local=locals()) fields = [] out_cols = [] cols_not_found = [] MATCHES_EXACTLY = 2 MATCHES = 1 #print('moolaa') #code.interact(local=locals()) header = [re.sub('\n', '', h) for h in header] for col in cols: matches = [0 for _ in range(len(header))] col_cleaned = re.escape(col.strip('$').strip()) col_escaped = re.escape(col) #print('baconpie') #code.interact(local=locals()) for i, field in enumerate(header): if re.match(col_cleaned + '$', field): matches[i] = MATCHES_EXACTLY elif re.match(col_escaped, field, re.IGNORECASE): matches[i] = MATCHES if MATCHES_EXACTLY in matches: if matches.count(MATCHES_EXACTLY) > 1: raise Exception("Worksheet has non-unique columns.") else: fields.append(header[matches.index(MATCHES_EXACTLY)]) out_cols.append(col) elif MATCHES in matches: if matches.count(MATCHES) > 1: header_lengths = [len(h) for h in header] options = [(x, l) for i, h, l in zip(matches, header, header_lengths) if i == 1] min_l = min([tup[1] for tup in options]) selection = [tup[0] for tup in options if tup[1] == min_l] selection = selection[0] fields.append(selection) out_cols.append(col) #try: # raise Exception("Column matches multiple fields in worksheet.") #except: # traceback.print_exc() # code.interact(local=locals()) else: fields.append(header[matches.index(MATCHES)]) out_cols.append(col) else: raise ColumnError(col) results = {} for col, field in zip(out_cols, fields): final_colname = col if return_cols else field results[final_colname] = ws.col_values(start_col + header.index(field), start_row, start_row + table_nrow) if not return_full_names: results_shortnames = {} for field, col in zip(fields, cols): results_shortnames[col] = results[field] results = results_shortnames return results if not return_rows else [dict(zip(results.keys(), row)) for row in zip(*results.values())] class FMDBException(Exception): def __init__(self, msg): Exception.__init__(self, msg) def update_database(script, host=None, port=5432, admin=None, password=None): if not host: host = '\\28-aramplour3' admin='postgres' password='watershed.123' # open the setup script that defines tables and procedures with open(script, 'r') as f: script_sql = f.read() # execute the script with pg.connect(host=host, port=port, dbname='fmdb', user=admin, password=password) as cnxn: cnxn.autocommit = True with cnxn.cursor() as cursor: try: cursor.execute(script_sql) except: import traceback, code traceback.print_exc() code.interact(local=dict(locals().items() + globals().items())) def build_database(script=os.path.join(__dir__, "database_setup.sql"), host=None, port=5432, admin=None, password=None, delete_existing=False, make_test_user=False): with pg.connect(host=host, port=port, user=admin, password=password) as cnxn: cnxn.autocommit = True with cnxn.cursor() as cursor: cursor.execute("SELECT * FROM pg_catalog.pg_database WHERE datname = 'fmdb'") if cursor.fetchall(): if not delete_existing: while True: print("The fmdb database already exists on this server. Do you want to delete it?") ans = raw_input("[y/n] >> ") try: ans = ans.lower()[0] if ans == 'y': break elif ans == 'n': raise FMDBException("Database build cancelled by user.") else: raise ValueError() except IndexError, ValueError: print('Invalid input.') # disconnect any other users that are currently connected, then drop the database cursor.execute(""" SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'fmdb' AND pid <> pg_backend_pid(); """) cursor.execute("DROP DATABASE fmdb") cursor.execute("CREATE DATABASE fmdb") cursor.execute("SELECT 1 FROM pg_catalog.pg_group WHERE groname='fmdb_user'") if cursor.fetchone(): if not delete_existing: prompt = "There is already a role for fmdb_user. This installation will overwrite it. Do you want to proceed?" resp = yesno_prompt(prompt) if not resp: raise FMDBException("Database build cancelled by user.") cursor.execute("DROP ROLE fmdb_user") cursor.execute("SELECT 1 FROM pg_catalog.pg_group WHERE groname='fmdb_admin'") if cursor.fetchone(): if not delete_existing: prompt = "There is already a role for fmdb_admin. This installation will overwrite it. " + \ "Do you want to proceed?" resp = yesno_prompt(prompt) if not resp: raise FMDBException("Database build cancelled by user.") cursor.execute("DROP ROLE fmdb_admin") update_database(script, host=host, port=port, admin=admin, password=password) if make_test_user: with connect(host=host, port=port, user=admin, password=password) as cnxn: #cnxn.autocommit = True #with cnxn.cursor() as cursor: try: cnxn.execute("DROP USER fmdb_tester") except: pass cnxn.make_user('fmdb_tester', 'fmdb_tester') cnxn.add_admin('fmdb_tester') #cnxn.execute("SELECT make_user('fmdb_tester', 'fmdb_tester')") #cnxn.execute("SELECT add_fmdb_admin('fmdb_tester')") #cursor.execute("CREATE ROLE fmdb_tester WITH LOGIN PASSWORD 'fmdb_tester' IN GROUP fmdb_admin") def connect(host, user, password, port=5432, autocommit=True): return connection(host=host, user=user, password=password, port=port, autocommit=autocommit) class connection(object): def __init__(self, host, user, password, port=5432, autocommit=True): self.cnxn = pg.connect(host=host, dbname='fmdb', user=user, port=port, password=password) self.cnxn.autocommit = autocommit self.cursor = self.cnxn.cursor() self.cursor_columns = None self.cursor.execute(""" SELECT column_name FROM information_schema.columns WHERE table_name = 'filesummary_type' """) filesum_cols = [x[0] for x in self.cursor.fetchall()] self.filesummary_type = collections.namedtuple('filesummary_type', filesum_cols) self.cursor.execute(""" SELECT column_name FROM information_schema.columns WHERE table_name = 'sites_type' """) sites_cols = [row[0] for row in self.cursor.fetchall()] self.sites_type = collections.namedtuple('sites_type', sites_cols) self.cursor.execute(""" SELECT column_name FROM information_schema.columns WHERE table_name='eventstatistics' """) event_stats_colnames = [row[0] for row in self.cursor.fetchall()] self.eventstatistics = collections.namedtuple('eventstatistics', event_stats_colnames) self.cursor.execute(""" SELECT column_name FROM information_schema.columns WHERE table_name = 'allflows' """) allflows_colnames = [row[0] for row in self.cursor.fetchall()] self.allflows = collections.namedtuple('allflows', allflows_colnames) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.cursor.close() self.cnxn.close() if exc_type is not None: return False return True def close(self): self.cursor.close() self.cnxn.close() def execute(self, *args): try: self.cursor.execute(*args) except: self.cursor_columns = None raise else: if self.cursor.description: self.cursor_columns = [x.name for x in self.cursor.description] else: self.cursor_columns = None def fetchall(self, dicts=False): result = self.cursor.fetchall() if result and dicts: result = [dict(zip(self.cursor_columns, row)) for row in result] return result def fetchone(self, dicts=False): result = self.cursor.fetchone() if result and dicts: result = dict(zip(self.cursor_columns, result)) return result def fetchmany(self, size=None, dicts=False): if not size: size = self.cursor.arraysize result = self.cursor.fetchmany(size) if result and dicts: result = [dict(zip(self.cursor_columns, row)) for row in result] return result def make_user(self, name, password): self.execute("SELECT make_user('" + name + "', '" + password + "'"+ ")") def add_user(self, name): self.execute("SELECT add_fmdb_user('" + name + "')") def add_admin(self, name): self.execute("SELECT add_fmdb_admin('" + name + "')") def update_filesum(self, filesum_row): self.cursor.execute("SELECT update_filesummary(%s)", (self.filesummary_type(*filesum_row.values()),)) def batch_update(self, root, is_sses=False): manholes = [dirname for dirname in os.listdir(root) if not any(ch in string.ascii_lowercase for ch in dirname)] manhole_paths = [os.path.join(root, dirname) for dirname in manholes] manhole_paths = [m for m in manhole_paths if os.path.isdir(m)] for i, manhole_path in enumerate(manhole_paths): manhole_id = os.path.basename(manhole_path) manhole_folder_contents = [os.path.join(manhole_path, f) for f in os.listdir(manhole_path)] subdirs = filter(os.path.isdir, manhole_folder_contents) nonsite_names_pat = re.compile('video|report|photo|picture|invest|supplementary|scans|bk|deploy', re.IGNORECASE) site_paths = [p for p in subdirs if not re.search(nonsite_names_pat, os.path.basename(p))] deploy_paths = [p for p in subdirs if re.search('deploy', p, re.IGNORECASE)] if site_paths: for site_path in site_paths: site_id = os.path.basename(site_path) if re.search(re.compile('site', re.IGNORECASE), site_id): site_id = re.findall('\d+', site_id) if site_id: site_id = str(int(site_id[0])) else: continue site_folder_contents = [os.path.join(site_path, f) for f in os.listdir(site_path)] deploy_paths = filter(os.path.isdir, site_folder_contents) deploy_paths = [f for f in deploy_paths if re.search('[dD]eployment', os.path.basename(f))] if deploy_paths: for deploy_path in deploy_paths: deployment = os.path.basename(deploy_path) deployment_year = re.findall('\d{4}', deployment) if len(deployment_year) == 1: deployment_year = int(deployment_year[0]) self._doImportSSOAP(manhole_id, site_id, deployment_year, deploy_path, is_sses=is_sses) else: self._doImportSSOAP(manhole_id, site_id, None, deploy_path, is_sses=is_sses) else: self._doImportSSOAP(manhole_id, site_id, None, site_path, is_sses=is_sses) elif deploy_paths: for deploy_path in deploy_paths: deployment = os.path.basename(deploy_path) deployment_year = re.findall('\d{4}', deployment) if len(deployment_year) == 1: deployment_year = int(deployment_year[0]) self._doImportSSOAP(manhole_id, manhole_id, deployment_year, deploy_path, is_sses=is_sses) else: continue else: self._doImportSSOAP(manhole_id, None, None, manhole_path, is_sses=is_sses) def _doImportSSOAP(self, manhole_id, site_id, deployment, path, is_sses=False): filesum_row = OrderedDict(zip(self.filesummary_type._fields, itertools.cycle([False]))) filesum_row['manholeid'] = manhole_id filesum_row['siteid'] = site_id filesum_row['deployment'] = deployment filesum_row['modificationtimesconsistent'] = True filesum_row['importerror'] = None print ' '.join(['starting ', str(manhole_id), str(site_id), str(deployment)]) ssoap_dir = [fname for fname in os.listdir(path) if re.match(re.compile('ssoap', re.IGNORECASE), fname)] if len(ssoap_dir) == 1: filesum_row['hasssoapfolder'] = True ssoap_dir = ssoap_dir[0] ssoap_path = os.path.join(path, ssoap_dir) if is_sses: final_pat = 'sses' else: final_pat = 'final' try: final_dir = [fname for fname in os.listdir(ssoap_path) if re.match(re.compile(final_pat, re.IGNORECASE), fname)] except: final_dir = [] filesum_row['importerror'] = traceback.format_exc().encode('string-escape') if len(final_dir) == 1: filesum_row['hasfinalfolder'] = True final_dir = final_dir[0] final_path = os.path.join(ssoap_path, final_dir) try: if is_sses: res = self._importSSOAP_SSES(final_path, filesum_row, manhole_id, site_id, deployment) else: res = self._importSSOAP(final_path, filesum_row, manhole_id, site_id, deployment) except: filesum_row['importerror'] = traceback.format_exc().encode('string-escape') self.update_filesum(filesum_row) else: if res != 0: try: filesum_row['importerror'] = '\n'.join(res) self.update_filesum(filesum_row) except: traceback.print_exc() code.interact(local=locals()) elif len(final_dir) > 1: filesum_row['hasfinalfolder'] = True filesum_row['filesareambiguous'] = True self.update_filesum(filesum_row) else: self.update_filesum(filesum_row) elif len(ssoap_dir) > 1: filesum_row['hassoapfolder'] = True filesum_row['filesareambiguous'] = True self.update_filesum(filesum_row) else: self.update_filesum(filesum_row) print 'Done' self.cnxn.commit() def _importSSOAP(self, ssoap_path, filesum_row, manholeid, siteid=None, deployment=None): sdb_filepath = os.path.join(ssoap_path, '*.sdb') sdb_filepaths = glob.glob(sdb_filepath) mdb_filepath = os.path.join(ssoap_path, '*.mdb') mdb_filepaths = glob.glob(mdb_filepath) dtime_fmt = '%Y-%m-%d %H:%M:%S' ssoap_filepaths = sdb_filepaths if sdb_filepaths else mdb_filepaths if ssoap_filepaths: ssoap_filepath_mtimes = [os.path.getmtime(path) for path in ssoap_filepaths] max_mtime = max(ssoap_filepath_mtimes) ssoap_filepath = ssoap_filepaths[ssoap_filepath_mtimes.index(max_mtime)] ssoap_fname = os.path.basename(ssoap_filepath) ssoap_mtime = datetime.fromtimestamp(os.path.getmtime(ssoap_filepath)) sites_row = OrderedDict([(k, None) for k in self.sites_type._fields]) sites_row['ssoapfilename'] = ssoap_fname sites_row['ssoapmtime'] = ssoap_mtime.strftime(dtime_fmt) sites_row['manholeid'] = manholeid sites_row['siteid'] = siteid sites_row['deployment'] = deployment sites_row['directory'] = ssoap_path # create temp copy to work with to avoid corrupting original temp_ssoap_filepath = os.path.join(os.environ.get('TEMP'), '.temp_ssoap.mdb') if os.path.exists(temp_ssoap_filepath): os.chmod(temp_ssoap_filepath, stat.S_IWRITE) os.remove(temp_ssoap_filepath) shutil.copy(ssoap_filepath, temp_ssoap_filepath) os.chmod(temp_ssoap_filepath, stat.S_IWRITE) cnxn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=' + temp_ssoap_filepath) cursor = cnxn.cursor() cursor.execute('SELECT MeterID, RainGaugeID FROM Analyses') metergage_ids = cursor.fetchall() raingage, area, units = (None, None, None) file_conflict_excs = [] if not metergage_ids: msg = 'The SSOAP file in "' + ssoap_path + '" is missing its meter and gage.' file_conflict_excs.append(msg) if len(metergage_ids) > 1: msg = 'The SSOAP file in "' + ssoap_path + '" has multiple meters and gages.' file_conflict_excs.append(msg) else: meterid = metergage_ids[0].MeterID gageid = metergage_ids[0].RainGaugeID cursor.execute("SELECT StartDateTime, EndDateTime FROM Meters WHERE MeterID = ?", meterid) startdtime, enddtime = cursor.fetchone() sites_row['startdatetime'] = startdtime.strftime(dtime_fmt) sites_row['enddatetime'] = enddtime.strftime(dtime_fmt) cursor.execute('SELECT RaingaugeName FROM Raingauges WHERE RaingaugeID = ?', gageid) sites_row['raingage'] = str(cursor.fetchone().RaingaugeName) try: cursor.execute('SELECT Area, AreaUnitID FROM Meters WHERE MeterID = ?', meterid) except: # the Meters table in old ssoap files doesn't have AreaUnitID cursor.execute('SELECT Area FROM Meters WHERE MeterID = ?', meterid) sites_row['area'] = cursor.fetchone().Area sites_row['areaunits'] = None else: sites_row['area'], units_id = cursor.fetchone() cursor.execute('SELECT ShortLabel FROM AreaUnits WHERE AreaUnitID = ?', units_id) sites_row['areaunits'] = str(cursor.fetchone().ShortLabel) cursor.close() cnxn.close() os.remove(temp_ssoap_filepath) ## GET EVENT NOTES DATA FROM RVALUE SPREADSHEET xls_paths = glob.glob(os.path.join(ssoap_path, '*.xls')) + glob.glob(os.path.join(ssoap_path, '*.xlsx')) xls_fnames = [os.path.basename(path) for path in xls_paths] eventnotes_pat = re.compile('rvalue', re.IGNORECASE) eventnotes_fnames = [fname for fname in xls_fnames if re.search(eventnotes_pat, fname) and not fname.startswith('~')] if len(eventnotes_fnames) == 0: file_conflict_excs.append("No event notes found for " + ssoap_path) elif len(eventnotes_fnames) > 1: file_conflict_excs.append('Multiple event notes spreadsheets found in ' + ssoap_path) filesum_row['haseventnotes'] = True filesum_row['filesareambiguous'] = True file_conflict_excs.append("No eventnotes found in " + ssoap_path) else: filesum_row['haseventnotes'] = True eventnotes_path = os.path.join(ssoap_path, eventnotes_fnames[0]) sites_row['eventnotesmtime'] = datetime.fromtimestamp(os.path.getmtime(eventnotes_path)).strftime(dtime_fmt) sites_row['eventnotesfilename'] = eventnotes_fnames[0] csv_paths = glob.glob(os.path.join(ssoap_path, '*.csv')) csv_fnames = [os.path.basename(path) for path in csv_paths] rtk_path = None rtk_csvs = [fname for fname in csv_fnames if re.search(re.compile('simul', re.IGNORECASE), fname)] if len(rtk_csvs) == 1: filesum_row['hasrtk'] = True sites_row['rtkfilename'] = rtk_csvs[0] rtk_path = os.path.join(ssoap_path, rtk_csvs[0]) rtk_mtime = datetime.fromtimestamp(os.path.getmtime(rtk_path)) sites_row['rtkmtime'] = rtk_mtime.strftime(dtime_fmt) if rtk_mtime < ssoap_mtime: filesum_row['modificationtimesconsistent'] = False elif len(rtk_csvs) > 1: file_conflict_excs.append('Multiple RTK files found.') filesum_row['hasrtk'] = True filesum_row['filesareambiguous'] = True self.cursor.execute("SELECT get_analysis_id(%s, %s, %s)", (manholeid, siteid, deployment)) analysisid = self.cursor.fetchone()[0] allflows_outofdate = True eventstats_outofdate = True all_up_to_date = False if analysisid: self.execute("SELECT SSOAPMTime, EventNotesMTime, RTKMtime FROM Sites WHERE AnalysisID = %s", (analysisid,)) db_ssoap_mtime, db_notes_mtime, db_rtk_mtime = self.fetchone() db_ssoap_mtime_str = db_ssoap_mtime.strftime(dtime_fmt) db_notes_mtime_str = db_notes_mtime.strftime(dtime_fmt) db_rtk_mtime_str = db_rtk_mtime.strftime(dtime_fmt) if db_rtk_mtime else None ssoap_uptodate = db_ssoap_mtime_str == sites_row['ssoapmtime'] notes_uptodate = db_notes_mtime_str == sites_row['eventnotesmtime'] rtk_uptodate = db_rtk_mtime_str == sites_row['rtkmtime'] if ssoap_uptodate and notes_uptodate and rtk_uptodate: all_up_to_date = True if ssoap_uptodate: allflows_outofdate = False if notes_uptodate and rtk_uptodate: eventstats_outofdate = False # GET RVALUE DATA rvalue_csvs = [fname for fname in csv_fnames if re.search(re.compile('rvalue|event_*stat', re.IGNORECASE), fname)] if len(rvalue_csvs) == 1: filesum_row['hasrvalue'] = True sites_row['rvaluefilename'] = rvalue_csvs[0] rvalue_path = os.path.join(ssoap_path, rvalue_csvs[0]) rvalue_mtime = datetime.fromtimestamp(os.path.getmtime(rvalue_path)) if rvalue_mtime < ssoap_mtime: filesum_row['modificationtimesconsistent'] = False sites_row['rvaluemtime'] = rvalue_mtime.strftime(dtime_fmt) elif len(rvalue_csvs) > 1: file_conflict_excs.append("Multiple RValue CSVs found in " + ssoap_path) filesum_row['filesareambiguous'] = True filesum_row['hasrvalue'] = True else: file_conflict_excs.append("No RValue CSVs found in " + ssoap_path) allflows_pat = re.compile('all_?flow', re.IGNORECASE) allflows_fnames = [fname for fname in csv_fnames if re.search(allflows_pat, fname)] if len(allflows_fnames) == 0: file_conflict_excs.append("No all flows file found.") elif len(allflows_fnames) > 1: filesum_row['hasallflows'] = False file_conflict_excs.append("Multiple allflows files found.") else: filesum_row['hasallflows'] = True sites_row['allflowsfilename'] = allflows_fnames[0] allflows_path = os.path.join(ssoap_path, allflows_fnames[0]) allflows_mtime = datetime.fromtimestamp(os.path.getmtime(allflows_path)) sites_row['allflowsmtime'] = allflows_mtime.strftime(dtime_fmt) if allflows_mtime < ssoap_mtime: filesum_row['modificationtimesconsistent'] = False self.update_filesum(filesum_row) self.cursor.execute("SELECT update_analysis(%s)", (self.sites_type(*sites_row.values()), )) analysisid = self.cursor.fetchone()[0] if file_conflict_excs: return file_conflict_excs os.chmod(ssoap_filepath, stat.S_IREAD) if all_up_to_date: return 0 if (allflows_outofdate or eventstats_outofdate): wb = xlrd.open_workbook(eventnotes_path) sheet_names = [sheet.name for sheet in wb.sheets()] en_label = [name for name in sheet_names if re.search(re.compile('event\s*notes', re.IGNORECASE), name)] if len(en_label) == 1: en_label = en_label[0] event_notes = wb.sheet_by_name(en_label) en_titles = '(Event Notes)|(Storms Events Cut)|(Storm Event Tails Cut)' en_fields = ['Event Number', 'Good or Bad', 'Notes'] eventnotes_table = query_worksheet(event_notes, 'Event Number', en_fields, title=en_titles, return_rows=True, max_cols_hint=5) for row in eventnotes_table: for field in ['Good or Bad', 'Notes']: row[field] = str(row[field].replace(u'\u2019', "'")) # remain columns to match database names row['flag'] = row['Good or Bad'] row['notes'] = row['Notes'] row['event'] = row['Event Number'] del row['Good or Bad'] del row['Notes'] del row['Event Number'] elif len(en_label) > 1: raise FMDBException('Ambiguous event tables in ' + path) else: raise FMDBException("No event table found in " + path) outlier_label_pat = re.compile(r'\(-\)\s*outlier\s*table$', re.IGNORECASE) outlier_label = [name for name in sheet_names if re.search(outlier_label_pat, name)] if len(outlier_label) > 1: raise FMDBException("Ambiguous outlier table in " + path) elif len(outlier_label) == 0: raise FMDBException("Can't find outlier table in " + path) outlier_label = outlier_label[0] outlier = wb.sheet_by_name(outlier_label) outlier_table = query_worksheet(outlier, 'Event', ['Event']) good_events = [int(x) for x in outlier_table['Event']] for i in range(len(eventnotes_table)): eventnotes_table[i]['outlier'] = 'true' if eventnotes_table[i]['event'] not in good_events else 'false' with open(rvalue_path, 'r') as f: # eat header lines header_lines = 8 for i in range(header_lines): _ = f.readline() event_time_cols = ['startdatetime', 'enddatetime'] rainfall_time_cols = ['rainfall_startdatetime', 'rainfall_enddatetime'] header = ['event'] + event_time_cols + ['duration', 'iivolume_in', 'rainvolume_in', 'totalrvalue', 'peakiiflow_mgd', 'peaktotalflow', 'peakfactor', 'rainfall_in_15min', 'observedflow_mgd', 'gwiflow_mgd', 'basewastewaterflow_mgd'] + rainfall_time_cols + ['rainfallduration_hrs'] f_buffer = StringIO.StringIO() for line in f: line = line.strip().strip(',') + '\n' f_buffer.write(line) f_buffer.seek(0) reader = csv.DictReader(f_buffer, fieldnames=header) rvalue_table = list(reader) # the rvalue csv lines all end in a comma, leading DictReader to think there is a unnamed # empty column at the end of the table. This key is stored in the dict with a None key, and here # we remove it. for row in rvalue_table: try: del row[None] # some of the event stats csv end with a comma, resulting in an empty column except: pass for k in row.keys(): if k not in event_time_cols and k not in rainfall_time_cols: row[k] = float(row[k]) # GET RTK DATA rtk_csvs = [fname for fname in csv_fnames if re.search(re.compile('simul', re.IGNORECASE), fname)] rtk_header_keep = ['event'] + event_time_cols + ['duration', 'r1', 't1', 'k1', 'r2', 't2', 'k2', 'r3', 't3', 'k3', 'rainvolume_in', # duplicates rvalue column 'peakrainfall', 'totalrvalue', # obs volume in sim vs obs. 'simvolume'] rtk_header_discard1 = [ 'differencevolume', 'percentdifvolume', 'peak_i-i_flow_mgd'] rtk_header_discard2 = ['difference_peak', 'percent_dif_peak'] simpeak_header = ['simpeak'] rtk_header_discard = rtk_header_discard1 + rtk_header_discard2 rtk_header = rtk_header_keep + rtk_header_discard1 + simpeak_header + rtk_header_discard2 rtk_header_keep = rtk_header_keep + simpeak_header rtk_table = [] if rtk_path: with open(rtk_path, 'r') as f: num_header = 3 for i in range(num_header): _ = f.readline() # these are columns in the rtk csv, but they are computed from the others and # therefore excluded from the database while True: line = f.readline().strip().strip(',') if line.strip() == '': break line = line.split(',') line = zip(rtk_header, line) line = dict([(name, value) for name, value in line if name in rtk_header_keep]) rtk_table.append(line) for row in rtk_table: for k in row.keys(): if k not in event_time_cols: row[k] = float(row[k]) else: rtk_table = [dict(zip(rtk_header_keep, itertools.cycle([None]))) for _ in range(len(rvalue_table))] event_stats_table = [] if len(eventnotes_table) != len(rvalue_table) or len(eventnotes_table) != len(rtk_table): exc = "The number of events in the eventnotes, rvalue CSV, and RTK csv don not match in " + ssoap_path raise FMDBException(exc) for notes, rvalues, rtks in zip(eventnotes_table, rvalue_table, rtk_table): event_stats_table.append(dict(rtks.items() + notes.items() + rvalues.items())) for row in event_stats_table: row['analysisid'] = analysisid if len(self.eventstatistics._fields) != len(event_stats_table[0]): msg = "The number of columns read from the event statistics and simulated vs. " + \ "observed CSV files does not " + \ "match the number of columns in EventStatistics table." raise FMDBException(msg) event_stats_array = [[row[x] for x in self.eventstatistics._fields] for row in event_stats_table] event_stats_array = [self.eventstatistics(*row) for row in event_stats_array] event_stats_array = [self.cursor.mogrify('%s::eventstatistics', (row,)) for row in event_stats_array] event_stats_array = 'ARRAY[' + ','.join(event_stats_array) + ']' self.cursor.execute("SELECT update_eventstatistics(" + event_stats_array + ")") if allflows_outofdate: with open(allflows_path, 'r') as f: header = f.readline().split(',') origcols = [col.strip("\"' \n") for col in header if col] date_fields = ["month", "day", "year", "hour"] fields_min_sec = ["minute", "second"] nondate_fields = ["lotus date", "obs flow", "avg DWF", "gwi adjustment", "adjusted DWF", "gwi flow", "BWF", "iandi", "curve 1", "curve 2", "curve 3", "total"] field_mapping = { 'analysisid' : 'analysisid', 'datetime' : 'DateTime', 'lotusdate' : 'lotus date', 'obsflow' : 'obs flow', 'avgdwf' : 'avg DWF', 'gwiadjustment' : 'gwi adjustment', 'adjusteddwf' : 'adjusted DWF', 'gwiflow' : 'gwi flow', 'bwf' : 'BWF', 'iandi' : 'iandi', 'curve1' : 'curve 1', 'curve2' : 'curve 2', 'curve3' : 'curve 3', 'total' : 'total' } if len(origcols) == 18: if origcols != date_fields + fields_min_sec + nondate_fields: raise Exception("Unexpected fields encountered.") has_min_sec = True elif len(origcols) == 16: if origcols != date_fields + nondate_fields: raise Exception("Unexpected fields encountered.") has_min_sec = False else: raise Exception("Unexpected number of columns in allflows.") reader = csv.DictReader(f, fieldnames=origcols) chunk_size = 10000 row_chunks = itertools.izip_longest(*[iter(reader)]*chunk_size, fillvalue=None) for chunk in row_chunks: chunk_table = [] for row in chunk: if row: year = int(row['year']) month = int(row['month']) day = int(row['day']) if has_min_sec: hour = int(row['hour']) minute = int(row['minute']) second = int(row['second']) else: hours = row['hour'] hour_split = hours.split('.') if len(hour_split) > 1: hour = int(hour_split[0]) minutes = str(float('.' + hour_split[1]) * 60) minute_split = minutes.split('.') if len(minute_split) > 1: minute = int(minute_split[0]) seconds = str(float('.' + minute_split[1]) * 60) second_split = seconds.split('.') second = int(second_split[0]) else: minute = int(minute_split[0]) second = 0 else: hour = int(hour_split[0]) minute = 0 second = 0 dtime = datetime(year, month, day, hour, minute, second).strftime('%m/%d/%Y %H:%M:%S') for field in date_fields + fields_min_sec: if field in row.keys(): del row[field] row['DateTime'] = dtime row['analysisid'] = analysisid new_row = self.allflows(*[row[field_mapping[k]] for k in self.allflows._fields]) chunk_table.append(new_row) allflows_array = [self.cursor.mogrify('%s::allflows', (row,)) for row in chunk_table] allflows_array = 'ARRAY[' + ','.join(allflows_array) + ']' self.cursor.execute("SELECT update_allflows(" + allflows_array + ")") return 0 def _importSSOAP_SSES(self, ssoap_path, filesum_row, manholeid, siteid=None, deployment=None): sdb_filepath = os.path.join(ssoap_path, '*.sdb') sdb_filepaths = glob.glob(sdb_filepath) mdb_filepath = os.path.join(ssoap_path, '*.mdb') mdb_filepaths = glob.glob(mdb_filepath) dtime_fmt = '%Y-%m-%d %H:%M:%S' ssoap_filepaths = sdb_filepaths if sdb_filepaths else mdb_filepaths if ssoap_filepaths: ssoap_filepath_mtimes = [os.path.getmtime(path) for path in ssoap_filepaths] max_mtime = max(ssoap_filepath_mtimes) ssoap_filepath = ssoap_filepaths[ssoap_filepath_mtimes.index(max_mtime)] ssoap_fname = os.path.basename(ssoap_filepath) ssoap_mtime = datetime.fromtimestamp(os.path.getmtime(ssoap_filepath)) sites_row = OrderedDict([(k, None) for k in self.sites_type._fields]) sites_row['ssoapfilename'] = ssoap_fname sites_row['ssoapmtime'] = ssoap_mtime.strftime(dtime_fmt) sites_row['manholeid'] = manholeid sites_row['siteid'] = siteid sites_row['deployment'] = deployment sites_row['directory'] = ssoap_path # create temp copy to work with to avoid corrupting original temp_ssoap_filepath = os.path.join(os.environ.get('TEMP'), '.temp_ssoap.mdb') if os.path.exists(temp_ssoap_filepath): os.chmod(temp_ssoap_filepath, stat.S_IWRITE) os.remove(temp_ssoap_filepath) shutil.copy(ssoap_filepath, temp_ssoap_filepath) os.chmod(temp_ssoap_filepath, stat.S_IWRITE) cnxn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=' + temp_ssoap_filepath) cursor = cnxn.cursor() cursor.execute('SELECT MeterID, RainGaugeID FROM Analyses') metergage_ids = cursor.fetchall() raingage, area, units = (None, None, None) file_conflict_excs = [] if not metergage_ids: msg = 'The SSOAP file in "' + ssoap_path + '" is missing its meter and gage.' file_conflict_excs.append(msg) if len(metergage_ids) > 1: msg = 'The SSOAP file in "' + ssoap_path + '" has multiple meters and gages.' file_conflict_excs.append(msg) else: meterid = metergage_ids[0].MeterID gageid = metergage_ids[0].RainGaugeID cursor.execute("SELECT StartDateTime, EndDateTime FROM Meters WHERE MeterID = ?", meterid) startdtime, enddtime = cursor.fetchone() sites_row['startdatetime'] = startdtime.strftime(dtime_fmt) sites_row['enddatetime'] = enddtime.strftime(dtime_fmt) cursor.execute('SELECT RaingaugeName FROM Raingauges WHERE RaingaugeID = ?', gageid) sites_row['raingage'] = str(cursor.fetchone().RaingaugeName) try: cursor.execute('SELECT Area, AreaUnitID FROM Meters WHERE MeterID = ?', meterid) except: # the Meters table in old ssoap files doesn't have AreaUnitID cursor.execute('SELECT Area FROM Meters WHERE MeterID = ?', meterid) sites_row['area'] = cursor.fetchone().Area sites_row['areaunits'] = None else: sites_row['area'], units_id = cursor.fetchone() cursor.execute('SELECT ShortLabel FROM AreaUnits WHERE AreaUnitID = ?', units_id) sites_row['areaunits'] = str(cursor.fetchone().ShortLabel) cursor.close() cnxn.close() os.remove(temp_ssoap_filepath) xls_paths = glob.glob(os.path.join(ssoap_path, '*.xls')) + glob.glob(os.path.join(ssoap_path, '*.xlsx')) xls_fnames = [os.path.basename(path) for path in xls_paths] eventnotes_pat = re.compile('rdii', re.IGNORECASE) # TODO eventnotes_fnames = [fname for fname in xls_fnames if re.search(eventnotes_pat, fname) and not fname.startswith('~')] if len(eventnotes_fnames) == 0: sites_row['eventnotesfilename'] = None elif len(eventnotes_fnames) > 1: file_conflict_excs.append('Multiple event notes spreadsheets found in ' + ssoap_path) filesum_row['haseventnotes'] = True filesum_row['filesareambiguous'] = True else: filesum_row['haseventnotes'] = True sites_row['eventnotesfilename'] = eventnotes_fnames[0] eventnotes_path = os.path.join(ssoap_path, eventnotes_fnames[0]) sites_row['eventnotesmtime'] = datetime.fromtimestamp(os.path.getmtime(eventnotes_path)).strftime(dtime_fmt) csv_paths = glob.glob(os.path.join(ssoap_path, '*.csv')) csv_fnames = [os.path.basename(path) for path in csv_paths] rtk_path = None rtk_xls = [fname for fname in xls_fnames if re.search(re.compile('simul', re.IGNORECASE), fname)] if len(rtk_xls) == 1: filesum_row['hasrtk'] = True sites_row['rtkfilename'] = rtk_xls[0] rtk_path = os.path.join(ssoap_path, rtk_xls[0]) rtk_mtime = datetime.fromtimestamp(os.path.getmtime(rtk_path)) sites_row['rtkmtime'] = rtk_mtime.strftime(dtime_fmt) if rtk_mtime < ssoap_mtime: filesum_row['modificationtimesconsistent'] = False elif len(rtk_xls) > 1: file_conflict_excs.append('Multiple RTK files found') filesum_row['hasrtk'] = True filesum_row['filesareambiguous'] = True self.cursor.execute("SELECT get_analysis_id(%s, %s, %s)", (manholeid, siteid, deployment)) analysisid = self.cursor.fetchone()[0] allflows_outofdate = True eventstats_outofdate = True all_up_to_date = False if analysisid: self.execute("SELECT SSOAPMTime, EventNotesMTime, RTKMtime FROM Sites WHERE AnalysisID = %s", (analysisid,)) db_ssoap_mtime, db_notes_mtime, db_rtk_mtime = self.fetchone() db_ssoap_mtime_str = db_ssoap_mtime.strftime(dtime_fmt) db_notes_mtime_str = db_notes_mtime.strftime(dtime_fmt) db_rtk_mtime_str = db_rtk_mtime.strftime(dtime_fmt) if db_rtk_mtime else None ssoap_uptodate = db_ssoap_mtime_str == sites_row['ssoapmtime'] notes_uptodate = db_notes_mtime_str == sites_row['eventnotesmtime'] rtk_uptodate = db_rtk_mtime_str == sites_row['rtkmtime'] if ssoap_uptodate and notes_uptodate and rtk_uptodate: all_up_to_date = True if ssoap_uptodate: allflows_outofdate = False if notes_uptodate and rtk_uptodate: eventstats_outofdate = False # TODO Rvalue code differs rvalue_xls = [fname for fname in xls_fnames if re.search('event', fname, re.IGNORECASE)] rvalue_xls = [fname for fname in rvalue_xls if not re.match('~', fname)] if len(rvalue_xls) == 1: filesum_row['hasrvalue'] = True sites_row['rvaluefilename'] = rvalue_xls[0] rvalue_path = os.path.join(ssoap_path, rvalue_xls[0]) rvalue_mtime = datetime.fromtimestamp(os.path.getmtime(rvalue_path)) if rvalue_mtime < ssoap_mtime: filesum_row['modificationtimesconsistent'] = False sites_row['rvaluemtime'] = rvalue_mtime.strftime(dtime_fmt) elif len(rvalue_xls) > 1: file_conflict_excs.append("Multiple RValue XLSs found in " + ssoap_path) filesum_row['filesareambiguous'] = True filesum_row['hasrvalue'] = True else: file_conflict_excs.append("No RValue XLSs found in " + ssoap_path) allflows_pat = re.compile('all_?flow', re.IGNORECASE) allflows_fnames = [fname for fname in csv_fnames if re.search(allflows_pat, fname)] if len(allflows_fnames) == 0: file_conflict_excs.append("No all flows file found.") elif len(allflows_fnames) > 1: filesum_row['hasallflows'] = False file_conflict_excs.append("Multiple allflows files found.") else: filesum_row['hasallflows'] = True sites_row['allflowsfilename'] = allflows_fnames[0] allflows_path = os.path.join(ssoap_path, allflows_fnames[0]) allflows_mtime = datetime.fromtimestamp(os.path.getmtime(allflows_path)) sites_row['allflowsmtime'] = allflows_mtime.strftime(dtime_fmt) if allflows_mtime < ssoap_mtime: filesum_row['modificationtimesconsistent'] = False self.update_filesum(filesum_row) if file_conflict_excs: return file_conflict_excs os.chmod(ssoap_filepath, stat.S_IREAD) self.cursor.execute("SELECT update_analysis(%s)", (self.sites_type(*sites_row.values()), )) analysisid = self.cursor.fetchone()[0] if all_up_to_date: return 0 if (allflows_outofdate or eventstats_outofdate): if filesum_row['haseventnotes']: wb = xlrd.open_workbook(eventnotes_path) sheet_name = wb.sheets()[0].name event_notes = wb.sheet_by_name(sheet_name) en_fields = ['Accept Storm', 'Comment'] eventnotes_table_raw = query_worksheet(event_notes, 'Event', en_fields, return_cols=True) new_en_fields = {'Accept Storm' : 'outlier', 'Comment' : 'notes'} eventnotes_table = {} for key in eventnotes_table_raw: if key == 'Accept Storm': eventnotes_table[new_en_fields[key]] = [x == 'No' for x in eventnotes_table_raw[key]] else: eventnotes_table[new_en_fields[key]] = eventnotes_table_raw[key] eventnotes_table['flag'] = [None for _ in range(len(eventnotes_table['outlier']))] wb = xlrd.open_workbook(rvalue_path) sheet_name = wb.sheets()[0].name rvalues = wb.sheet_by_name(sheet_name) rvalue_fields = ['Event', 'Event Start', 'Event End', 'Duration (hours)', 'I/I Volume (In.)', 'Rain Volume (In.)', 'Total R-value (ratio)', 'Peak I/I Flow (mgd)', 'Peak Total Flow (mgd)', 'EventPeak Rainfall (In./15 min)', 'Observed Flow (mgd)', 'GWI Flow (mgd)', 'Base Wastewater Flow (mgd)', 'Rainfall Start Date', 'Rainfall End Date', 'Rainfall Duration (hours)'] raw_rvalue_table = query_worksheet(rvalues, 'Event', return_cols=True, cols=rvalue_fields) new_rvalue_fields = {'Event' : 'event', 'Event Start' : 'startdatetime', 'Event End' : 'enddatetime', 'Duration (hours)' : 'duration', 'I/I Volume (In.)' : 'iivolume_in', 'Rain Volume (In.)' : 'rainvolume_in', 'Total R-value (ratio)' : 'totalrvalue', 'Peak I/I Flow (mgd)' : 'peakiiflow_mgd', 'Peak Total Flow (mgd)' : 'peaktotalflow', 'EventPeak Rainfall (In./15 min)' : 'rainfall_in_15min', 'Observed Flow (mgd)' : 'observedflow_mgd', 'GWI Flow (mgd)' : 'gwiflow_mgd', 'Base Wastewater Flow (mgd)' : 'basewastewaterflow_mgd', 'Rainfall Start Date' : 'rainfall_startdatetime', 'Rainfall End Date' : 'rainfall_enddatetime', 'Rainfall Duration (hours)' : 'rainfallduration_hrs'} rvalue_table = {} for key in raw_rvalue_table: rvalue_table[new_rvalue_fields[key]] = raw_rvalue_table[key][1:] # drop the first row of column numbers rvalue_table['peakfactor'] = [None for _ in range(len(rvalue_table['gwiflow_mgd']))] if not filesum_row['haseventnotes']: num_events = len(rvalue_table['duration']) eventnotes_table = { 'outlier' : [False for _ in range(num_events)], 'notes' : ['' for _ in range(num_events)], 'flag' : [None for _ in range(num_events)] } #new_rtk_fields = { # "R1(ratio)" : 'r1', # "T1(hours)" : 't1', # "K1(ratio)" : 'k1', # "R2(ratio)" : 'r2', # "T2(hours)" : 't2', # "K2(ratio)" : 'k2', # "R3(ratio)" : 'r3', # "T3(hours)" : 't3', # "K3(ratio)" : 'k3', # "Peak 15 Minute Rainfall(inches)" : 'peakrainfall', # "Simulated Volume(total R ratio)" : 'simvolume', # "Simulated Peak(mgd)" : 'simpeak'} new_rtk_fields = { "R1" : 'r1', "T1" : 't1', "K1" : 'k1', "R2" : 'r2', "T2" : 't2', "K2" : 'k2', "R3" : 'r3', "T3" : 't3', "K3" : 'k3', "Peak 15 Minute Rainfall" : 'peakrainfall', "Simulated Volume" : 'simvolume', "Simulated Peak" : 'simpeak'} if rtk_path: wb = xlrd.open_workbook(rtk_path) sheet_name = wb.sheets()[0].name rtks = wb.sheet_by_name(sheet_name) rtk_fields = ["R1", "T1", "K1", "R2", "T2", "K2", "R3", "T3", "K3", "Peak 15 Minute Rainfall", "Simulated Volume", "Simulated Peak"] #rtk_fields = ["R1(ratio)", "T1(hours)", # "K1(ratio)", "R2(ratio)", "T2(hours)", "K2(ratio)", "R3(ratio)", "T3(hours)", "K3(ratio)", # "Peak 15 Minute Rainfall(inches)", "Simulated Volume(total R ratio)", "Simulated Peak(mgd)"] raw_rtk_table = query_worksheet(rtks, 'Event', cols=rtk_fields, return_cols=True) rtk_table = {} for key in raw_rtk_table: rtk_table[new_rtk_fields[key]] = raw_rtk_table[key][1:] # drop the first row of column numbers else: rtk_table = {} for name in new_rtk_fields.values(): rtk_table[name] = [None for _ in range(len(rvalue_table))] #rtk_table = [dict(zip(new_rtk_fields.values(), itertools.cycle([None]))) for _ in range(len(rvalue_table))] event_stats_table_cols = OrderedDict(rvalue_table.items() + rtk_table.items() + eventnotes_table.items()) event_stats_table_rows = zip(*event_stats_table_cols.values()) event_stats_table = [] for row in event_stats_table_rows: new_row = dict(zip(event_stats_table_cols.keys(), row)) new_row['analysisid'] = analysisid event_stats_table.append(new_row) if len(self.eventstatistics._fields) != len(event_stats_table[0]): msg = "The number of columns read from the event statistics and simulated vs. " + \ "observed CSV files does not " + \ "match the number of columns in EventStatistics table." raise FMDBException(msg) datetime_fields = ['startdatetime', 'enddatetime', 'rainfall_startdatetime', 'rainfall_enddatetime'] days_between_epochs = 25569 seconds_in_day = 86400 four_hours = 60 * 60 * 4 for row in event_stats_table: for field in datetime_fields: if isinstance(row[field], basestring): row[field] = datetime.strptime(row[field], '%m/%d/%Y %H:%M') else: row[field] = datetime.fromtimestamp((row[field] - days_between_epochs) * seconds_in_day + four_hours) event_stats_array = [[row[x] for x in self.eventstatistics._fields] for row in event_stats_table] event_stats_array = [self.eventstatistics(*row) for row in event_stats_array] event_stats_array = [self.cursor.mogrify('%s::eventstatistics', (row,)) for row in event_stats_array] event_stats_array = 'ARRAY[' + ','.join(event_stats_array) + ']' self.cursor.execute("SELECT update_eventstatistics(" + event_stats_array + ")") if allflows_outofdate: with open(allflows_path, 'r') as f: header = f.readline().split(',') origcols = [col.strip("\"' \n") for col in header if col] date_fields = ["month", "day", "year", "hour"] fields_min_sec = ["minute", "second"] nondate_fields = ["lotus date", "obs flow", "avg DWF", "gwi adjustment", "adjusted DWF", "gwi flow", "BWF", "iandi", "curve 1", "curve 2", "curve 3", "total"] field_mapping = { 'analysisid' : 'analysisid', 'datetime' : 'DateTime', 'lotusdate' : 'lotus date', 'obsflow' : 'obs flow', 'avgdwf' : 'avg DWF', 'gwiadjustment' : 'gwi adjustment', 'adjusteddwf' : 'adjusted DWF', 'gwiflow' : 'gwi flow', 'bwf' : 'BWF', 'iandi' : 'iandi', 'curve1' : 'curve 1', 'curve2' : 'curve 2', 'curve3' : 'curve 3', 'total' : 'total' } if len(origcols) == 18: if origcols != date_fields + fields_min_sec + nondate_fields: raise Exception("Unexpected fields encountered.") has_min_sec = True elif len(origcols) == 16: if origcols != date_fields + nondate_fields: raise Exception("Unexpected fields encountered.") has_min_sec = False else: raise Exception("Unexpected number of columns in allflows.") reader = csv.DictReader(f, fieldnames=origcols) chunk_size = 10000 row_chunks = itertools.izip_longest(*[iter(reader)]*chunk_size, fillvalue=None) for chunk in row_chunks: chunk_table = [] for row in chunk: if row: year = int(row['year']) month = int(row['month']) day = int(row['day']) if has_min_sec: hour = int(row['hour']) minute = int(row['minute']) second = int(row['second']) else: hours = row['hour'] hour_split = hours.split('.') if len(hour_split) > 1: hour = int(hour_split[0]) minutes = str(float('.' + hour_split[1]) * 60) minute_split = minutes.split('.') if len(minute_split) > 1: minute = int(minute_split[0]) seconds = str(float('.' + minute_split[1]) * 60) second_split = seconds.split('.') second = int(second_split[0]) else: minute = int(minute_split[0]) second = 0 else: hour = int(hour_split[0]) minute = 0 second = 0 dtime = datetime(year, month, day, hour, minute, second).strftime('%m/%d/%Y %H:%M:%S') for field in date_fields + fields_min_sec: if field in row.keys(): del row[field] row['DateTime'] = dtime row['analysisid'] = analysisid new_row = self.allflows(*[row[field_mapping[k]] for k in self.allflows._fields]) chunk_table.append(new_row) allflows_array = [self.cursor.mogrify('%s::allflows', (row,)) for row in chunk_table] allflows_array = 'ARRAY[' + ','.join(allflows_array) + ']' self.cursor.execute("SELECT update_allflows(" + allflows_array + ")") return 0 #def collect_ssoap(root=None): # if not root: # root = os.path.join("\\\\pwdoows1", "Modeling", "Data", "Temporary Monitors", # "Flow Monitoring", "Flow Monitoring by ManholeID") # # manholes = [d for d in os.listdir(root) if not any(ch in string.ascii_lowercase for ch in dirname)]
Python
__all__ = ['pyfmdb']
Python
from sys import stdin from Token import Token class Lexer: def __init__(self): self.l = "" def nextToken(self): if (len(self.l) == 0): c = str(stdin.read(1)) s = "" while(c.isdigit()): s += c c = str(stdin.read(1)) if (len(s) > 0): t = Token(s, "INT") self.l = c return t else: if (c == " "): return self.nextToken() else: return self.__toToken(c) else: if (self.l == " "): self.l = "" return self.nextToken() else: x = self.l self.l = "" return self.__toToken(x) def __toToken(self, c): t = None if (c == "*"): t = Token(c, "MULT") elif (c == "+"): t = Token(c, "PLUS") elif (c == "("): t = Token(c, "LPAREN") elif (c == ")"): t = Token(c, "RPAREN") elif (c == "\n"): t = Token(c, "END") else: t = Token(c, "ERROR") return t
Python
from sys import stdin from sys import exit class Interpreter: def __init__(self): self.stack = [] self.s = stdin.readlines() self.errormsg = "" def interpret(self): if (len(self.s) < 2): self.errormsg = "No input" self.error() for line in self.s: if line[0] == 'P': if line[0:4] == "PUSH": num = line[5:len(line)] for i in range (0, len(num) -1): if not (num[i].isdigit()): self.errormsg = "Invalid operation" self.error() self.stack.append(int(num)) elif line[0:5] == "PRINT": print self.stack.pop() else: self.errormsg = "WTF" self.error() elif line[0] == 'A': if (line[0:3] == "ADD"): if len(self.stack) > 1: self.stack.append(self.stack.pop() + self.stack.pop()) else: self.errormsg = "ADD" self.error() else: self.error() elif line[0] == 'M': if (line[0:4] == "MULT"): if len(self.stack) > 1: self.stack.append(self.stack.pop() * self.stack.pop()) else: self.error() else: self.error() elif line[0] == 'E': if (line[0:6] == "ERROR"): self.errormsg = "Syntax error" self.error() else: self.errormsg = "ERROR" self.error() def error(self): print "Error for operator: " + self.errormsg exit() def main(self): while self.s != "PRINT": self.interpret() print self.stack.pop() intr = Interpreter() intr.interpret()
Python
from Lexer import Lexer from Parser import Parser import sys class Compiler: if __name__ == "__main__": myLexer = Lexer() myParser = Parser(myLexer) myParser.parse()
Python
from Lexer import Lexer from sys import exit from sys import stdout from sys import stdin class Parser: def __init__(self,l): self.lex = l self.t = None def parse(self): self.t = self.lex.nextToken() self._expr() print "PRINT" if not (stdin.isatty()): if (stdin.read(1)): print "ERROR" def _expr(self): self._term() if self.t.tCode == "PLUS": self.t = self.lex.nextToken() self._expr() print "ADD" def _term(self): self._factor() if self.t.tCode == "MULT": self.t = self.lex.nextToken() self._term() print "MULT" def _factor(self): if self.t.tCode == "INT": print "PUSH " + self.t.lexeme self.t = self.lex.nextToken() elif self.t.tCode == "LPAREN": self.t = self.lex.nextToken() self._expr() if self.t.tCode != "RPAREN": self._synError() self.t = self.lex.nextToken() else: self._synError() def _synError(self): print "Syntax error" exit()
Python
class Token: def __init__(self, lex, tokencode): self.tCode = tokencode self.lexeme = lex
Python
# Django settings for pastesite project. import os STATIC_PATH = os.getcwd() DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'paste.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '3306' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Asia/Shanghai' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'zh-cn' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = STATIC_PATH + '/site_media/' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/site_media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'tmm@5ufh12g6*3ug*-y8((6t7be=(5%2aj=1a(dh6_%o9-p0i5' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.CacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'pastesite.urls' CACHE_BACKEND = "dummy:///" #CACHE_BACKEND = "file:///home/icefox/pastesite/cache/django_cache?timeout=3600" TEMPLATE_DIRS = ( STATIC_PATH + '/templates', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'pastesite.pastebin', )
Python
#!/usr/bin/python import os, sys _PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _PROJECT_DIR) sys.path.insert(0, os.path.dirname(_PROJECT_DIR)) _PROJECT_NAME = _PROJECT_DIR.split('/')[-1] os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % _PROJECT_NAME from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false")
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH + "/site_media/"}), (r'^$', 'pastesite.pastebin.views.create'), (r'^register/$', 'pastesite.pastebin.views.register'), (r'^about/$', 'pastesite.pastebin.views.about'), (r'^login/$', 'pastesite.pastebin.views.user_login'), (r'^logout/$', 'pastesite.pastebin.views.user_logout'), (r'^ranks/$', 'pastesite.pastebin.views.ranks'), (r'^user/(?P<username>\w+)/$', 'pastesite.pastebin.views.user'), (r'^paste/', include('pastesite.pastebin.urls')), )
Python
#!/usr/bin/python import os, sys _PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _PROJECT_DIR) sys.path.insert(0, os.path.dirname(_PROJECT_DIR)) _PROJECT_NAME = _PROJECT_DIR.split('/')[-1] os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % _PROJECT_NAME from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false")
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
# Django settings for improgrammer project. import sys, os CURDIR = os.getcwd() DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = './programmer.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'bg7cqu3@klbxj3cencg*%8j-v@1g=^0+_#n$#xbfq&ttgrc*xk' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'improgrammer.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. CURDIR + '/templates', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'improgrammer.programmer', )
Python
from django.db import models from django.contrib.auth.models import User # Create your models here. class Member(models.Model): member = models.ForeignKey(User, related_name = 'member_user') lastLoginTime = models.DateTimeField(auto_now_add = True) entryCount = models.IntegerField(default = 0) commentCount = models.IntegerField(default = 0) motto = models.CharField(max_length = 255) def __unicode__(self): return self.User.username class Message(models.Model): member = models.ForeignKey(Member, related_name = 'message_user') createdTime = models.DateTimeField(auto_now_add = True) content = models.TextField() isRead = models.BooleanField(default = False) def __unicode__(self): return self.id class Category(models.Model): name = models.CharField(max_length = 75) entryCount = models.IntegerField(default = 0) def __unicode__(self): return self.name class Tag(models.Model): name = models.CharField(max_length = 75) entryCount = models.IntegerField(default = 0) def __unicode__(self): return self.name class Entry(models.Model): name = models.CharField(max_length = 255) member = models.ForeignKey(Member, related_name = 'entry_user') category = models.ForeignKey(Category) commentCount = models.IntegerField(default = 0) tags = models.ManyToManyField(Tag) def __unicode__(self): return self.name class Comment(models.Model): member = models.ForeignKey(Member, related_name = 'comment_user') entry = models.ForeignKey(Entry) content = models.TextField() good = models.IntegerField(default = 0) bad = models.IntegerField(default = 0) isBest = models.BooleanField(default = False) createdTime = models.DateTimeField(auto_now_add = True) modifiedTime = models.DateTimeField(auto_now = True) def __unicode__(self): return self.entry.name + '-' + self.member.user.username
Python
#-*-coding:utf-8-*- from django import forms class RegisterForm(forms.Form): username = forms.CharField(max_length = 75, label = u'用户名') password = forms.CharField(widget = forms.PasswordInput, label = u'密码') password_confirm = forms.CharField(widget = forms.PasswordInput, label = u'密码确认') email = forms.EmailField(label = '邮件地址') def password_confirm_clean(self): if self.cleaned_data['password'] != self.cleaned['password_confirm']: raise u'两次密码不一样' else: return self.cleaned_data['password_confirm'] class LoginForm(forms.Form): username = forms.CharField(max_length = 75, label = u'用户名') password = forms.CharField(widget = forms.PasswordInput, label = u'密码')
Python
#-*-coding:utf-8-*- from improgrammer.programmer.models import * from improgrammer.programmer.forms import * from django.shortcuts import render_to_response from django.http import HttpRequest from django.http import HttpResponse from django.http import HttpResponseRedirect from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.contrib.auth.models import User from django.contrib.auth import authenticate, login # Create your views here. def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] == form.cleaned_data['password_confirm']: user = User(username = form.cleaned_data['username'], password = form.cleaned_data['password'], email = form.cleaned_data['email']) user.save() return HttpResponseRedirect('/') else: form.errors['password'] = 'not same' else: form = RegisterForm() return render_to_response('register.html', {'form':form}) def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid: user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password']) if user is not None: login(request, user) return HttpResponseRedirect('/') else: return render_to_response('message.html', {'code':101}) else: form = LoginForm() return render_to_response('login.html', {'form' : form}) def home(request): return render_to_response('home.html')
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^improgrammer/', include('improgrammer.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), (r'^register$', 'improgrammer.programmer.views.register'), (r'^login$', 'improgrammer.programmer.views.login'), (r'^$', 'improgrammer.programmer.views.home'), )
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
# Django settings for pinkewang project. import os CURRENT_PATH = os.getcwd() DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('kingheaven', 'mykingheaven@gmail.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'pinkewang' # Or path to database file if using sqlite3. DATABASE_USER = 'root' # Not used with sqlite3. DATABASE_PASSWORD = 'root' # Not used with sqlite3. DATABASE_HOST = 'localhost' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '3306' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Asia/Shanghai' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'zh-cn' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = CURRENT_PATH + '/site_media/' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/site_media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'ou=32vjjf43u29(j1np02z9kp=4n_%jg7cbl)o8yl!p(=+4+5c' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'pinkewang.urls' TEMPLATE_DIRS = ( CURRENT_PATH + '/templates', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'pinkewang.member', 'pinkewang.share', 'pinkewang.pinke', 'django.contrib.admin', )
Python
from django.db import models # Create your models here.
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * urlpatterns = patterns('pinkewang.pinke.views', )
Python
# Create your views here.
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
#-*-coding:utf-8-*- from django.db import models from django.contrib import admin from django.db.models import permalink from django.contrib.auth.models import User # Create your models here. GENDER_CHOICES= (('m', u'先生'), ('f', u'女士')) class Member(models.Model): user = models.ForeignKey(User) telephone = models.CharField(max_length = 15, blank = True) qq = models.CharField(max_length = 100, blank = True) gender = models.CharField(max_length = 1, choices = GENDER_CHOICES, blank = True) shareCreatedNum = models.IntegerField(default = 0) #发布的分享 shareCommentedNum = models.IntegerField(default = 0) #分享的回复 pinkeCreatedNum = models.IntegerField(default = 0) #发布的拼客 pinkeJoinedNum = models.IntegerField(default = 0) #参加的拼客 pinkeCommentedNum = models.IntegerField(default = 0) #拼客的回复 avatar = models.ImageField(upload_to="avatars", blank = True) def __unicode__(self): return self.user.username @permalink def get_absolute_url(self): return "/profile/%d/" % self.user.id admin.site.register(Member)
Python
from django import forms from django.forms import ModelForm from pinkewang.member.models import * class RegisterForm(forms.Form): username = forms.CharField(max_length = 15) password = forms.CharField(max_length = 15, widget = forms.PasswordInput) passwordConfirm = forms.CharField(max_length = 15, widget = forms.PasswordInput) email = forms.EmailField() agreement = forms.BooleanField() class LoginForm(forms.Form): username = forms.CharField(min_length = 5, max_length = 15) password = forms.CharField(min_length = 5, max_length = 15, widget = forms.PasswordInput) class ProfileForm(ModelForm): class Meta: model = Member fields = ['telephone', 'qq', 'gender', 'avatar']
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
#-*-coding:utf-8-*- # Create your views here. from django.shortcuts import * from django.contrib.auth.models import User from django.contrib.auth import * from django.contrib.auth.decorators import * from django.template import * from pinkewang.member.forms import * from pinkewang.member.models import * def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password']) user.save() member = Member(user = user) member.save() return HttpResponseRedirect('/thanks/') else: form = RegisterForm() return render_to_response('member/register.html', {'form':form}) def home_page(request): members = Member.objects.all()[:10] return render_to_response('home_page.html', {'members':members}, context_instance=RequestContext(request)) def user_login(request): if request.POST: form = LoginForm(request.POST) if form.is_valid(): user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password']) if user is not None: login(request, user) return redirect("/") else: form = LoginForm() return render_to_response('member/login.html', {'form': form}) def user_logout(request): logout(request) return redirect("/") def profile(request, id): user_info = User.objects.get(id = id) member = Member.objects.get(user = user_info.id) return render_to_response('member/profile.html', {'user_info': user_info, 'member': member}, context_instance=RequestContext(request)) @login_required def manage(request): member = Member.objects.get(user = request.user.id) if request.POST: form = ProfileForm(request.POST, instance = member) if form.is_valid(): form.save() return redirect("/manage/") else: form = ProfileForm(instance = member) return render_to_response('member/manage.html', {'form': form}, context_instance=RequestContext(request))
Python
from django.conf.urls.defaults import * import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pinkewang/', include('pinkewang.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('pinkewang.member.views', (r'^$', 'home_page'), (r'^register/$', 'register'), (r'^login/$', 'user_login'), (r'^logout/$', 'user_logout'), (r'^manage/$', 'manage'), (r'^profile/(?P<id>\d+)/$', 'profile'), ) urlpatterns += patterns('', (r'^share/', include('pinkewang.share.urls')), ) urlpatterns += patterns('', (r'^pinke/', include('pinkewang.pinke.urls')), )
Python
from django.db import models # Create your models here.
Python