pe

package module
v1.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 25, 2021 License: MIT Imports: 20 Imported by: 0

README

Portable Executable Parser GoDoc Report Card codecov GitHub Workflow Status

pe is a go package for parsing the portable executable file format. This package was designed with malware analysis in mind, and being resistent to PE malformations.

Table of content

Features

  • Works with PE32/PE32+ file fomat.
  • Supports Intel x86/AMD64/ARM7ARM7 Thumb/ARM8-64/IA64/CHPE architectures.
  • MS DOS header.
  • Rich Header (calculate checksum).
  • NT Header (file header + optional header).
  • COFF symbol table and string table.
  • Sections headers + entropy calculation.
  • Data directories
    • Import Table + ImpHash calculation.
    • Export Table
    • Resource Table
    • Exceptions Table
    • Security Table + Authentihash calculation.
    • Relocations Table
    • Debug Table (CODEVIEW, POGO, VC FEATURE, REPRO, FPO, EXDLL CHARACTERISTICS debug types).
    • TLS Table
    • Load Config Directory (SEH, GFID, GIAT, Guard LongJumps, CHPE, Dynamic Value Reloc Table, Enclave Configuration, Volatile Metadata tables).
    • Bound Import Table
    • Delay Import Table
    • COM Table (CLR Metadata Header, Metadata Table Streams)
  • Report several anomalies

Installing

Using this go package is easy. First, use go get to install the latest version of the library. This command will install the pedumper executable along with the library and its dependencies:

go get -u github.com/saferwall/pe

Next, include pe package in your application:

import "github.com/saferwall/pe"

Using the library

package main

import (
	peparser "github.com/saferwall/pe"
)

func main() {
    filename := "C:\\Binaries\\notepad.exe"
    pe, err := peparser.New(filename, nil)
	if err != nil {
		log.Fatalf("Error while opening file: %s, reason: %v", filename, err)
    }
    
    err = pe.Parse()
    if err != nil {
        log.Fatalf("Error while parsing file: %s, reason: %v", filename, err)
    }

Start by instantiating a pe object by called the New() method, which takes the file path to the file to be parsed and some optional options.

Afterwards, a call to the Parse() method will give you access to all the different part of the PE format, directly accessible to be used. Here is the definition of the struct:

type File struct {
	DosHeader    ImageDosHeader              `json:",omitempty"`
	RichHeader   *RichHeader                 `json:",omitempty"`
	NtHeader     ImageNtHeader               `json:",omitempty"`
	COFF         *COFF                        `json:",omitempty"`
	Sections     []Section                   `json:",omitempty"`
	Imports      []Import                    `json:",omitempty"`
	Export       *Export                     `json:",omitempty"`
	Debugs       []DebugEntry                `json:",omitempty"`
	Relocations  []Relocation                `json:",omitempty"`
	Resources    *ResourceDirectory          `json:",omitempty"`
	TLS          *TLSDirectory               `json:",omitempty"`
	LoadConfig   *LoadConfig                 `json:",omitempty"`
	Exceptions   []Exception                 `json:",omitempty"`
	Certificates *Certificate                `json:",omitempty"`
	DelayImports []DelayImport               `json:",omitempty"`
	BoundImports []BoundImportDescriptorData `json:",omitempty"`
	GlobalPtr    uint32                      `json:",omitempty"`
	CLR          *CLRData                    `json:",omitempty"`
	IAT          []IATEntry                  `json:",omitempty"`
	Header       []byte
	data         mmap.MMap
	closer       io.Closer
	Is64         bool
	Is32         bool
	Anomalies    []string `json:",omitempty"`
	size         uint32
	f            *os.File
	opts         *Options
}
PE Header

As mentionned before, all members of the struct are directly (no getters/setters) accessible, additionally, the fields types has been preserved as the spec defines them, that means if you need to show the prettified version of an int type, you have to call the corresponding function.

	fmt.Printf("Magic is: %x\n", pe.DosHeader.Magic)
    fmt.Printf("Signature is: %x\n", pe.NtHeader.Signature)
	fmt.Printf("Machine is: %x, Meaning: %s\n", pe.NtHeader.FileHeader.Machine, pe.PrettyMachineType())

Output:

Magic is: 5a4d
Signature is: 4550
Machine is: 8664, Meaning: x64
Iterating over sections
for _, sec := range pe.Sections {
    fmt.Printf("Section Name : %s\n", sec.NameString())
    fmt.Printf("Section VirtualSize : %x\n", sec.Header.VirtualSize)
    fmt.Printf("Section Flags : %x, Meaning: %v\n\n",
        sec.Header.Characteristics, sec.PrettySectionFlags())
}

Output:

Section Name : .text
Section VirtualSize : 2ea58
Section Flags : 60500060, Meaning: [Align8Bytes Readable Align16Bytes Executable Contains Code Initialized Data Align1Bytes]

Section Name : .data
Section VirtualSize : 58
Section Flags : c0500040, Meaning: [Readable Initialized Data Writable Align1Bytes Align16Bytes Align8Bytes]

Section Name : .rdata
Section VirtualSize : 18d0
Section Flags : 40600040, Meaning: [Align2Bytes Align8Bytes Readable Initialized Data Align32Bytes]

...

Roadmap

  • imports MS-styled names demangling
  • PE: VB5 and VB6 typical structures: project info, DLLCall-imports, referenced modules, object table

Fuzz Testing

To validate the parser we use the go-fuzz and a corpus of known malformed and tricky PE files from corkami.

References

Documentation

Index

Constants

View Source
const (
	// An unknown value that is ignored by all tools.
	ImageDebugTypeUnknown = 0

	// The COFF debug information (line numbers, symbol table, and string table).
	// This type of debug information is also pointed to by fields in the file headers.
	ImageDebugTypeCOFF = 1

	// The Visual C++ debug information.
	ImageDebugTypeCodeview = 2

	// The frame pointer omission (FPO) information. This information tells the
	// debugger how to interpret nonstandard stack frames, which use the EBP
	// register for a purpose other than as a frame pointer.
	ImageDebugTypeFPO = 3

	// The location of DBG file.
	ImageDebugTypeMisc = 4

	// A copy of .pdata section.
	ImageDebugTypeException = 5

	// Reserved.
	ImageDebugTypeFixup = 6

	// The mapping from an RVA in image to an RVA in source image.
	ImageDebugTypeOmapToSrc = 7

	// The mapping from an RVA in source image to an RVA in image.
	ImageDebugTypeOmapFromSrc = 8

	// Reserved for Borland.
	ImageDebugTypeBorland = 9

	// Reserved.
	ImageDebugTypeReserved10 = 10

	// Reserved.
	ImageDebugTypeClsid = 11

	// Visual C++ features (/GS counts /sdl counts and guardN counts)
	ImageDebugTypeVCFeature = 12

	// Pogo aka PGO aka Profile Guided Optimization.
	ImageDebugTypePOGO = 13

	// Incremental Link Time Code Generation (iLTCG)
	ImageDebugTypeILTCG = 14

	// Intel MPX
	ImageDebugTypeMPX = 15

	// PE determinism or reproducibility.
	ImageDebugTypeRepro = 16

	// Extended DLL characteristics bits.
	ImageDebugTypeExDllCharacteristics = 20
)

The following values are defined for the Type field of the debug directory entry:

View Source
const (
	// CVSignatureRSDS represents the CodeView signature 'SDSR'.
	CVSignatureRSDS = 0x53445352

	// CVSignatureNB10 represents the CodeView signature 'NB10'.
	CVSignatureNB10 = 0x3031424e
)
View Source
const (
	// FrameFPO indicates a frame of type FPO.
	FrameFPO = 0x0

	// FrameTrap indicates a frame of type Trap.
	FrameTrap = 0x1

	// FrameTSS indicates a frame of type TSS.
	FrameTSS = 0x2

	// FrameNonFPO indicates a frame of type Non-FPO.
	FrameNonFPO = 0x3
)
View Source
const (
	// POGOTypePGU represents a signature for an undocumented PGO sub type.
	POGOTypePGU = 0x50475500
	// POGzOTypePGI represents a signature for an undocumented PGO sub type.
	POGzOTypePGI = 0x50474900
	// POGOTypePGO represents a signature for an undocumented PGO sub type.
	POGOTypePGO = 0x50474F00
	// POGOTypeLTCG represents a signature for an undocumented PGO sub type.
	POGOTypeLTCG = 0x4c544347
)
View Source
const (
	// The image file contains IL code only, with no embedded native unmanaged
	// code except the start-up stub (which simply executes an indirect jump to
	// the CLR entry point).
	COMImageFlagsILOnly = 0x00000001

	// The image file can be loaded only into a 32-bit process.
	COMImageFlags32BitRequired = 0x00000002

	// This flag is obsolete and should not be set. Setting it—as the IL
	// assembler allows, using the .corflags directive—will render your module
	// unloadable.
	COMImageFlagILLibrary = 0x00000004

	// The image file is protected with a strong name signature.
	COMImageFlagsStrongNameSigned = 0x00000008

	// The executable’s entry point is an unmanaged method. The EntryPointToken/
	// EntryPointRVA field of the CLR header contains the RVA of this native
	// method. This flag was introduced in version 2.0 of the CLR.
	COMImageFlagsNativeEntrypoint = 0x00000010

	// The CLR loader and the JIT compiler are required to track debug
	// information about the methods. This flag is not used.
	COMImageFlagsTrackDebugData = 0x00010000

	// The image file can be loaded into any process, but preferably into a
	// 32-bit process. This flag can be only set together with flag
	// COMIMAGE_FLAGS_32BITREQUIRED. When set, these two flags mean the image
	// is platformneutral, but prefers to be loaded as 32-bit when possible.
	// This flag was introduced in CLR v4.0
	COMImageFlags32BitPreferred = 0x00020000
)

COM+ Header entry point flags.

View Source
const (
	// V-table slots are 32-bits in size.
	CORVTable32Bit = 0x01

	// V-table slots are 64-bits in size.
	CORVTable64Bit = 0x02

	//  The thunk created by the common language runtime must provide data
	// marshaling between managed and unmanaged code.
	CORVTableFromUnmanaged = 0x04

	// The thunk created by the common language runtime must provide data
	// marshaling between managed and unmanaged code. Current appdomain should
	// be selected to dispatch the call.
	CORVTableFromUnmanagedRetainAppDomain = 0x08

	// Call most derived method described by
	CORVTableCallMostDerived = 0x10
)

V-table constants.

View Source
const (
	// The current module descriptor.
	Module = 0
	// Class reference descriptors.
	TypeRef = 1
	// Class or interface definition descriptors.
	TypeDef = 2
	// A class-to-fields lookup table, which does not exist in optimized
	// metadata (#~ stream).
	FieldPtr = 3
	// Field definition descriptors.
	Field = 4
	// A class-to-methods lookup table, which does not exist in
	// optimized metadata (#~ stream).
	MethodPtr = 5
	// Method definition descriptors.
	Method = 6
	// A method-to-parameters lookup table, which does not exist in optimized
	// metadata (#~ stream).
	ParamPtr = 7
	// Parameter definition descriptors.
	Param = 8
	// Interface implementation descriptors.
	InterfaceImpl = 9
	// Member (field or method) reference descriptors.
	MemberRef = 10
	// Constant value descriptors that map the default values stored in the
	// #Blob stream to respective fields, parameters, and properties.
	Constant = 11
	// Custom attribute descriptors.
	CustomAttribute = 12
	// Field or parameter marshaling descriptors for managed/unmanaged
	// interoperations.
	FieldMarshal = 13
	// Security descriptors.
	DeclSecurity = 14
	// Class layout descriptors that hold information about how the loader
	// should lay out respective classes.
	ClassLayout = 15
	// Field layout descriptors that specify the offset or ordinal of
	// individual fields.
	FieldLayout = 16
	// Stand-alone signature descriptors. Signatures per se are used in two
	// capacities: as composite signatures of local variables of methods and as
	// parameters of the call indirect (calli) IL instruction.
	StandAloneSig = 17
	// A class-to-events mapping table. This is not an intermediate lookup
	// table, and it does exist in optimized metadata.
	EventMap = 18
	// An event map–to–events lookup table, which does not exist in optimized
	// metadata (#~ stream).
	EventPtr = 19
	// Event descriptors.
	Event = 20
	// A class-to-properties mapping table. This is not an intermediate lookup
	// table, and it does exist in optimized metadata.
	PropertyMap = 21
	// A property map–to–properties lookup table, which does not exist in
	// optimized metadata (#~ stream).
	PropertyPtr = 22
	// Property descriptors.
	Property = 23
	// Method semantics descriptors that hold information about which method is
	// associated with a specific property or event and in what capacity.
	MethodSemantics = 24
	// Method implementation descriptors.
	MethodImpl = 25
	// Module reference descriptors.
	ModuleRef = 26
	// Type specification descriptors.
	TypeSpec = 27
	// Implementation map descriptors used for the platform invocation
	// (P/Invoke) type of managed/unmanaged code interoperation.
	ImplMap = 28
	// Field-to-data mapping descriptors.
	FieldRVA = 29
	// Edit-and-continue log descriptors that hold information about what
	// changes have been made to specific metadata items during in-memory
	// editing. This table does not exist in optimized metadata (#~ stream)
	ENCLog = 30
	// Edit-and-continue mapping descriptors. This table does not exist in
	// optimized metadata (#~ stream).
	ENCMap = 31
	// The current assembly descriptor, which should appear only in the prime
	// module metadata.
	Assembly = 32
	// This table is unused.
	AssemblyProcessor = 33
	// This table is unused.
	AssemblyOS = 34
	// Assembly reference descriptors.
	AssemblyRef = 35
	// This table is unused.
	AssemblyRefProcessor = 36
	// This table is unused.
	AssemblyRefOS = 37
	// File descriptors that contain information about other files in the
	// current assembly.
	FileMD = 38
	// Exported type descriptors that contain information about public classes
	// exported by the current assembly, which are declared in other modules of
	// the assembly. Only the prime module of the assembly should carry this
	// table.
	ExportedType = 39
	// Managed resource descriptors.
	ManifestResource = 40
	// Nested class descriptors that provide mapping of nested classes to their
	// respective enclosing classes.
	NestedClass = 41
	//  Type parameter descriptors for generic (parameterized) classes and
	// methods.
	GenericParam = 42
	// Generic method instantiation descriptors.
	MethodSpec = 43
	// Descriptors of constraints specified for type parameters of generic
	// classes and methods
	GenericParamConstraint = 44
)

Metadata Tables constants.

View Source
const (
	StringStream = 0
	GUIDStream   = 1
	BlobStream   = 2
)

Heaps Streams Bit Positions.

View Source
const (

	// UnwFlagNHandler - The function has no handler.
	UnwFlagNHandler = uint8(0x0)

	// UnwFlagEHandler - The function has an exception handler that should
	// be called when looking for functions that need to examine exceptions.
	UnwFlagEHandler = uint8(0x1)

	// UnwFlagUHandler - The function has a termination handler that should
	// be called when unwinding an exception.
	UnwFlagUHandler = uint8(0x2)

	// UnwFlagChainInfo - This unwind info structure is not the primary one
	// for the procedure. Instead, the chained unwind info entry is the contents
	// of a previous RUNTIME_FUNCTION entry. For information, see Chained unwind
	// info structures. If this flag is set, then the UNW_FLAG_EHANDLER and
	// UNW_FLAG_UHANDLER flags must be cleared. Also, the frame register and
	// fixed-stack allocation field  must have the same values as in the primary
	// unwind info.
	UnwFlagChainInfo = uint8(0x4)
)
View Source
const (
	// Push a nonvolatile integer register, decrementing RSP by 8. The
	// operation info is the number of the register. Because of the constraints
	// on epilogs, UWOP_PUSH_NONVOL unwind codes must appear first in the
	// prolog and correspondingly, last in the unwind code array. This relative
	// ordering applies to all other unwind codes except UWOP_PUSH_MACHFRAME.
	UwOpPushNonVol = uint8(0)

	// Allocate a large-sized area on the stack. There are two forms. If the
	// operation info equals 0, then the size of the allocation divided by 8 is
	// recorded in the next slot, allowing an allocation up to 512K - 8. If the
	// operation info equals 1, then the unscaled size of the allocation is
	// recorded in the next two slots in little-endian format, allowing
	// allocations up to 4GB - 8.
	UwOpAllocLarge = uint8(1)

	// Allocate a small-sized area on the stack. The size of the allocation is
	// the operation info field * 8 + 8, allowing allocations from 8 to 128
	// bytes.
	UwOpAllocSmall = uint8(2)

	// Establish the frame pointer register by setting the register to some
	// offset of the current RSP. The offset is equal to the Frame Register
	// offset (scaled) field in the UNWIND_INFO * 16, allowing offsets from 0
	// to 240. The use of an offset permits establishing a frame pointer that
	// points to the middle of the fixed stack allocation, helping code density
	// by allowing more accesses to use short instruction forms. The operation
	// info field is reserved and shouldn't be used.
	UwOpSetFpReg = uint8(3)

	// Save a nonvolatile integer register on the stack using a MOV instead of
	// a PUSH. This code is primarily used for shrink-wrapping, where a
	// nonvolatile register is saved to the stack in a position that was
	// previously allocated. The operation info is the number of the register.
	// The scaled-by-8 stack offset is recorded in the next unwind operation
	// code slot, as described in the note above.
	UwOpSaveNonVol = uint8(4)

	// Save a nonvolatile integer register on the stack with a long offset,
	// using a MOV instead of a PUSH. This code is primarily used for
	// shrink-wrapping, where a nonvolatile register is saved to the stack in a
	// position that was previously allocated. The operation info is the number
	// of the register. The unscaled stack offset is recorded in the next two
	// unwind operation code slots, as described in the note above.
	UwOpSaveNonVolFar = uint8(5)

	// For version 1 of the UNWIND_INFO structure, this code was called
	// UWOP_SAVE_XMM and occupied 2 records, it retained the lower 64 bits of
	// the XMM register, but was later removed and is now skipped. In practice,
	// this code has never been used.
	// For version 2 of the UNWIND_INFO structure, this code is called
	// UWOP_EPILOG, takes 2 entries, and describes the function epilogue.
	UwOpEpilog = uint8(6)

	// For version 1 of the UNWIND_INFO structure, this code was called
	// UWOP_SAVE_XMM_FAR and occupied 3 records, it saved the lower 64 bits of
	// the XMM register, but was later removed and is now skipped. In practice,
	// this code has never been used.
	// For version 2 of the UNWIND_INFO structure, this code is called
	// UWOP_SPARE_CODE, takes 3 entries, and makes no sense.
	UwOpSpareCode = uint8(7)

	// Save all 128 bits of a nonvolatile XMM register on the stack. The
	// operation info is the number of the register. The scaled-by-16 stack
	// offset is recorded in the next slot.
	UwOpSaveXmm128 = uint8(8)

	// Save all 128 bits of a nonvolatile XMM register on the stack with a long
	// offset. The operation info is the number of the register. The unscaled
	// stack offset is recorded in the next two slots.
	UwOpSaveXmm128Far = uint8(9)

	// Push a machine frame. This unwind code is used to record the effect of a
	// hardware interrupt or exception.
	UwOpPushMachFrame = uint8(10)

	// UWOP_SET_FPREG_LARGE is a CLR Unix-only extension to the Windows AMD64
	// unwind codes. It is not part of the standard Windows AMD64 unwind codes
	// specification. UWOP_SET_FPREG allows for a maximum of a 240 byte offset
	// between RSP and the frame pointer, when the frame pointer is
	// established. UWOP_SET_FPREG_LARGE has a 32-bit range scaled by 16. When
	// UWOP_SET_FPREG_LARGE is used, UNWIND_INFO.FrameRegister must be set to
	// the frame pointer register, and UNWIND_INFO.FrameOffset must be set to
	// 15 (its maximum value). UWOP_SET_FPREG_LARGE is followed by two
	// UNWIND_CODEs that are combined to form a 32-bit offset (the same as
	// UWOP_SAVE_NONVOL_FAR). This offset is then scaled by 16. The result must
	// be less than 2^32 (that is, the top 4 bits of the unscaled 32-bit number
	// must be zero). This result is used as the frame pointer register offset
	// from RSP at the time the frame pointer is established. Either
	// UWOP_SET_FPREG or UWOP_SET_FPREG_LARGE can be used, but not both.
	UwOpSetFpRegLarge = uint8(11)
)

_UNWIND_OP_CODES

View Source
const (
	// TinyPESize On Windows XP (x32) the smallest PE executable is 97 bytes.
	TinyPESize = 97

	// FileAlignmentHardcodedValue represents the value which PointerToRawData
	// should be at least equal or bigger to, or it will be rounded to zero.
	// According to http://corkami.blogspot.com/2010/01/parce-que-la-planche-aura-brule.html
	// if PointerToRawData is less that 0x200 it's rounded to zero.
	FileAlignmentHardcodedValue = 0x200
)
View Source
const (

	// ImageGuardCfInstrumented indicates that the module performs control flow
	// integrity checks using system-supplied support.
	ImageGuardCfInstrumented = 0x00000100

	// ImageGuardCfWInstrumented indicates that the module performs control
	// flow and write integrity checks.
	ImageGuardCfWInstrumented = 0x00000200

	// ImageGuardCfFunctionTablePresent indicates that the module contains
	// valid control flow target metadata.
	ImageGuardCfFunctionTablePresent = 0x00000400

	// ImageGuardSecurityCookieUnused indicates that the module does not make
	// use of the /GS security cookie.
	ImageGuardSecurityCookieUnused = 0x00000800

	// ImageGuardProtectDelayloadIAT indicates that the module supports read
	// only delay load IAT.
	ImageGuardProtectDelayloadIAT = 0x00001000

	// ImageGuardDelayloadIATInItsOwnSection indicates that the Delayload
	// import table in its own .didat section (with nothing else in it) that
	// can be freely reprotected.
	ImageGuardDelayloadIATInItsOwnSection = 0x00002000

	// ImageGuardCfExportSuppressionInfoPresent indicates that the module
	// contains suppressed export information. This also infers that the
	// address taken IAT table is also present in the load config.
	ImageGuardCfExportSuppressionInfoPresent = 0x00004000

	// ImageGuardCfEnableExportSuppression indicates that the module enables
	// suppression of exports.
	ImageGuardCfEnableExportSuppression = 0x00008000

	// ImageGuardCfLongjumpTablePresent indicates that the module contains
	// longjmp target information.
	ImageGuardCfLongjumpTablePresent = 0x00010000

	// ImageGuardCfFnctionTableSizeMask indicates that the mask for the
	// subfield that contains the stride of Control Flow Guard function table
	// entries (that is, the additional count of bytes per table entry).
	ImageGuardCfFnctionTableSizeMask = 0xF0000000

	// ImageGuardCfFnctionTableSizeShift indicates the shift to right-justify
	// Guard CF function table stride.
	ImageGuardCfFnctionTableSizeShift = 28

	// ImageGuardFlagFIDSupressed indicates that the call target is explicitly
	// suppressed (do not treat it as valid for purposes of CFG)
	ImageGuardFlagFIDSupressed = 0x1

	// ImageGuardFlagExportSupressed indicates that the call target is export
	// suppressed. See Export suppression for more details
	ImageGuardFlagExportSupressed = 0x2

	ImageDynamicRelocationGuardRfPrologue = 0x00000001
	ImageDynamicRelocationGuardREpilogue  = 0x00000002
	ImageEnclaveLongIdLength              = 32
	ImageEnclaveShortIdLength             = 16

	// ImageEnclaveImportMatchNone indicates that none of the identifiers of the image need to match the value in the import record.
	ImageEnclaveImportMatchNone = 0x00000000

	// ImageEnclaveImportMatchUniqueId indicates that the value of the enclave unique identifier of the image must match the value in the import record. Otherwise, loading of the image fails.
	ImageEnclaveImportMatchUniqueId = 0x00000001

	// ImageEnclaveImportMatchAuthorId indicates that the value of the enclave author identifier of the image must match the value in the import record. Otherwise, loading of the image fails. If this flag is set and the import record indicates an author identifier of all zeros, the imported image must be part of the Windows installation.
	ImageEnclaveImportMatchAuthorId = 0x00000002

	// ImageEnclaveImportMatchFamilyId indicates that the value of the enclave family identifier of the image must match the value in the import record. Otherwise, loading of the image fails.
	ImageEnclaveImportMatchFamilyId = 0x00000003

	// ImageEnclaveImportMatchImageId indicates that the value of the enclave image identifier must match the value in the import record. Otherwise, loading of the image fails.
	ImageEnclaveImportMatchImageId = 0x00000004
)
View Source
const (

	// The DOS MZ executable format is the executable file format used
	// for .EXE files in DOS.
	ImageDOSSignature   = 0x5A4D // MZ
	ImageDOSZMSignature = 0x4D5A // ZM

	// The New Executable (abbreviated NE or NewEXE) is a 16-bit .exe file
	// format, a successor to the DOS MZ executable format. It was used in
	// Windows 1.0–3.x, multitasking MS-DOS 4.0, OS/2 1.x, and the OS/2 subset
	// of Windows NT up to version 5.0 (Windows 2000). A NE is also called a
	// segmented executable.
	ImageOS2Signature = 0x454E

	// Linear Executable is an executable file format in the EXE family.
	// It was used by 32-bit OS/2, by some DOS extenders, and by Microsoft
	// Windows VxD files. It is an extension of MS-DOS EXE, and a successor
	// to NE (New Executable).
	ImageOS2LESignature = 0x454C

	// There are two main varieties of LE executables:
	// LX (32-bit), and LE (mixed 16/32-bit).
	ImageVXDSignature = 0x584C

	// Terse Executables have a 'VZ' signature.
	ImageTESignature = 0x5A56

	// The Portable Executable (PE) format is a file format for executables,
	// object code, DLLs and others used in 32-bit and 64-bit versions of
	// Windows operating systems.
	ImageNTSignature = 0x00004550 // PE00
)

Image executable types

View Source
const (
	ImageNtOptionalHeader32Magic = 0x10b
	ImageNtOptionalHeader64Magic = 0x20b
	ImageROMOptionalHeaderMagic  = 0x10
)

Optional Header magic

View Source
const (
	ImageFileMachineUnknown   = uint16(0x0)    // The contents of this field are assumed to be applicable to any machine type
	ImageFileMachineAM33      = uint16(0x1d3)  // Matsushita AM33
	ImageFileMachineAMD64     = uint16(0x8664) // x64
	ImageFileMachineARM       = uint16(0x1c0)  // ARM little endian
	ImageFileMachineARM64     = uint16(0xaa64) // ARM64 little endian
	ImageFileMachineARMNT     = uint16(0x1c4)  // ARM Thumb-2 little endian
	ImageFileMachineEBC       = uint16(0xebc)  // EFI byte code
	ImageFileMachineI386      = uint16(0x14c)  // Intel 386 or later processors and compatible processors
	ImageFileMachineIA64      = uint16(0x200)  // Intel Itanium processor family
	ImageFileMachineM32R      = uint16(0x9041) // Mitsubishi M32R little endian
	ImageFileMachineMIPS16    = uint16(0x266)  // MIPS16
	ImageFileMachineMIPSFPU   = uint16(0x366)  // MIPS with FPU
	ImageFileMachineMIPSFPU16 = uint16(0x466)  // MIPS16 with FPU
	ImageFileMachinePowerPC   = uint16(0x1f0)  // Power PC little endian
	ImageFileMachinePowerPCFP = uint16(0x1f1)  // Power PC with floating point support
	ImageFileMachineR4000     = uint16(0x166)  // MIPS little endian
	ImageFileMachineRISCV32   = uint16(0x5032) // RISC-V 32-bit address space
	ImageFileMachineRISCV64   = uint16(0x5064) // RISC-V 64-bit address space
	ImageFileMachineRISCV128  = uint16(0x5128) // RISC-V 128-bit address space
	ImageFileMachineSH3       = uint16(0x1a2)  // Hitachi SH3
	ImageFileMachineSH3DSP    = uint16(0x1a3)  // Hitachi SH3 DSP
	ImageFileMachineSH4       = uint16(0x1a6)  // Hitachi SH4
	ImageFileMachineSH5       = uint16(0x1a8)  // Hitachi SH5
	ImageFileMachineTHUMB     = uint16(0x1c2)  // Thumb
	ImageFileMachineWCEMIPSv2 = uint16(0x169)  // MIPS little-endian WCE v2
)

Image file machine types

View Source
const (
	// Image file only. This flag indicates that the file contains no base
	// relocations and must be loaded at its preferred base address. In the
	// case of base address conflict, the OS loader reports an error. This flag
	// should not be set for managed PE files.
	ImageFileRelocsStripped = 0x0001

	// Flag indicates that the file is an image file (EXE or DLL). This flag
	// should be set for managed PE files. If it is not set, this generally
	// indicates a linker error (i.e. no unresolved external references).
	ImageFileExecutableImage = 0x0002

	// COFF line numbers have been removed. This flag should be set for managed
	// PE files because they do not use the debug information embedded in the
	// PE file itself. Instead, the debug information is saved in accompanying
	// program database (PDB) files.
	ImageFileLineNumsStripped = 0x0004

	// COFF symbol table entries for local symbols have been removed. This flag
	// should be set for managed PE files, for the reason given in the preceding
	// entry.
	ImageFileLocalSymsStripped = 0x0008

	// Aggressively trim the working set.
	ImageFileAgressibeWsTrim = 0x0010

	// Application can handle addresses beyond the 2GB range. This flag should
	// not be set for pure-IL managed PE files of versions 1.0 and 1.1 but can
	// be set for v2.0+ files.
	ImageFileLargeAddressAware = 0x0020

	// Little endian.
	ImageFileBytesReservedLow = 0x0080

	// Machine is based on 32-bit architecture. This flag is usually set by
	// the current versions of code generators producing managed PE files.
	// Version 2.0 and newer, however, can produce 64-bit specific images,
	// which don’t have this flag set.
	ImageFile32BitMachine = 0x0100

	// Debug information has been removed from the image file.
	ImageFileDebugStripped = 0x0200

	// If the image file is on removable media, copy and run it from the swap
	// file.
	ImageFileRemovableRunFromSwap = 0x0400

	// If the image file is on a network, copy and run it from the swap file.
	ImageFileNetRunFromSwap = 0x0800

	// The image file is a system file (for example, a device driver). This flag
	ImageFileSystem = 0x1000

	// The image file is a DLL rather than an EXE. It cannot be directly run.
	ImageFileDLL = 0x2000

	// The image file should be run on a uniprocessor machine only.
	ImageFileUpSystemOnly = 0x4000

	// Big endian.
	ImageFileBytesReservedHigh = 0x8000
)

The Characteristics field contains flags that indicate attributes of the object or image file.

View Source
const (
	ImageSubsystemUnknown                = 0  // An unknown subsystem.
	ImageSubsystemNative                 = 1  // Device drivers and native Windows processes
	ImageSubsystemWindowsGUI             = 2  // The Windows graphical user interface (GUI) subsystem.
	ImageSubsystemWindowsCUI             = 3  // The Windows character subsystem
	ImageSubsystemOS2CUI                 = 5  // The OS/2 character subsystem.
	ImageSubsystemPosixCUI               = 7  // The Posix character subsystem.
	ImageSubsystemNativeWindows          = 8  // Native Win9x driver
	ImageSubsystemWindowsCEGUI           = 9  // Windows CE
	ImageSubsystemEFIApplication         = 10 // An Extensible Firmware Interface (EFI) application
	ImageSubsystemEFIBootServiceDriver   = 11 // An EFI driver with boot services
	ImageSubsystemEFIRuntimeDriver       = 12 // An EFI driver with run-time services
	ImageSubsystemEFIRom                 = 13 // An EFI ROM image .
	ImageSubsystemXBOX                   = 14 // XBOX.
	ImageSubsystemWindowsBootApplication = 16 // Windows boot application.
)

Subsystem values of an OptionalHeader.

View Source
const (
	ImageDllCharacteristicsReserved1            = 0x0001 // Reserved, must be zero.
	ImageDllCharacteristicsReserved2            = 0x0002 // Reserved, must be zero.
	ImageDllCharacteristicsReserved4            = 0x0004 // Reserved, must be zero.
	ImageDllCharacteristicsReserved8            = 0x0008 // Reserved, must be zero.
	ImageDllCharacteristicsHighEntropyVA        = 0x0020 // Image can handle a high entropy 64-bit virtual address space
	ImageDllCharacteristicsDynamicBase          = 0x0040 // DLL can be relocated at load time.
	ImageDllCharacteristicsForceIntegrity       = 0x0080 // Code Integrity checks are enforced.
	ImageDllCharacteristicsNXCompact            = 0x0100 // Image is NX compatible.
	ImageDllCharacteristicsNoIsolation          = 0x0200 // Isolation aware, but do not isolate the image.
	ImageDllCharacteristicsNoSEH                = 0x0400 // Does not use structured exception (SE) handling. No SE handler may be called in this image.
	ImageDllCharacteristicsNoBind               = 0x0800 // Do not bind the image.
	ImageDllCharacteristicsAppContainer         = 0x1000 // Image must execute in an AppContainer
	ImageDllCharacteristicsWdmDriver            = 0x2000 // A WDM driver.
	ImageDllCharacteristicsGuardCF              = 0x4000 // Image supports Control Flow Guard.
	ImageDllCharacteristicsTerminalServiceAware = 0x8000 // Terminal Server aware.

)

DllCharacteristics values of an OptionalHeader

View Source
const (
	ImageDirectoryEntryExport       = 0  // Export Table
	ImageDirectoryEntryImport       = 1  // Import Table
	ImageDirectoryEntryResource     = 2  // Resource Table
	ImageDirectoryEntryException    = 3  // Exception Table
	ImageDirectoryEntryCertificate  = 4  // Certificate Directory
	ImageDirectoryEntryBaseReloc    = 5  // Base Relocation Table
	ImageDirectoryEntryDebug        = 6  // Debug
	ImageDirectoryEntryArchitecture = 7  // Architecture Specific Data
	ImageDirectoryEntryGlobalPtr    = 8  // The RVA of the value to be stored in the global pointer register.
	ImageDirectoryEntryTLS          = 9  // The thread local storage (TLS) table
	ImageDirectoryEntryLoadConfig   = 10 // The load configuration table
	ImageDirectoryEntryBoundImport  = 11 // The bound import table
	ImageDirectoryEntryIAT          = 12 // Import Address Table
	ImageDirectoryEntryDelayImport  = 13 // Delay Import Descriptor
	ImageDirectoryEntryCLR          = 14 // CLR Runtime Header
	ImageDirectoryEntryReserved     = 15 // Must be zero
	ImageNumberOfDirectoryEntries   = 16 // Tables count.
)

DataDirectory entries of an OptionalHeader

View Source
const (
	// The base relocation is skipped. This type can be used to pad a block.
	ImageRelBasedAbsolute = 0

	// The base relocation adds the high 16 bits of the difference to the 16-bit
	// field at offset. The 16-bit field represents the high value of a 32-bit word.
	ImageRelBasedHigh = 1

	// The base relocation adds the low 16 bits of the difference to the 16-bit
	// field at offset. The 16-bit field represents the low half of a 32-bit word.
	ImageRelBasedLow = 2

	// The base relocation applies all 32 bits of the difference to the 32-bit
	// field at offset.
	ImageRelBasedHighLow = 3

	// The base relocation adds the high 16 bits of the difference to the 16-bit
	// field at offset. The 16-bit field represents the high value of a 32-bit
	// word. The low 16 bits of the 32-bit value are stored in the 16-bit word
	// that follows this base relocation. This means that this base relocation
	// occupies two slots.
	ImageRelBasedHighAdj = 4

	// The relocation interpretation is dependent on the machine type.
	// When the machine type is MIPS, the base relocation applies to a MIPS jump
	// instruction.
	ImageRelBasedMIPSJmpAddr = 5

	// This relocation is meaningful only when the machine type is ARM or Thumb.
	// The base relocation applies the 32-bit address of a symbol across a
	// consecutive MOVW/MOVT instruction pair.
	ImageRelBasedARMMov32 = 5

	// This relocation is only meaningful when the machine type is RISC-V. The
	// base relocation applies to the high 20 bits of a 32-bit absolute address.
	ImageRelBasedRISCVHigh20 = 5

	// Reserved, must be zero.
	ImageRelReserved = 6

	// This relocation is meaningful only when the machine type is Thumb.
	// The base relocation applies the 32-bit address of a symbol to a
	// consecutive MOVW/MOVT instruction pair.
	ImageRelBasedThumbMov32 = 7

	// This relocation is only meaningful when the machine type is RISC-V.
	// The base relocation applies to the low 12 bits of a 32-bit absolute
	// address formed in RISC-V I-type instruction format.
	ImageRelBasedRISCVLow12i = 7

	// This relocation is only meaningful when the machine type is RISC-V.
	// The base relocation applies to the low 12 bits of a 32-bit absolute
	// address formed in RISC-V S-type instruction format.
	ImageRelBasedRISCVLow12s = 8

	// The relocation is only meaningful when the machine type is MIPS.
	// The base relocation applies to a MIPS16 jump instruction.
	ImageRelBasedMIPSJmpAddr16 = 9

	// The base relocation applies the difference to the 64-bit field at offset.
	ImageRelBasedDir64 = 10
)

The Type field of the relocation record indicates what kind of relocation should be performed. Different relocation types are defined for each type of machine.

View Source
const (
	// DansSignature ('DanS' as dword) is where the rich header struct starts.
	DansSignature = 0x536E6144

	// RichSignature ('0x68636952' as dword) is where the rich header struct ends.
	RichSignature = "Rich"

	// AnoDansSigNotFound is reported when rich header signature was found, but
	AnoDansSigNotFound = "Rich Header found, but could not locate DanS " +
		"signature"

	// AnoPaddingDwordNotZero is repoted when rich header signature leading
	// padding DWORDs are not equal to 0.
	AnoPaddingDwordNotZero = "Rich header found: 3 leading padding DWORDs " +
		"not found after DanS signature"
)
View Source
const (
	// ImageScnReserved1 for future use.
	ImageScnReserved1 = 0x00000000

	// ImageScnReserved2 for future use.
	ImageScnReserved2 = 0x00000001

	// ImageScnReserved3 for future use.
	ImageScnReserved3 = 0x00000002

	// ImageScnReserved4 for future use.
	ImageScnReserved4 = 0x00000004

	// ImageScnTypeNoPad indicates the section should not be padded to the next
	// boundary. This flag is obsolete and is replaced by ImageScnAlign1Bytes.
	// This is valid only for object files.
	ImageScnTypeNoPad = 0x00000008

	// ImageScnReserved5 for future use.
	ImageScnReserved5 = 0x00000010

	// ImageScnCntCode indicates the section contains executable code.
	ImageScnCntCode = 0x00000020

	// ImageScnCntInitializedData indicates the section contains initialized data.
	ImageScnCntInitializedData = 0x00000040

	// ImageScnCntUninitializedData indicates the section contains uninitialized
	// data.
	ImageScnCntUninitializedData = 0x00000080

	// ImageScnLnkOther is reserved for future use.
	ImageScnLnkOther = 0x00000100

	// ImageScnLnkInfo indicates the section contains comments or other
	// information. The .drectve section has this type. This is valid for
	// object files only.
	ImageScnLnkInfo = 0x00000200

	// ImageScnReserved6 for future use.
	ImageScnReserved6 = 0x00000400

	// ImageScnLnkRemove indicates the section will not become part of the image
	// This is valid only for object files.
	ImageScnLnkRemove = 0x00000800

	// ImageScnLnkComdat indicates the section contains COMDAT data. For more
	// information, see COMDAT Sections (Object Only). This is valid only for
	// object files.
	ImageScnLnkComdat = 0x00001000

	// ImageScnGpRel indicates the section contains data referenced through the
	// global pointer (GP).
	ImageScnGpRel = 0x00008000

	// ImageScnMemPurgeable is reserved for future use.
	ImageScnMemPurgeable = 0x00020000

	// ImageScnMem16Bit is reserved for future use.
	ImageScnMem16Bit = 0x00020000

	// ImageScnMemLocked is reserved for future use.
	ImageScnMemLocked = 0x00040000

	// ImageScnMemPreload is reserved for future use.
	ImageScnMemPreload = 0x00080000

	// ImageScnAlign1Bytes indicates to align data on a 1-byte boundary.
	// Valid only for object files.
	ImageScnAlign1Bytes = 0x00100000

	// ImageScnAlign2Bytes indicates to align data on a 2-byte boundary.
	// Valid only for object files.
	ImageScnAlign2Bytes = 0x00200000

	// ImageScnAlign4Bytes indicates to align data on a 4-byte boundary.
	// Valid only for object files.
	ImageScnAlign4Bytes = 0x00300000

	// ImageScnAlign8Bytes indicates to align data on a 8-byte boundary.
	// Valid only for object files.
	ImageScnAlign8Bytes = 0x00400000

	// ImageScnAlign16Bytes indicates to align data on a 16-byte boundary.
	// Valid only for object files.
	ImageScnAlign16Bytes = 0x00500000

	// ImageScnAlign32Bytes indicates to align data on a 32-byte boundary.
	// Valid only for object files.
	ImageScnAlign32Bytes = 0x00600000

	// ImageScnAlign64Bytes indicates to align data on a 64-byte boundary.
	// Valid only for object files.
	ImageScnAlign64Bytes = 0x00700000

	// ImageScnAlign128Bytes indicates to align data on a 128-byte boundary.
	// Valid only for object files.
	ImageScnAlign128Bytes = 0x00800000

	// ImageScnAlign256Bytes indicates to align data on a 256-byte boundary.
	// Valid only for object files.
	ImageScnAlign256Bytes = 0x00900000

	// ImageScnAlign512Bytes indicates to align data on a 512-byte boundary.
	// Valid only for object files.
	ImageScnAlign512Bytes = 0x00A00000

	// ImageScnAlign1024Bytes indicates to align data on a 1024-byte boundary.
	// Valid only for object files.
	ImageScnAlign1024Bytes = 0x00B00000

	// ImageScnAlign2048Bytes indicates to align data on a 2048-byte boundary.
	// Valid only for object files.
	ImageScnAlign2048Bytes = 0x00C00000

	// ImageScnAlign4096Bytes indicates to align data on a 4096-byte boundary.
	// Valid only for object files.
	ImageScnAlign4096Bytes = 0x00D00000

	// ImageScnAlign8192Bytes indicates to align data on a 8192-byte boundary.
	// Valid only for object files.
	ImageScnAlign8192Bytes = 0x00E00000

	// ImageScnLnkMRelocOvfl indicates the section contains extended relocations.
	ImageScnLnkMRelocOvfl = 0x01000000

	// ImageScnMemDiscardable indicates the section can be discarded as needed.
	ImageScnMemDiscardable = 0x02000000

	//ImageScnMemNotCached indicates the  section cannot be cached.
	ImageScnMemNotCached = 0x04000000

	// ImageScnMemNotPaged indicates the section is not pageable.
	ImageScnMemNotPaged = 0x08000000

	// ImageScnMemShared indicates the section can be shared in memory.
	ImageScnMemShared = 0x10000000

	// ImageScnMemExecute indicates the section can be executed as code.
	ImageScnMemExecute = 0x20000000

	// ImageScnMemRead indicates the section can be read.
	ImageScnMemRead = 0x40000000

	// ImageScnMemWrite indicates the section can be written to.
	ImageScnMemWrite = 0x80000000
)
View Source
const (
	// WinCertRevision1_0 represents the WIN_CERT_REVISION_1_0 Version 1,
	// legacy version of the Win_Certificate structure.
	// It is supported only for purposes of verifying legacy Authenticode
	// signatures
	WinCertRevision1_0 = 0x0100

	// WinCertRevision2_0 represents the WIN_CERT_REVISION_2_0. Version 2
	// is the current version of the Win_Certificate structure.
	WinCertRevision2_0 = 0x0200
)

The options for the WIN_CERTIFICATE Revision member include (but are not limited to) the following.

View Source
const (
	// Certificate contains an X.509 Certificate (Not Supported)
	WinCertTypeX509 = 0x0001

	// Certificate contains a PKCS#7 SignedData structure.
	WinCertTypePKCSSignedData = 0x0002

	// Reserved.
	WinCertTypeReserved1 = 0x0003

	// Terminal Server Protocol Stack Certificate signing (Not Supported).
	WinCertTypeTsStackSigned = 0x0004
)

The options for the WIN_CERTIFICATE CertificateType member include (but are not limited to) the items in the following table. Note that some values are not currently supported.

View Source
const (

	// ImageSymTypeNull indicates no type information or unknown base type.
	// Microsoft tools use this setting.
	ImageSymTypeNull = 0

	// ImageSymTypeVoid indicates no type no valid type; used with void pointers and functions.
	ImageSymTypeVoid = 1

	// ImageSymTypeChar indicates a character (signed byte).
	ImageSymTypeChar = 2

	// ImageSymTypeShort indicates a 2-byte signed integer.
	ImageSymTypeShort = 3

	// ImageSymTypeInt indicates a natural integer type (normally 4 bytes in
	// Windows).
	ImageSymTypeInt = 4

	// ImageSymTypeLong indicates a 4-byte signed integer.
	ImageSymTypeLong = 5

	// ImageSymTypeFloat indicates a 4-byte floating-point number.
	ImageSymTypeFloat = 6

	// ImageSymTypeDouble indicates an 8-byte floating-point number.
	ImageSymTypeDouble = 7

	// ImageSymTypeStruct indicates a structure.
	ImageSymTypeStruct = 8

	// ImageSymTypeUnion indicates a union.
	ImageSymTypeUnion = 9

	// ImageSymTypeEnum indicates an enumerated type.
	ImageSymTypeEnum = 10

	// ImageSymTypeMoe A member of enumeration (a specific value).
	ImageSymTypeMoe = 11

	// ImageSymTypeByte indicates a byte; unsigned 1-byte integer.
	ImageSymTypeByte = 12

	// ImageSymTypeWord indicates a word; unsigned 2-byte integer.
	ImageSymTypeWord = 13

	// ImageSymTypeUint indicates an unsigned integer of natural size
	// (normally, 4 bytes).
	ImageSymTypeUint = 14

	// ImageSymTypeDword indicates an unsigned 4-byte integer.
	ImageSymTypeDword = 15

	// ImageSymClassEndOfFunction indicates a special symbol that represents
	// the end of function, for debugging purposes.
	ImageSymClassEndOfFunction = 0xff

	// ImageSymClassNull indicates no assigned storage class.
	ImageSymClassNull = 0

	// ImageSymClassAutomatic indicates automatic (stack) variable. The Value
	// field specifies the stack frame offset.
	ImageSymClassAutomatic = 1

	// ImageSymClassExternal indicates a value that Microsoft tools use for
	// external symbols. The Value field indicates the size if the section
	// number is IMAGE_SYM_UNDEFINED (0). If the section number is not zero,
	// then the Value field specifies the offset within the section.
	ImageSymClassExternal = 2

	// ImageSymClassStatic indicates the offset of the symbol within the
	// section. If the Value field is zero, then the symbol represents a
	// section name.
	ImageSymClassStatic = 3

	// ImageSymClassRegister indicates a register variable. The Value field
	// specifies the register number.
	ImageSymClassRegister = 4

	// ImageSymClassExternalDef indicates a symbol that is defined externally.
	ImageSymClassExternalDef = 5

	// ImageSymClassLabel indicates a code label that is defined within the
	// module. The Value field specifies the offset of the symbol within the
	// section.
	ImageSymClassLabel = 6

	// ImageSymClassUndefinedLabel indicates a reference to a code label that
	// is not defined.
	ImageSymClassUndefinedLabel = 7

	// ImageSymClassMemberOfStruct indicates the structure member. The Value
	// field specifies the n th member.
	ImageSymClassMemberOfStruct = 8

	// ImageSymClassArgument indicates a formal argument (parameter) of a
	// function. The Value field specifies the n th argument.
	ImageSymClassArgument = 9

	// ImageSymClassStructTag indicates the structure tag-name entry.
	ImageSymClassStructTag = 10

	// ImageSymClassMemberOfUnion indicates a union member. The Value field
	// specifies the n th member.
	ImageSymClassMemberOfUnion = 11

	// ImageSymClassUnionTag indicates the structure tag-name entry.
	ImageSymClassUnionTag = 12

	// ImageSymClassTypeDefinition indicates a typedef entry.
	ImageSymClassTypeDefinition = 13

	// ImageSymClassUndefinedStatic indicates a static data declaration.
	ImageSymClassUndefinedStatic = 14

	// ImageSymClassEnumTag indicates an enumerated type tagname entry.
	ImageSymClassEnumTag = 15

	// ImageSymClassMemberOfEnum indicates a member of an enumeration. The
	// Value field specifies the n th member.
	ImageSymClassMemberOfEnum = 16

	// ImageSymClassRegisterParam indicates a register parameter.
	ImageSymClassRegisterParam = 17

	// ImageSymClassBitField indicates a bit-field reference. The Value field
	// specifies the n th bit in the bit field.
	ImageSymClassBitField = 18

	// ImageSymClassBlock indicates a .bb (beginning of block) or .eb (end of
	// block) record. The Value field is the relocatable address of the code
	// location.
	ImageSymClassBlock = 100

	// ImageSymClassFunction indicates a value that Microsoft tools use for
	// symbol records that define the extent of a function: begin function (.bf
	// ), end function ( .ef ), and lines in function ( .lf ). For .lf
	// records, the Value field gives the number of source lines in the
	// function. For .ef records, the Value field gives the size of the
	// function code.
	ImageSymClassFunction = 101

	// ImageSymClassEndOfStruct indicates an end-of-structure entry.
	ImageSymClassEndOfStruct = 102

	// ImageSymClassFile indicates a value that Microsoft tools, as well as
	// traditional COFF format, use for the source-file symbol record. The
	// symbol is followed by auxiliary records that name the file.
	ImageSymClassFile = 103

	// ImageSymClassSsection indicates a definition of a section (Microsoft
	// tools use STATIC storage class instead).
	ImageSymClassSsection = 104

	// ImageSymClassWeakExternal indicates a weak external. For more
	// information, see Auxiliary Format 3: Weak Externals.
	ImageSymClassWeakExternal = 24

	// ImageSymClassClrToken indicates a CLR token symbol. The name is an ASCII
	// string that consists of the hexadecimal value of the token. For more
	// information, see CLR Token Definition (Object Only).
	ImageSymClassClrToken = 25

	// ImageSymUndefined indicates that the symbol record is not yet assigned a
	// section. A value of zero indicates that a reference to an external
	// symbol is defined elsewhere. A value of non-zero is a common symbol with
	// a size that is specified by the value.
	ImageSymUndefined = 0

	// ImageSymAbsolute indicates that the symbol has an absolute
	// (non-relocatable) value and is not an address.
	ImageSymAbsolute = -1

	// ImageSymDebug indicates that the symbol provides general type or
	// debugging information but does not correspond to a section. Microsoft
	// tools use this setting along with .file records (storage class FILE).
	ImageSymDebug = -2
)
View Source
const (
	// ImageDllCharacteristicsExCETCompat indicates that the image is CET
	// compatible.
	ImageDllCharacteristicsExCETCompat = 0x0001
)
View Source
const (
	// MaxStringLength represents the maximum length of a string to be retrieved
	// from the file. It's there to prevent loading massive amounts of data from
	// memory mapped files. Strings longer than 0x100B should be rather rare.
	MaxStringLength = uint32(0x100)
)

Variables

View Source
var (

	// AnoPEHeaderOverlapDOSHeader is reported when the PE headers overlaps with
	// the DOS header.
	AnoPEHeaderOverlapDOSHeader = "PE Header overlaps with DOS header"

	// AnoPETimeStampNull is reported when the file header timestamp is 0.
	AnoPETimeStampNull = "File Header timestamp set to 0"

	// AnoPETimeStampFuture is reported when the file header timestamp is more
	// than one day ahead of the current date timestamp.
	AnoPETimeStampFuture = "File Header timestamp set to 0"

	// NumberOfSections is reported when number of sections is larger or equal than 10.
	AnoNumberOfSections10Plus = "Number of sections is 10+"

	// AnoNumberOfSectionsNull is reported when sections count's is 0.
	AnoNumberOfSectionsNull = "Number of sections is 0"

	// AnoSizeOfOptionalHeaderNull is reported when size of optional header is 0.
	AnoSizeOfOptionalHeaderNull = "Size of optional header is 0"

	// AnoUncommonSizeOfOptionalHeader32 is reported when size of optional
	// header for PE32 is larger than 0xE0.
	AnoUncommonSizeOfOptionalHeader32 = `Size of optional header is larger than
	 0xE0 (PE32)`

	// AnoUncommonSizeOfOptionalHeader64 is reported when size of optional
	// header for PE32+ is larger than 0xF0.
	AnoUncommonSizeOfOptionalHeader64 = `Size of optional header is larger than
	 0xF0 (PE32+)`

	// AnoAddressOfEntryPointNull is reported when address of entry point is 0.
	AnoAddressOfEntryPointNull = "Address of entry point is 0."

	// AnoAddressOfEPLessSizeOfHeaders is reported when address of entry point
	// is smaller than size of headers, the file cannot run under Windows.
	AnoAddressOfEPLessSizeOfHeaders = `Address of entry point is smaller than 
		size of headers, the file cannot run under Windows 8`

	// AnoImageBaseNull is reported when the image base is null
	AnoImageBaseNull = "Image base is 0"

	// AnoDanSMagicOffset is reported when the `DanS` magic offset is different
	// than 0x80.
	AnoDanSMagicOffset = "`DanS` magic offset is different than 0x80"

	// ErrInvalidFileAlignment is reported when file alignment is larger than
	//  0x200 and not a power of 2.
	ErrInvalidFileAlignment = "FileAlignment larger than 0x200 and not a power of 2"

	// ErrInvalidSectionAlignment is reported when file alignment is lesser
	// than 0x200 and different from section alignment.
	ErrInvalidSectionAlignment = `FileAlignment lesser than 0x200 and different 
		from section alignment`

	// AnoMajorSubsystemVersion is reported when MajorSubsystemVersion has a
	// value different than the standard 3 --> 6.
	AnoMajorSubsystemVersion = `MajorSubsystemVersion is outside 3<-->6 boundary`

	// AnonWin32VersionValue is reported when Win32VersionValue is different than 0
	AnonWin32VersionValue = `Win32VersionValue is a reserved field, should be
		normally set to 0x0.`

	// AnoInvalidPEChecksum is reported when the optional header checksum field
	// is different from what it should normally be.
	AnoInvalidPEChecksum = `Optional header checksum is invalid.`

	// AnoNumberOfRvaAndSizes is reported when NumberOfRvaAndSizes is different
	// than 16.
	AnoNumberOfRvaAndSizes = `Optional header NumberOfRvaAndSizes != 16`
)

Anomalies found in a PE

View Source
var (
	ErrExportMaxOrdEntries       = "Export directory contains more than max ordinal entries"
	ErrExportManyRepeatedEntries = "Export directory contains many repeated entries"
	AnoNullNumberOfFunctions     = "Export directory contains zero number of functions"
	AnoNullAddressOfFunctions    = "Export directory contains zero address of functions"
)
View Source
var (

	// ErrInvalidPESize is returned when the file size is less that the smallest
	// PE file size possible.ErrImageOS2SignatureFound
	ErrInvalidPESize = errors.New("Not a PE file, smaller than tiny PE")

	// ErrDOSMagicNotFound is returned when file is potentially a ZM executable.
	ErrDOSMagicNotFound = errors.New("DOS Header magic not found")

	// ErrInvalidElfanewValue is returned when e_lfanew is larger than file size.
	ErrInvalidElfanewValue = errors.New(
		"Invalid e_lfanew value. Probably not a PE file")

	// ErrInvalidNtHeaderOffset is returned when the NT Header offset is beyond
	// the image file.
	ErrInvalidNtHeaderOffset = errors.New(
		"Invalid NT Header Offset. NT Header Signature not found")

	// ErrImageOS2SignatureFound is returned when signature is for a NE file.
	ErrImageOS2SignatureFound = errors.New(
		"Not a valid PE signature. Probably a NE file")

	// ErrImageOS2LESignatureFound is returned when signature is for a LE file.
	ErrImageOS2LESignatureFound = errors.New(
		"Not a valid PE signature. Probably an LE file")

	// ErrImageVXDSignatureFound is returned when signature is for a LX file.
	ErrImageVXDSignatureFound = errors.New(
		"Not a valid PE signature. Probably an LX file")

	// ErrImageTESignatureFound is returned when signature is for a TE file.
	ErrImageTESignatureFound = errors.New(
		"Not a valid PE signature. Probably a TE file")

	// ErrImageNtSignatureNotFound is returned when PE magic signature is not found.
	ErrImageNtSignatureNotFound = errors.New(
		"Not a valid PE signature. Magic not found")

	// ErrImageNtOptionalHeaderMagicNotFound is returned when optional header
	// magic is different from PE32/PE32+.
	ErrImageNtOptionalHeaderMagicNotFound = errors.New(
		"Not a valid PE signature. Optional Header magic not found")

	// ErrImageBaseNotAligned is reported when the image base is not aligned to 64K.
	ErrImageBaseNotAligned = errors.New(
		"Corrupt PE file. Image base not aligned to 64 K")

	// AnoImageBaseOverflow is reported when the image base + SizeOfImage is
	// larger than 80000000h/FFFF080000000000h in PE32/P32+.
	AnoImageBaseOverflow = "Image base beyong allowed address"

	// ErrInvalidSectionFileAlignment is reported when section alignment is less than a
	// PAGE_SIZE and section alignement != file alignment.
	ErrInvalidSectionFileAlignment = errors.New("Corrupt PE file. Section " +
		"alignment is less than a PAGE_SIZE and section alignement != file alignment")

	// AnoInvalidSizeOfImage is reported when SizeOfImage is not multiple of
	// SectionAlignment.
	AnoInvalidSizeOfImage = "Invalid SizeOfImage value, should be multiple " +
		"of SectionAlignment"

	// ErrOutsideBoundary is reported when attempting to read an address beyond
	// file image limits.
	ErrOutsideBoundary = errors.New("Reading data outside boundary")
)

Errors

View Source
var (
	// AnoInvalidThunkAddressOfData is reported when thunk address is too spread out.
	AnoInvalidThunkAddressOfData = "Thunk Address Of Data too spread out"

	// AnoManyRepeatedEntries is reported when import directory contains many
	// entries have the same RVA.
	AnoManyRepeatedEntries = "Import directory contains many repeated entries"

	// AnoAddressOfDataBeyondLimits is reported when Thunk AddressOfData goes
	// beyond limites.
	AnoAddressOfDataBeyondLimits = "Thunk AddressOfData beyond limits"

	// AnoImportNoNameNoOrdinal is reported when an import entry does not have
	// a name neither an oridinal, most probably malformed data.
	AnoImportNoNameNoOrdinal = "Must have either an ordinal or a name in an import"

	// ErrDamagedImportTable is reported when the IAT and ILT table length is 0.
	ErrDamagedImportTable = errors.New(
		"Damaged Import Table information. ILT and/or IAT appear to be broken")
)
View Source
var (
	// ErrInvalidBaseRelocVA is reposed when base reloc lies outside of the image.
	ErrInvalidBaseRelocVA = errors.New("Invalid relocation information." +
		" Base Relocation VirtualAddress is outside of PE Image")

	// ErrInvalidBasicRelocSizeOfBloc is reposed when base reloc is too large.
	ErrInvalidBasicRelocSizeOfBloc = errors.New("Invalid relocation " +
		"information. Base Relocation SizeOfBlock too large")
)
View Source
var (
	RTCursor       = 1
	RTBitmap       = 2
	RTIcon         = 3
	RTMenu         = 4
	RTDialog       = 5
	RTString       = 6
	RTFontdir      = 7
	RTFont         = 8
	RTAccelerator  = 9
	RTRCdata       = 10
	RTMessagetable = 11
	RTGroupCursor  = 12
	RTGroupIcon    = 14
	RTVersion      = 16
	RTDlgInclude   = 17
	RTPlugPlay     = 19
	RTVxd          = 20
	RTAniCursor    = 21
	RTAniIcon      = 22
	RTHtml         = 23
	RTManifest     = 24
)

Predefined Resource Types.

View Source
var OleAut32OrdNames = map[uint64]string{}/* 398 elements not displayed */

OleAut32OrdNames maps ordinals to names.

View Source
var OpInfoRegisters = map[uint8]string{
	// contains filtered or unexported fields
}

OpInfoRegisters maps registers to string.

View Source
var OrdNames = map[string]map[uint64]string{
	"ws2_32.dll":   WS232OrdNames,
	"wsock32.dll":  WS232OrdNames,
	"oleaut32.dll": OleAut32OrdNames,
}

OrdNames maps the dll names to ordinal names.

View Source
var UnOpToString = map[uint8]string{
	UwOpPushNonVol:    "UWOP_PUSH_NONVOL",
	UwOpAllocLarge:    "UWOP_ALLOC_LARE",
	UwOpAllocSmall:    "UWOP_ALLOC_SMALL",
	UwOpSetFpReg:      "UWOP_SET_FPREG",
	UwOpSaveNonVol:    "UWOP_SAVE_NONVOL",
	UwOpSaveNonVolFar: "UWOP_SAVE_NONVOL_FAR",
	UwOpEpilog:        "UWOP_EPILOG",
	UwOpSpareCode:     "UWOP_SPARE_CODE",
	UwOpSaveXmm128:    "UWOP_SAVE_XMM128",
	UwOpSaveXmm128Far: "UWOP_SAVE_XMM128_FAR",
	UwOpPushMachFrame: "UWOP_PUSH_MACHFRAME",
	UwOpSetFpRegLarge: "UWOP_SET_FPREG_LARGE",
}

UnOpToString maps unwind opcodes to strings.

View Source
var WS232OrdNames = map[uint64]string{}/* 117 elements not displayed */

WS232OrdNames maps ordinals to name.

Functions

func FPOFrameTypePretty

func FPOFrameTypePretty(ft uint8) string

FPOFrameTypePretty returns a string interpretation of the FPO frame type.

func Fuzz

func Fuzz(data []byte) int

func IsBitSet

func IsBitSet(n uint64, pos int) bool

IsBitSet returns true when a bit on a particular position is set.

func IsPrintable

func IsPrintable(s string) bool

IsPrintable checks weather a string is printable.

func IsValidDosFilename

func IsValidDosFilename(filename string) bool

IsValidDosFilename returns true if the DLL name is likely to be valid. Valid FAT32 8.3 short filename characters according to: http://en.wikipedia.org/wiki/8.3_filename The filename length is not checked because the DLLs filename can be longer that the 8.3

func IsValidFunctionName

func IsValidFunctionName(functionName string) bool

IsValidFunctionName checks if an imported name uses the valid accepted characters expected in mangled function names. If the symbol's characters don't fall within this charset we will assume the name is invalid.

func Max

func Max(x, y uint32) uint32

Max returns the larger of x or y.

func MetadataTableIndextToString

func MetadataTableIndextToString(k int) string

MetadataTableIndextToString returns the string representation of the metadata table index.

func Min

func Min(values []uint32) uint32

Min returns the min number in a slice.

func OrdLookup

func OrdLookup(libname string, ord uint64, makeName bool) string

OrdLookup returns API name given an ordinal.

func PrettyExtendedDLLCharacteristics

func PrettyExtendedDLLCharacteristics(characteristics uint32) []string

PrettyExtendedDLLCharacteristics maps dll char to string.

func PrettyUnwindInfoHandlerFlags

func PrettyUnwindInfoHandlerFlags(flags uint8) []string

PrettyUnwindInfoHandlerFlags returns the string representation of the `flags` field of the unwind info structure.

func PrintLoadConfigStruct

func PrintLoadConfigStruct()

PrintLoadConfigStruct will print size of each load config struct.

func ProdIDtoStr

func ProdIDtoStr(prodID uint16) string

ProdIDtoStr mapps product ids to MS internal names. list from: https://github.com/kirschju/richheader

func ProdIDtoVSversion

func ProdIDtoVSversion(prodID uint16) string

ProdIDtoVSversion retrieves the Visual Studio version from product id. list from: https://github.com/kirschju/richheader

func SectionAttributeDescription

func SectionAttributeDescription(section string) string

SectionAttributeDescription maps a section attribute to a friendly name.

func StringifyGuardFlags

func StringifyGuardFlags(flags uint32) []string

StringifyGuardFlags returns list of strings which describes the GuardFlags.

Types

type BoundForwardedRefData

type BoundForwardedRefData struct {
	Struct ImageBoundForwardedRef
	Name   string
}

BoundForwardedRefData reprents the struct in addition to the dll name.

type BoundImportDescriptorData

type BoundImportDescriptorData struct {
	Struct        ImageBoundImportDescriptor
	Name          string
	ForwardedRefs []BoundForwardedRefData
}

BoundImportDescriptorData represents the descripts in addition to forwarded refs.

type CFGFunction

type CFGFunction struct {
	Target      uint32
	Flags       *uint8
	Description string
}

type CFGIATEntry

type CFGIATEntry struct {
	RVA         uint32
	IATValue    uint32
	INTValue    uint32
	Description string
}

type CLRData

type CLRData struct {
	CLRHeader                  *ImageCOR20Header          `json:"clr_header,omitempty"`
	MetadataHeader             *MetadataHeader            `json:"metadata_header,omitempty"`
	MetadataStreamHeaders      []*MetadataStreamHeader    `json:"metadata_stream_headers,omitempty"`
	MetadataStreams            map[string][]byte          `json:"-"`
	MetadataTablesStreamHeader *MetadataTableStreamHeader `json:"metadata_tables_stream_header,omitempty"`
	MetadataTables             map[int]*MetadataTable     `json:"metadata_tables,omitempty"`
	StringStreamIndexSize      int                        `json:"-"`
	GUIDStreamIndexSize        int                        `json:"-"`
	BlobStreamIndexSize        int                        `json:"-"`
}

CLRData embeds the Common Language Runtime Header structure as well as the Metadata header structure.

type COFF

type COFF struct {
	SymbolTable       []COFFSymbol
	StringTable       []string
	StringTableOffset uint32
	StringTableM      map[uint32]string // Map the symbol offset => symbol name.
}

COFF holds properties related to the COFF format.

type COFFSymbol

type COFFSymbol struct {
	// The name of the symbol, represented by a union of three structures. An
	// array of 8 bytes is used if the name is not more than 8 bytes long.
	// union {
	//    BYTE     ShortName[8];
	//    struct {
	//        DWORD   Short;     // if 0, use LongName
	//        DWORD   Long;      // offset into string table
	//    } Name;
	//    DWORD   LongName[2];    // PBYTE  [2]
	// } N;
	Name [8]byte

	// The value that is associated with the symbol. The interpretation of this
	// field depends on SectionNumber and StorageClass. A typical meaning is
	// the relocatable address.
	Value uint32

	// The signed integer that identifies the section, using a one-based index
	// into the section table. Some values have special meaning, as defined in section 5.4.2, "Section Number Values."
	SectionNumber int16

	// A number that represents type. Microsoft tools set this field to 0x20 (function) or 0x0 (not a function). For more information, see Type Representation.
	Type uint16

	// An enumerated value that represents storage class. For more information, see Storage Class.
	StorageClass uint8

	// The number of auxiliary symbol table entries that follow this record.
	NumberOfAuxSymbols uint8
}

COFFSymbol represents an entry in the COFF symbol table, which it is an array of records, each 18 bytes long. Each record is either a standard or auxiliary symbol-table record. A standard record defines a symbol or name and has the following format.

func (*COFFSymbol) SectionNumberName

func (symbol *COFFSymbol) SectionNumberName(pe *File) string

SectionNumberName returns the name of the section corresponding to a section symbol number if any.

func (*COFFSymbol) String

func (symbol *COFFSymbol) String(pe *File) (string, error)

String returns represenation of the symbol name.

type CVHeader

type CVHeader struct {
	// CodeView signature, equal to `NB10`
	Signature uint32

	// CodeView offset. Set to 0, because debug information is stored in a separate file.
	Offset uint32
}

CVHeader represents the the CodeView header struct to the PDB 2.0 file.

type CertInfo

type CertInfo struct {
	// The certificate authority (CA) that charges customers to issue
	// certificates for them.
	Issuer string

	// The subject of the certificate is the entity its public key is associated
	// with (i.e. the "owner" of the certificate).
	Subject string

	// The certificate won't be valid after this timestamp.
	NotBefore time.Time

	// The certificate won't be valid after this timestamp.
	NotAfter time.Time
}

CertInfo wraps the important fields of the pkcs7 structure. This is what we what keep in JSON marshalling.

type Certificate

type Certificate struct {
	Header   WinCertificate
	Content  *pkcs7.PKCS7 `json:"-"`
	Info     CertInfo
	Verified bool
}

Certificate directory.

type CodeRange

type CodeRange struct {
	Begin   uint32
	Length  uint32
	Machine uint8
}

type CompID

type CompID struct {
	// The minor version information for the compiler used when building the product.
	MinorCV uint16

	// Provides information about the identity or type of the objects used to
	// build the PE32.
	ProdID uint16

	// Indicates how often the object identified by the former two fields is
	// referenced by this PE32 file.
	Count uint32

	// The raw @comp.id structure (unmasked).
	Unmasked uint32
}

CompID represents the `@comp.id` structure.

type CompilerIAT

type CompilerIAT struct {
	RVA         uint32
	Value       uint32
	Description string
}

type CvInfoPDB20

type CvInfoPDB20 struct {
	// Points to the CodeView header structure.
	CvHeader CVHeader

	// The time when debug information was created (in seconds since 01.01.1970)
	Signature uint32

	// Ever-incrementing value, which is initially set to 1 and incremented every
	// time when a part of the PDB file is updated without rewriting the whole file.
	Age uint32

	// Null-terminated name of the PDB file. It can also contain full or partial
	// path to the file.
	PDBFileName string
}

CvInfoPDB20 represents the the CodeView data block of a PDB 2.0 file.

type CvInfoPDB70

type CvInfoPDB70 struct {
	// CodeView signature, equal to `RSDS`
	CvSignature uint32

	// A unique identifier, which changes with every rebuild of the executable and PDB file.
	Signature GUID

	// Ever-incrementing value, which is initially set to 1 and incremented every
	// time when a part of the PDB file is updated without rewriting the whole file.
	Age uint32

	// Null-terminated name of the PDB file. It can also contain full or partial
	// path to the file.
	PDBFileName string
}

CvInfoPDB70 represents the the CodeView data block of a PDB 7.0 file.

type DVRT

type DVRT struct {
	ImgDynRelocTable ImageDynamicRelocationTable
	Entries          []RelocEntry
}

DVRT Dynamic Value Relocation Table

type DataDirectory

type DataDirectory struct {
	VirtualAddress uint32 // The RVA of the data structure.
	Size           uint32 // The size in bytes of the data structure refered to.
}

DataDirectory represents an array of 16 IMAGE_DATA_DIRECTORY structures, 8 bytes apiece, each relating to an important data structure in the PE file. The data directory table starts at offset 96 in a 32-bit PE header and at offset 112 in a 64-bit PE header. Each entry in the data directory table contains the RVA and size of a table or a string that this particular directory entry describes;this information is used by the operating system.

type DebugEntry

type DebugEntry struct {
	// Points to the image debug entry structure.
	Struct ImageDebugDirectory

	// Holds specific information about the debug type entry.
	Info interface{}
}

DebugEntry wraps ImageDebugDirectory to include debug directory type.

type DelayImport

type DelayImport struct {
	Offset     uint32
	Name       string
	Functions  []*ImportFunction
	Descriptor ImageDelayImportDescriptor
}

DelayImport represents an entry in the delay import table.

type Enclave

type Enclave struct {

	// Points to either ImageEnclaveConfig32{} or ImageEnclaveConfig64{}
	Config interface{}

	Imports []ImageEnclaveImport
}

type Exception

type Exception struct {
	RuntimeFunction ImageRuntimeFunctionEntry
	UnwinInfo       UnwindInfo
}

Exception represent an entry in the function table.

type Export

type Export struct {
	Functions []ExportFunction
	Struct    ImageExportDirectory
	Name      string
}

Export represent the export table.

type ExportFunction

type ExportFunction struct {
	Ordinal      uint32
	FunctionRVA  uint32
	NameOrdinal  uint32
	NameRVA      uint32
	Name         string
	Forwarder    string
	ForwarderRVA uint32
}

ExportFunction represents an imported function in the export table.

type FPOData

type FPOData struct {
	// The offset of the first byte of the function code.
	OffStart uint32

	// The number of bytes in the function.
	ProcSize uint32

	// The number of local variables.
	NumLocals uint32

	// The size of the parameters, in DWORDs.
	ParamsSize uint16

	// The number of bytes in the function prolog code.
	PrologLength uint8

	// The number of registers saved.
	SavedRegsCount uint8

	// A variable that indicates whether the function uses structured exception handling.
	HasSEH uint8

	// A variable that indicates whether the EBP register has been allocated.
	UseBP uint8

	// Reserved for future use.
	Reserved uint8

	// A variable that indicates the frame type.
	FrameType uint8
}

FPOData Represents the stack frame layout for a function on an x86 computer when frame pointer omission (FPO) optimization is used. The structure is used to locate the base of the call frame.

type File

type File struct {
	DosHeader    ImageDosHeader              `json:",omitempty"`
	RichHeader   *RichHeader                 `json:",omitempty"`
	NtHeader     ImageNtHeader               `json:",omitempty"`
	COFF         *COFF                       `json:",omitempty"`
	Sections     []Section                   `json:",omitempty"`
	Imports      []Import                    `json:",omitempty"`
	Export       *Export                     `json:",omitempty"`
	Debugs       []DebugEntry                `json:",omitempty"`
	Relocations  []Relocation                `json:",omitempty"`
	Resources    *ResourceDirectory          `json:",omitempty"`
	TLS          *TLSDirectory               `json:",omitempty"`
	LoadConfig   *LoadConfig                 `json:",omitempty"`
	Exceptions   []Exception                 `json:",omitempty"`
	Certificates *Certificate                `json:",omitempty"`
	DelayImports []DelayImport               `json:",omitempty"`
	BoundImports []BoundImportDescriptorData `json:",omitempty"`
	GlobalPtr    uint32                      `json:",omitempty"`
	CLR          *CLRData                    `json:",omitempty"`
	IAT          []IATEntry                  `json:",omitempty"`
	Header       []byte

	Is64      bool
	Is32      bool
	Anomalies []string `json:",omitempty"`
	// contains filtered or unexported fields
}

A File represents an open PE file.

func New

func New(name string, opts *Options) (*File, error)

New instaniates a file instance with options given a file name.

func NewBytes

func NewBytes(data []byte, opts *Options) (*File, error)

NewBytes instaniates a file instance with options given a memory buffer.

func (*File) Authentihash

func (pe *File) Authentihash() []byte

Authentihash generates the pe image file hash. The relevant sections to exclude during hashing are:

  • The location of the checksum
  • The location of the entry of the Certificate Table in the Data Directory
  • The location of the Certificate Table.

func (*File) COFFStringTable

func (pe *File) COFFStringTable() error

COFFStringTable retrieves the list of strings in the COFF string table if any.

func (*File) Checksum

func (pe *File) Checksum() uint32

Checksum calculates the PE checksum as generated by CheckSumMappedFile().

func (*File) Close

func (pe *File) Close() error

Close closes the File.

func (*File) GetAnomalies

func (pe *File) GetAnomalies() error

GetAnomalies reportes anomalies found in a PE binary. These nomalies does prevent the Windows loader from loading the files but is an interesting features for malware analysis.

func (*File) GetDelayImportEntryInfoByRVA

func (pe *File) GetDelayImportEntryInfoByRVA(rva uint32) (DelayImport, int)

GetDelayImportEntryInfoByRVA return an import function + index of the entry given an RVA.

func (*File) GetExportFunctionByRVA

func (pe *File) GetExportFunctionByRVA(rva uint32) ExportFunction

GetExportFunctionByRVA return an export function given an RVA.

func (*File) GetImportEntryInfoByRVA

func (pe *File) GetImportEntryInfoByRVA(rva uint32) (Import, int)

GetImportEntryInfoByRVA return an import function + index of the entry given an RVA.

func (*File) GetMetadataStreamIndexSize

func (pe *File) GetMetadataStreamIndexSize(BitPosition int) int

GetMetadataStreamIndexSize returns the size of indexes to read into a particular heap.

func (*File) GetStringFromData

func (pe *File) GetStringFromData(offset uint32, data []byte) []byte

GetStringFromData returns ASCII string from within the data.

func (*File) ImpHash

func (pe *File) ImpHash() (string, error)

ImpHash calculates the import hash. Algorithm: ========== Resolving ordinals to function names when they appear Converting both DLL names and function names to all lowercase Removing the file extensions from imported module names Building and storing the lowercased string . in an ordered list Generating the MD5 hash of the ordered list

func (*File) IsDLL

func (pe *File) IsDLL() bool

IsDLL returns true if the PE file is a standard DLL.

func (*File) IsDriver

func (pe *File) IsDriver() bool

IsDriver returns true if the PE file is a Windows driver.

func (*File) IsEXE

func (pe *File) IsEXE() bool

IsEXE returns true if the PE file is a standard executable.

func (*File) Parse

func (pe *File) Parse() error

Parse performs the file parsing for a PE binary.

func (*File) ParseCOFFSymbolTable

func (pe *File) ParseCOFFSymbolTable() error

ParseCOFFSymbolTable parses the COFF symbol table. The symbol table is inherited from the traditional COFF format. It is distinct from Microsoft Visual C++ debug information. A file can contain both a COFF symbol table and Visual C++ debug information, and the two are kept separate. Some Microsoft tools use the symbol table for limited but important purposes, such as communicating COMDAT information to the linker. Section names and file names, as well as code and data symbols, are listed in the symbol table.

func (*File) ParseDOSHeader

func (pe *File) ParseDOSHeader() (err error)

ParseDOSHeader parses the DOS header stub. Every PE file begins with a small MS-DOS stub. The need for this arose in the early days of Windows, before a significant number of consumers were running it. When executed on a machine without Windows, the program could at least print out amessage saying that Windows was required to run the executable.

func (*File) ParseDataDirectories

func (pe *File) ParseDataDirectories() error

ParseDataDirectories parses the data directores. The DataDirectory is an array of 16 structures. Each array entry has a predefined meaning for what it refers to.

func (*File) ParseNTHeader

func (pe *File) ParseNTHeader() (err error)

ParseNTHeader parse the PE NT header structure refered as IMAGE_NT_HEADERS. Its offset is given by the e_lfanew field in the IMAGE_DOS_HEADER at the beginning of the file.

func (*File) ParseRichHeader

func (pe *File) ParseRichHeader() error

ParseRichHeader parses the rich header struct.

func (*File) ParseSectionHeader

func (pe *File) ParseSectionHeader() (err error)

ParseSectionHeader parses the PE section headers. Each row of the section table is, in effect, a section header. It must immediately follow the PE header.

func (*File) PrettyCOFFTypeRepresentation

func (pe *File) PrettyCOFFTypeRepresentation(k uint8) string

PrettyCOFFTypeRepresentation returns the string representation of the `Type` field of a COFF table entry.

func (*File) PrettyDataDirectory

func (pe *File) PrettyDataDirectory(entry int) string

PrettyDataDirectory returns the string representations of the data directory entry.

func (*File) PrettyDllCharacteristics

func (pe *File) PrettyDllCharacteristics() []string

PrettyDllCharacteristics returns the string representations of the `DllCharacteristics` field of ImageOptionalHeader.

func (*File) PrettyImageFileCharacteristics

func (pe *File) PrettyImageFileCharacteristics() []string

PrettyImageFileCharacteristics returns the string representations of the `Characteristics` field of the IMAGE_FILE_HEADER.

func (*File) PrettyMachineType

func (pe *File) PrettyMachineType() string

PrettyMachineType returns the string representations of the `Machine` field of the IMAGE_FILE_HEADER.

func (*File) PrettyRelocTypeEntry

func (pe *File) PrettyRelocTypeEntry(k uint8) string

PrettyRelocTypeEntry returns the string representation of the `Type` field of a base reloc entry.

func (*File) PrettySectionFlags

func (pe *File) PrettySectionFlags(curSectionFlag uint32) []string

PrettySectionFlags returns the string representations of the `Flags` field of section header.

func (*File) PrettySubsystem

func (pe *File) PrettySubsystem() string

PrettySubsystem returns the string representations of the `Subsystem` field of ImageOptionalHeader.

func (*File) PrettyTLSCharacteristics

func (pe *File) PrettyTLSCharacteristics(Characteristics uint32) []string

PrettyTLSCharacteristics returns the string representations of the `Characteristics` field of TLS directory.

func (*File) ReadBytesAtOffset

func (pe *File) ReadBytesAtOffset(offset, size uint32) ([]byte, error)

ReadBytesAtOffset returns a byte array from offset.

func (*File) ReadUint16

func (pe *File) ReadUint16(offset uint32) (uint16, error)

ReadUint16 read a uint16 from a buffer.

func (*File) ReadUint32

func (pe *File) ReadUint32(offset uint32) (uint32, error)

ReadUint32 read a uint32 from a buffer.

func (*File) ReadUint64

func (pe *File) ReadUint64(offset uint32) (uint64, error)

ReadUint64 read a uint64 from a buffer.

func (*File) ReadUint8

func (pe *File) ReadUint8(offset uint32) (uint8, error)

ReadUint8 read a uint8 from a buffer.

func (*File) RichHeaderChecksum

func (pe *File) RichHeaderChecksum() uint32

RichHeaderChecksum calculate the Rich Header checksum.

type GUID

type GUID struct {
	Data1 uint32
	Data2 uint16
	Data3 uint16
	Data4 [8]byte
}

GUID is a 128-bit value consisting of one group of 8 hexadecimal digits, followed by three groups of 4 hexadecimal digits each, followed by one group of 12 hexadecimal digits.

type HybridPE

type HybridPE struct {
	CHPEMetadata interface{}
	CodeRanges   []CodeRange
	CompilerIAT  []CompilerIAT
}

type IATEntry

type IATEntry struct {
	Index   uint32
	Rva     uint32
	Value   interface{}
	Meaning string
}

IATEntry represents an entry inside the IAT.

type ImageARMRuntimeFunctionEntry

type ImageARMRuntimeFunctionEntry struct {
	// Function Start RVA is the 32-bit RVA of the start of the function. If
	// the function contains thumb code, the low bit of this address must be set.
	BeginAddress uint32 `bitfield:",functionstart"`

	// Flag is a 2-bit field that indicates how to interpret the remaining
	// 30 bits of the second .pdata word. If Flag is 0, then the remaining bits
	// form an Exception Information RVA (with the low two bits implicitly 0).
	// If Flag is non-zero, then the remaining bits form a Packed Unwind Data
	// structure.
	Flag uint8

	/* Exception Information RVA or Packed Unwind Data.

	Exception Information RVA is the address of the variable-length exception
	information structure, stored in the .xdata section.
	This data must be 4-byte aligned.

	Packed Unwind Data is a compressed description of the operations required
	to unwind from a function, assuming a canonical form. In this case, no
	.xdata record is required. */
	ExceptionFlag uint32
}

ImageARMRuntimeFunctionEntry represents the function table entry for the ARM platform.

type ImageBaseRelocation

type ImageBaseRelocation struct {
	// The image base plus the page RVA is added to each offset to create the
	// VA where the base relocation must be applied.
	VirtualAddress uint32

	// The total number of bytes in the base relocation block, including the
	// Page RVA and Block Size fields and the Type/Offset fields that follow.
	SizeOfBlock uint32
}

ImageBaseRelocation represents the IMAGE_BASE_RELOCATION structure. Each chunk of base relocation data begins with an IMAGE_BASE_RELOCATION structure.

type ImageBaseRelocationEntry

type ImageBaseRelocationEntry struct {
	// Locate data that must be reallocated in buffer (data being an address
	// we use pointer of pointer).
	Data uint16

	// The offset of the relocation. This value plus the VirtualAddress
	// in IMAGE_BASE_RELOCATION is the complete RVA.
	Offset uint16

	// A value that indicates the kind of relocation that should be performed.
	// Valid relocation types depend on machine type.
	Type uint8
}

ImageBaseRelocationEntry represents an image base relocation entry.

type ImageBoundForwardedRef

type ImageBoundForwardedRef struct {
	TimeDateStamp    uint32
	OffsetModuleName uint16
	Reserved         uint16
}

ImageBoundForwardedRef represents the IMAGE_BOUND_FORWARDER_REF.

type ImageBoundImportDescriptor

type ImageBoundImportDescriptor struct {
	TimeDateStamp               uint32 // is just the value from the Exports information of the DLL which is being imported from.
	OffsetModuleName            uint16 //  offset of the DLL name counted from the beginning of the BOUND_IMPORT table
	NumberOfModuleForwarderRefs uint16 // number of forwards

}

ImageBoundImportDescriptor represents the IMAGE_BOUND_IMPORT_DESCRIPTOR.

type ImageCHPEMetadataX86v1

type ImageCHPEMetadataX86v1 struct {
	Version                                  uint32
	CHPECodeAddressRangeOffset               uint32
	CHPECodeAddressRangeCount                uint32
	WowA64ExceptionHandlerFunctionPtr        uint32
	WowA64DispatchCallFunctionPtr            uint32
	WowA64DispatchIndirectCallFunctionPtr    uint32
	WowA64DispatchIndirectCallCfgFunctionPtr uint32
	WowA64DispatchRetFunctionPtr             uint32
	WowA64DispatchRetLeafFunctionPtr         uint32
	WowA64DispatchJumpFunctionPtr            uint32
}

type ImageCHPEMetadataX86v2

type ImageCHPEMetadataX86v2 struct {
	Version                                  uint32
	CHPECodeAddressRangeOffset               uint32
	CHPECodeAddressRangeCount                uint32
	WowA64ExceptionHandlerFunctionPtr        uint32
	WowA64DispatchCallFunctionPtr            uint32
	WowA64DispatchIndirectCallFunctionPtr    uint32
	WowA64DispatchIndirectCallCfgFunctionPtr uint32
	WowA64DispatchRetFunctionPtr             uint32
	WowA64DispatchRetLeafFunctionPtr         uint32
	WowA64DispatchJumpFunctionPtr            uint32
	CompilerIATPointer                       uint32 // Present if Version >= 2
}

type ImageCHPEMetadataX86v3

type ImageCHPEMetadataX86v3 struct {
	Version                                  uint32
	CHPECodeAddressRangeOffset               uint32
	CHPECodeAddressRangeCount                uint32
	WowA64ExceptionHandlerFunctionPtr        uint32
	WowA64DispatchCallFunctionPtr            uint32
	WowA64DispatchIndirectCallFunctionPtr    uint32
	WowA64DispatchIndirectCallCfgFunctionPtr uint32
	WowA64DispatchRetFunctionPtr             uint32
	WowA64DispatchRetLeafFunctionPtr         uint32
	WowA64DispatchJumpFunctionPtr            uint32
	CompilerIATPointer                       uint32
	WowA64RdtscFunctionPtr                   uint32 // Present if Version >= 3
}

type ImageCOR20Header

type ImageCOR20Header struct {

	// Size of the header in bytes.
	Cb uint32

	// Major number of the minimum version of the runtime required to run the
	// program.
	MajorRuntimeVersion uint16

	// Minor number of the version of the runtime required to run the program.
	MinorRuntimeVersio uint16

	// RVA and size of the metadata.
	MetaData ImageDataDirectory

	// Bitwise flags indicating attributes of this executable.
	Flags uint32

	// Metadata identifier (token) of the entry point for the image file; can
	// be 0 for DLL images. This field identifies a method belonging to this
	// module or a module containing the entry point method.
	// In images of version 2.0 and newer, this field may contain RVA of the
	// embedded native entry point method.
	// union {
	//
	// If COMIMAGE_FLAGS_NATIVE_ENTRYPOINT is not set,
	// EntryPointToken represents a managed entrypoint.
	//	DWORD               EntryPointToken;
	//
	// If COMIMAGE_FLAGS_NATIVE_ENTRYPOINT is set,
	// EntryPointRVA represents an RVA to a native entrypoint
	//	DWORD               EntryPointRVA;
	//};
	EntryPointRVAorToken uint32

	// This is the blob of managed resources. Fetched using
	// code:AssemblyNative.GetResource and code:PEFile.GetResource and accessible
	// from managed code from System.Assembly.GetManifestResourceStream. The
	// metadata has a table that maps names to offsets into this blob, so
	// logically the blob is a set of resources.
	Resources ImageDataDirectory

	// RVA and size of the hash data for this PE file, used by the loader for
	// binding and versioning. IL assemblies can be signed with a public-private
	// key to validate who created it. The signature goes here if this feature
	// is used.
	StrongNameSignature ImageDataDirectory

	// RVA and size of the Code Manager table. In the existing releases of the
	// runtime, this field is reserved and must be set to 0.
	CodeManagerTable ImageDataDirectory

	// RVA and size in bytes of an array of virtual table (v-table) fixups.
	// Among current managed compilers, only the VC++ linker and the IL
	// assembler can produce this array.
	VTableFixups ImageDataDirectory

	// RVA and size of an array of addresses of jump thunks. Among managed
	// compilers, only the VC++ of versions pre-8.0 could produce this table,
	// which allows the export of unmanaged native methods embedded in the
	// managed PE file. In v2.0+ of CLR this entry is obsolete and must be set
	// to 0.
	ExportAddressTableJumps ImageDataDirectory

	// Reserved for precompiled images; set to 0
	// NGEN images it points at a code:CORCOMPILE_HEADER structure
	ManagedNativeHeader ImageDataDirectory
}

ImageCOR20Header represents the CLR 2.0 header structure.

type ImageCORVTableFixup

type ImageCORVTableFixup struct {
	RVA   uint32 // Offset of v-table array in image.
	Count uint16 // How many entries at location.
	Type  uint16 // COR_VTABLE_xxx type of entries.
}

ImageCORVTableFixup defines the v-table fixups that contains the initializing information necessary for the runtime to create the thunks. Non VOS v-table entries. Define an array of these pointed to by IMAGE_COR20_HEADER.VTableFixups. Each entry describes a contiguous array of v-table slots. The slots start out initialized to the meta data token value for the method they need to call. At image load time, the CLR Loader will turn each entry into a pointer to machine code for the CPU and can be called directly.

type ImageDataDirectory

type ImageDataDirectory struct {

	// The relative virtual address of the table.
	VirtualAddress uint32

	// The size of the table, in bytes.
	Size uint32
}

ImageDataDirectory represents the directory format.

type ImageDebugDirectory

type ImageDebugDirectory struct {
	// Reserved, must be 0.
	Characteristics uint32

	// The time and date that the debug data was created.
	TimeDateStamp uint32

	// The major version number of the debug data format.
	MajorVersion uint16

	// The minor version number of the debug data format.
	MinorVersion uint16

	// The format of debugging information. This field enables support of
	// multiple debuggers.
	Type uint32

	// The size of the debug data (not including the debug directory itself).
	SizeOfData uint32

	//The address of the debug data when loaded, relative to the image base.
	AddressOfRawData uint32

	// The file pointer to the debug data.
	PointerToRawData uint32
}

ImageDebugDirectory represents the IMAGE_DEBUG_DIRECTORY structure. This directory indicates what form of debug information is present and where it is. This directory consists of an array of debug directory entries whose location and size are indicated in the image optional header.

type ImageDebugMisc

type ImageDebugMisc struct {
	DataType uint32 // The type of data carried in the `Data` field.

	// The length of this structure in bytes, including the entire Data field
	// and its NUL terminator (rounded to four byte multiple.)
	Length uint32

	// The encoding of the Data field. True if data is unicode string
	Unicode bool

	// Reserved
	Reserved [3]byte

	// Actual data
	Data string
}

ImageDebugMisc represents the IMAGE_DEBUG_MISC structure.

type ImageDelayImportDescriptor

type ImageDelayImportDescriptor struct {
	// As yet, no attribute flags are defined. The linker sets this field to zero
	// in the image. This field can be used to extend the record by indicating
	// the presence of new fields, or it can be used to indicate behaviors to
	// the delay or unload helper functions.
	Attributes uint32

	// The name of the DLL to be delay-loaded resides in the read-only data
	// section of the image. It is referenced through the szName field.
	Name uint32

	// The handle of the DLL to be delay-loaded is in the data section of the
	// image. The phmod field points to the handle. The supplied delay-load
	// helper uses this location to store the handle to the loaded DLL.
	ModuleHandleRVA uint32

	// The delay import address table (IAT) is referenced by the delay import
	// descriptor through the pIAT field. The delay-load helper updates these
	// pointers with the real entry points so that the thunks are no longer in
	// the calling loop
	ImportAddressTableRVA uint32

	// The delay import name table (INT) contains the names of the imports that
	// might require loading. They are ordered in the same fashion as the
	// function pointers in the IAT.
	ImportNameTableRVA uint32

	// The delay bound import address table (BIAT) is an optional table of
	// IMAGE_THUNK_DATA items that is used along with the timestamp field
	// of the delay-load directory table by a post-process binding phase.
	BoundImportAddressTableRVA uint32

	// The delay unload import address table (UIAT) is an optional table of
	// IMAGE_THUNK_DATA items that the unload code uses to handle an explicit
	// unload request. It consists of initialized data in the read-only section
	// that is an exact copy of the original IAT that referred the code to the
	// delay-load thunks. On the unload request, the library can be freed,
	// the *phmod cleared, and the UIAT written over the IAT to restore
	// everything to its preload state.
	UnloadInformationTableRVA uint32

	// 0 if not bound, otherwise, date/time of the target DLL.
	TimeDateStamp uint32
}

ImageDelayImportDescriptor represents the _IMAGE_DELAYLOAD_DESCRIPTOR structure.

type ImageDosHeader

type ImageDosHeader struct {
	// Magic number.
	Magic uint16

	// Bytes on last page of file.
	BytesOnLastPageOfFile uint16

	// Pages in file.
	PagesInFile uint16

	// Relocations.
	Relocations uint16

	// Size of header in paragraphs.
	SizeOfHeader uint16

	// Minimum extra paragraphs needed.
	MinExtraParagraphsNeeded uint16

	// Maximum extra paragraphs needed.
	MaxExtraParagraphsNeeded uint16

	// Initial (relative) SS value.
	InitialSS uint16

	// Initial SP value.
	InitialSP uint16

	// Checksum.
	Checksum uint16

	// Initial IP value.
	InitialIP uint16

	// Initial (relative) CS value.
	InitialCS uint16

	// File address of relocation table.
	AddressOfRelocationTable uint16

	// Overlay number.
	OverlayNumber uint16

	// Reserved words.
	ReservedWords1 [4]uint16

	// OEM identifier.
	OEMIdentifier uint16

	// OEM information.
	OEMInformation uint16

	// Reserved words.
	ReservedWords2 [10]uint16

	// File address of new exe header (Elfanew).
	AddressOfNewEXEHeader uint32
}

ImageDosHeader represents the DOS stub of a PE.

type ImageDynamicRelocation32

type ImageDynamicRelocation32 struct {
	Symbol        uint32
	BaseRelocSize uint32
}

type ImageDynamicRelocation32v2

type ImageDynamicRelocation32v2 struct {
	HeaderSize    uint32
	FixupInfoSize uint32
	Symbol        uint32
	SymbolGroup   uint32
	Flags         uint32
}

type ImageDynamicRelocation64

type ImageDynamicRelocation64 struct {
	Symbol        uint64
	BaseRelocSize uint32
}

type ImageDynamicRelocation64v2

type ImageDynamicRelocation64v2 struct {
	HeaderSize    uint32
	FixupInfoSize uint32
	Symbol        uint64
	SymbolGroup   uint32
	Flags         uint32
}

type ImageDynamicRelocationTable

type ImageDynamicRelocationTable struct {
	Version uint32
	Size    uint32
}

type ImageEnclaveConfig32

type ImageEnclaveConfig32 struct {

	// The size of the IMAGE_ENCLAVE_CONFIG32 structure, in bytes.
	Size uint32

	// If the size of IMAGE_ENCLAVE_CONFIG32 that the image loader can process is less than MinimumRequiredConfigSize, the enclave cannot be run securely. If MinimumRequiredConfigSize is zero, the minimum size of the IMAGE_ENCLAVE_CONFIG32 structure that the image loader must be able to process in order for the enclave to be usable is assumed to be the size of the structure through and including the MinimumRequiredConfigSize member.
	MinimumRequiredConfigSize uint32

	// A flag that indicates whether the enclave permits debugging.
	PolicyFlags uint32

	// The number of images in the array of images that the ImportList member
	// points to.
	NumberOfImports uint32

	// The relative virtual address of the array of images that the enclave
	// image may import, with identity information for each image.
	ImportList uint32

	// The size of each image in the array of images that the ImportList member
	// points to.
	ImportEntrySize uint32

	// The family identifier that the author of the enclave assigned to the enclave.
	FamilyID [ImageEnclaveShortIdLength]uint8

	// The image identifier that the author of the enclave assigned to the enclave.
	ImageID [ImageEnclaveShortIdLength]uint8

	// The version number that the author of the enclave assigned to the enclave.
	ImageVersion uint32

	// The security version number that the author of the enclave assigned to
	// the enclave.
	SecurityVersion uint32

	// The expected virtual size of the private address range for the enclave,
	// in bytes.
	EnclaveSize uint32

	// The maximum number of threads that can be created within the enclave.
	NumberOfThreads uint32

	// A flag that indicates whether the image is suitable for use as the
	// primary image in the enclave.
	EnclaveFlags uint32
}

type ImageEnclaveConfig64

type ImageEnclaveConfig64 struct {

	// The size of the IMAGE_ENCLAVE_CONFIG32 structure, in bytes.
	Size uint32

	// If the size of IMAGE_ENCLAVE_CONFIG32 that the image loader can process is less than MinimumRequiredConfigSize, the enclave cannot be run securely. If MinimumRequiredConfigSize is zero, the minimum size of the IMAGE_ENCLAVE_CONFIG32 structure that the image loader must be able to process in order for the enclave to be usable is assumed to be the size of the structure through and including the MinimumRequiredConfigSize member.
	MinimumRequiredConfigSize uint32

	// A flag that indicates whether the enclave permits debugging.
	PolicyFlags uint32

	// The number of images in the array of images that the ImportList member
	// points to.
	NumberOfImports uint32

	// The relative virtual address of the array of images that the enclave
	// image may import, with identity information for each image.
	ImportList uint32

	// The size of each image in the array of images that the ImportList member
	// points to.
	ImportEntrySize uint32

	// The family identifier that the author of the enclave assigned to the enclave.
	FamilyID [ImageEnclaveShortIdLength]uint8

	// The image identifier that the author of the enclave assigned to the enclave.
	ImageID [ImageEnclaveShortIdLength]uint8

	// The version number that the author of the enclave assigned to the enclave.
	ImageVersion uint32

	// The security version number that the author of the enclave assigned to the enclave.
	SecurityVersion uint32

	// The expected virtual size of the private address range for the enclave,in bytes.
	EnclaveSize uint64

	// The maximum number of threads that can be created within the enclave.
	NumberOfThreads uint32

	// A flag that indicates whether the image is suitable for use as the primary image in the enclave.
	EnclaveFlags uint32
}

type ImageEnclaveImport

type ImageEnclaveImport struct {

	// The type of identifier of the image that must match the value in the import record.
	MatchType uint32

	// The minimum enclave security version that each image must have for the image to be imported successfully. The image is rejected unless its enclave security version is equal to or greater than the minimum value in the import record. Set the value in the import record to zero to turn off the security version check.
	MinimumSecurityVersion uint32

	// The unique identifier of the primary module for the enclave, if the MatchType member is IMAGE_ENCLAVE_IMPORT_MATCH_UNIQUE_ID. Otherwise, the author identifier of the primary module for the enclave..
	UniqueOrAuthorID [ImageEnclaveLongIdLength]uint8

	// The family identifier of the primary module for the enclave.
	FamilyID [ImageEnclaveShortIdLength]uint8

	// The image identifier of the primary module for the enclave.
	ImageID [ImageEnclaveShortIdLength]uint8

	// The relative virtual address of a NULL-terminated string that contains the same value found in the import directory for the image.
	ImportName uint32

	// Reserved.
	Reserved uint32
}

ImageEnclaveImport defines a entry in the array of images that an enclave can import.

type ImageEpilogueDynamicRelocationHeader

type ImageEpilogueDynamicRelocationHeader struct {
	EpilogueCount               uint32
	EpilogueByteCount           uint8
	BranchDescriptorElementSize uint8
	BranchDescriptorCount       uint8
}

type ImageExportDirectory

type ImageExportDirectory struct {
	// Reserved, must be 0.
	Characteristics uint32

	// The time and date that the export data was created.
	TimeDateStamp uint32

	// The major version number.
	//The major and minor version numbers can be set by the user.
	MajorVersion uint16

	// The minor version number.
	MinorVersion uint16

	// The address of the ASCII string that contains the name of the DLL.
	// This address is relative to the image base.
	Name uint32

	// The starting ordinal number for exports in this image. This field
	// specifies the starting ordinal number for the export address table.
	// It is usually set to 1.
	Base uint32

	// The number of entries in the export address table.
	NumberOfFunctions uint32

	// The number of entries in the name pointer table. This is also the number
	// of entries in the ordinal table.
	NumberOfNames uint32

	// The address of the export address table, relative to the image base.
	AddressOfFunctions uint32

	// The address of the export name pointer table, relative to the image base.
	// The table size is given by the Number of Name Pointers field.
	AddressOfNames uint32

	// The address of the ordinal table, relative to the image base.
	AddressOfNameOrdinals uint32
}

ImageExportDirectory represents the IMAGE_EXPORT_DIRECTORY structure. The export directory table contains address information that is used to resolve imports to the entry points within this image.

type ImageFileHeader

type ImageFileHeader struct {
	// The number that identifies the type of target machine.
	Machine uint16

	// The number of sections. This indicates the size of the section table,
	// which immediately follows the headers.
	NumberOfSections uint16

	// // The low 32 bits of the number of seconds since 00:00 January 1, 1970
	// (a C run-time time_t value), that indicates when the file was created.
	TimeDateStamp uint32

	// // The file offset of the COFF symbol table, or zero if no COFF symbol
	// table is present. This value should be zero for an image because COFF
	// debugging information is deprecated.
	PointerToSymbolTable uint32

	// The number of entries in the symbol table. This data can be used to
	// locate the string table, which immediately follows the symbol table.
	// This value should be zero for an image because COFF debugging information
	// is deprecated.
	NumberOfSymbols uint32

	// The size of the optional header, which is required for executable files
	// but not for object files. This value should be zero for an object file.
	SizeOfOptionalHeader uint16

	// The flags that indicate the attributes of the file.
	Characteristics uint16
}

ImageFileHeader contains infos about the physical layout and properties of the file.

type ImageImportDescriptor

type ImageImportDescriptor struct {
	// The RVA of the import lookup/name table (INT). This table contains a name
	// or ordinal for each import. The INT is an array of IMAGE_THUNK_DATA structs.
	OriginalFirstThunk uint32

	// The stamp that is set to zero until the image is bound. After the image
	// is bound, this field is set to the time/data stamp of the DLL.
	TimeDateStamp uint32

	// The index of the first forwarder reference (-1 if no forwarders).
	ForwarderChain uint32

	// The address of an ASCII string that contains the name of the DLL.
	// This address is relative to the image base.
	Name uint32

	// The RVA of the import address table (IAT). The contents of this table are
	// identical to the contents of the import lookup table until the image is bound.
	FirstThunk uint32
}

ImageImportDescriptor describes the remainder of the import information. The import directory table contains address information that is used to resolve fixup references to the entry points within a DLL image. It consists of an array of import directory entries, one entry for each DLL to which the image refers. The last directory entry is empty (filled with null values), which indicates the end of the directory table.

type ImageLoadConfigCodeIntegrity

type ImageLoadConfigCodeIntegrity struct {
	Flags         uint16 // Flags to indicate if CI information is available, etc.
	Catalog       uint16 // 0xFFFF means not available
	CatalogOffset uint32
	Reserved      uint32 // Additional bitmask to be defined later
}

ImageLoadConfigCodeIntegrity Code Integrity in loadconfig (CI).

type ImageLoadConfigDirectory32

type ImageLoadConfigDirectory32 struct {
	// The actual size of the structure inclusive. May differ from the size
	// given in the data directory for Windows XP and earlier compatibility.
	Size uint32

	// Date and time stamp value.
	TimeDateStamp uint32

	// Major version number.
	MajorVersion uint16

	// Minor version number.
	MinorVersion uint16

	// The global loader flags to clear for this process as the loader starts
	// the process.
	GlobalFlagsClear uint32

	// The global loader flags to set for this process as the loader starts the
	// process.
	GlobalFlagsSet uint32

	// The default timeout value to use for this process's critical sections
	// that are abandoned.
	CriticalSectionDefaultTimeout uint32

	// Memory that must be freed before it is returned to the system, in bytes.
	DeCommitFreeBlockThreshold uint32

	// Total amount of free memory, in bytes.
	DeCommitTotalFreeThreshold uint32

	// [x86 only] The VA of a list of addresses where the LOCK prefix is used so
	// that they can be replaced with NOP on single processor machines.
	LockPrefixTable uint32

	// Maximum allocation size, in bytes.
	MaximumAllocationSize uint32

	// Maximum virtual memory size, in bytes.
	VirtualMemoryThreshold uint32

	// Process heap flags that correspond to the first argument of the HeapCreate
	// function. These flags apply to the process heap that is created during
	// process startup.
	ProcessHeapFlags uint32

	// Setting this field to a non-zero value is equivalent to calling
	// SetProcessAffinityMask with this value during process startup (.exe only)
	ProcessAffinityMask uint32

	// The service pack version identifier.
	CSDVersion uint16

	// Must be zero.
	DependentLoadFlags uint16

	// Reserved for use by the system.
	EditList uint32

	// A pointer to a cookie that is used by Visual C++ or GS implementation.
	SecurityCookie uint32

	// [x86 only] The VA of the sorted table of RVAs of each valid, unique SE
	// handler in the image.
	SEHandlerTable uint32

	// [x86 only] The count of unique handlers in the table.
	SEHandlerCount uint32

	// The VA where Control Flow Guard check-function pointer is stored.
	GuardCFCheckFunctionPointer uint32

	// The VA where Control Flow Guard dispatch-function pointer is stored.
	GuardCFDispatchFunctionPointer uint32

	// The VA of the sorted table of RVAs of each Control Flow Guard function in
	// the image.
	GuardCFFunctionTable uint32

	// The count of unique RVAs in the above table.
	GuardCFFunctionCount uint32

	// Control Flow Guard related flags.
	GuardFlags uint32

	// Code integrity information.
	CodeIntegrity ImageLoadConfigCodeIntegrity

	// The VA where Control Flow Guard address taken IAT table is stored.
	GuardAddressTakenIatEntryTable uint32

	// The count of unique RVAs in the above table.
	GuardAddressTakenIatEntryCount uint32

	// The VA where Control Flow Guard long jump target table is stored.
	GuardLongJumpTargetTable uint32

	// The count of unique RVAs in the above table.
	GuardLongJumpTargetCount uint32

	DynamicValueRelocTable uint32

	// Not sure when this was renamed from HybridMetadataPointer.
	CHPEMetadataPointer uint32

	GuardRFFailureRoutine                    uint32
	GuardRFFailureRoutineFunctionPointer     uint32
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint32
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint32
	VolatileMetadataPointer                  uint32
	GuardEHContinuationTable                 uint32
	GuardEHContinuationCount                 uint32
	GuardXFGCheckFunctionPointer             uint32
	GuardXFGDispatchFunctionPointer          uint32
	GuardXFGTableDispatchFunctionPointer     uint32
}

ImageLoadConfigDirectory32 Contains the load configuration data of an image for x86 binaries.

type ImageLoadConfigDirectory32v1

type ImageLoadConfigDirectory32v1 struct {
	Size                          uint32
	TimeDateStamp                 uint32
	MajorVersion                  uint16
	MinorVersion                  uint16
	GlobalFlagsClear              uint32
	GlobalFlagsSet                uint32
	CriticalSectionDefaultTimeout uint32
	DeCommitFreeBlockThreshold    uint32
	DeCommitTotalFreeThreshold    uint32
	LockPrefixTable               uint32
	MaximumAllocationSize         uint32
	VirtualMemoryThreshold        uint32
	ProcessHeapFlags              uint32
	ProcessAffinityMask           uint32
	CSDVersion                    uint16
	DependentLoadFlags            uint16
	EditList                      uint32
	SecurityCookie                uint32
}

ImageLoadConfigDirectory32v1 size is 0x40.

type ImageLoadConfigDirectory32v10

type ImageLoadConfigDirectory32v10 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint32
	DeCommitTotalFreeThreshold               uint32
	LockPrefixTable                          uint32
	MaximumAllocationSize                    uint32
	VirtualMemoryThreshold                   uint32
	ProcessHeapFlags                         uint32
	ProcessAffinityMask                      uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint32
	SecurityCookie                           uint32
	SEHandlerTable                           uint32
	SEHandlerCount                           uint32
	GuardCFCheckFunctionPointer              uint32
	GuardCFDispatchFunctionPointer           uint32
	GuardCFFunctionTable                     uint32
	GuardCFFunctionCount                     uint32
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint32
	GuardAddressTakenIatEntryCount           uint32
	GuardLongJumpTargetTable                 uint32
	GuardLongJumpTargetCount                 uint32
	DynamicValueRelocTable                   uint32
	CHPEMetadataPointer                      uint32
	GuardRFFailureRoutine                    uint32
	GuardRFFailureRoutineFunctionPointer     uint32
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint32
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint32
	VolatileMetadataPointer                  uint32
}

ImageLoadConfigDirectory32v10 size is 0xA4 since Windows 10 build 18362 (or maybe earlier).

type ImageLoadConfigDirectory32v11

type ImageLoadConfigDirectory32v11 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint32
	DeCommitTotalFreeThreshold               uint32
	LockPrefixTable                          uint32
	MaximumAllocationSize                    uint32
	VirtualMemoryThreshold                   uint32
	ProcessHeapFlags                         uint32
	ProcessAffinityMask                      uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint32
	SecurityCookie                           uint32
	SEHandlerTable                           uint32
	SEHandlerCount                           uint32
	GuardCFCheckFunctionPointer              uint32
	GuardCFDispatchFunctionPointer           uint32
	GuardCFFunctionTable                     uint32
	GuardCFFunctionCount                     uint32
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint32
	GuardAddressTakenIatEntryCount           uint32
	GuardLongJumpTargetTable                 uint32
	GuardLongJumpTargetCount                 uint32
	DynamicValueRelocTable                   uint32
	CHPEMetadataPointer                      uint32
	GuardRFFailureRoutine                    uint32
	GuardRFFailureRoutineFunctionPointer     uint32
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint32
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint32
	VolatileMetadataPointer                  uint32
	GuardEHContinuationTable                 uint32
	GuardEHContinuationCount                 uint32
}

ImageLoadConfigDirectory32v11 size is 0xAC since Windows 10 build 19564 (or maybe earlier).

type ImageLoadConfigDirectory32v12

type ImageLoadConfigDirectory32v12 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint32
	DeCommitTotalFreeThreshold               uint32
	LockPrefixTable                          uint32
	MaximumAllocationSize                    uint32
	VirtualMemoryThreshold                   uint32
	ProcessHeapFlags                         uint32
	ProcessAffinityMask                      uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint32
	SecurityCookie                           uint32
	SEHandlerTable                           uint32
	SEHandlerCount                           uint32
	GuardCFCheckFunctionPointer              uint32
	GuardCFDispatchFunctionPointer           uint32
	GuardCFFunctionTable                     uint32
	GuardCFFunctionCount                     uint32
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint32
	GuardAddressTakenIatEntryCount           uint32
	GuardLongJumpTargetTable                 uint32
	GuardLongJumpTargetCount                 uint32
	DynamicValueRelocTable                   uint32
	CHPEMetadataPointer                      uint32
	GuardRFFailureRoutine                    uint32
	GuardRFFailureRoutineFunctionPointer     uint32
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint32
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint32
	VolatileMetadataPointer                  uint32
	GuardEHContinuationTable                 uint32
	GuardEHContinuationCount                 uint32
	GuardXFGCheckFunctionPointer             uint32
	GuardXFGDispatchFunctionPointer          uint32
	GuardXFGTableDispatchFunctionPointer     uint32
}

ImageLoadConfigDirectory32v12 size is 0xB8 since Visual C++ 2019 / RS5_IMAGE_LOAD_CONFIG_DIRECTORY32.

type ImageLoadConfigDirectory32v2

type ImageLoadConfigDirectory32v2 struct {
	Size                          uint32
	TimeDateStamp                 uint32
	MajorVersion                  uint16
	MinorVersion                  uint16
	GlobalFlagsClear              uint32
	GlobalFlagsSet                uint32
	CriticalSectionDefaultTimeout uint32
	DeCommitFreeBlockThreshold    uint32
	DeCommitTotalFreeThreshold    uint32
	LockPrefixTable               uint32
	MaximumAllocationSize         uint32
	VirtualMemoryThreshold        uint32
	ProcessHeapFlags              uint32
	ProcessAffinityMask           uint32
	CSDVersion                    uint16
	DependentLoadFlags            uint16
	EditList                      uint32
	SecurityCookie                uint32
	SEHandlerTable                uint32
	SEHandlerCount                uint32
}

ImageLoadConfigDirectory32v2 size is 0x48.

type ImageLoadConfigDirectory32v3

type ImageLoadConfigDirectory32v3 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint32
	DeCommitTotalFreeThreshold     uint32
	LockPrefixTable                uint32
	MaximumAllocationSize          uint32
	VirtualMemoryThreshold         uint32
	ProcessHeapFlags               uint32
	ProcessAffinityMask            uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint32
	SecurityCookie                 uint32
	SEHandlerTable                 uint32
	SEHandlerCount                 uint32
	GuardCFCheckFunctionPointer    uint32
	GuardCFDispatchFunctionPointer uint32
	GuardCFFunctionTable           uint32
	GuardCFFunctionCount           uint32
	GuardFlags                     uint32
}

ImageLoadConfigDirectory32v3 size is 0x5C.

type ImageLoadConfigDirectory32v4

type ImageLoadConfigDirectory32v4 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint32
	DeCommitTotalFreeThreshold     uint32
	LockPrefixTable                uint32
	MaximumAllocationSize          uint32
	VirtualMemoryThreshold         uint32
	ProcessHeapFlags               uint32
	ProcessAffinityMask            uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint32
	SecurityCookie                 uint32
	SEHandlerTable                 uint32
	SEHandlerCount                 uint32
	GuardCFCheckFunctionPointer    uint32
	GuardCFDispatchFunctionPointer uint32
	GuardCFFunctionTable           uint32
	GuardCFFunctionCount           uint32
	GuardFlags                     uint32
	CodeIntegrity                  ImageLoadConfigCodeIntegrity
}

ImageLoadConfigDirectory32v4 size is 0x6c since Windows 10 (preview 9879)

type ImageLoadConfigDirectory32v5

type ImageLoadConfigDirectory32v5 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint32
	DeCommitTotalFreeThreshold     uint32
	LockPrefixTable                uint32
	MaximumAllocationSize          uint32
	VirtualMemoryThreshold         uint32
	ProcessHeapFlags               uint32
	ProcessAffinityMask            uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint32
	SecurityCookie                 uint32
	SEHandlerTable                 uint32
	SEHandlerCount                 uint32
	GuardCFCheckFunctionPointer    uint32
	GuardCFDispatchFunctionPointer uint32
	GuardCFFunctionTable           uint32
	GuardCFFunctionCount           uint32
	GuardFlags                     uint32
	CodeIntegrity                  ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable uint32
	GuardAddressTakenIatEntryCount uint32
	GuardLongJumpTargetTable       uint32
	GuardLongJumpTargetCount       uint32
}

ImageLoadConfigDirectory32v5 size is 0x78 since Windows 10 build 14286 (or maybe earlier).

type ImageLoadConfigDirectory32v6

type ImageLoadConfigDirectory32v6 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint32
	DeCommitTotalFreeThreshold     uint32
	LockPrefixTable                uint32
	MaximumAllocationSize          uint32
	VirtualMemoryThreshold         uint32
	ProcessHeapFlags               uint32
	ProcessAffinityMask            uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint32
	SecurityCookie                 uint32
	SEHandlerTable                 uint32
	SEHandlerCount                 uint32
	GuardCFCheckFunctionPointer    uint32
	GuardCFDispatchFunctionPointer uint32
	GuardCFFunctionTable           uint32
	GuardCFFunctionCount           uint32
	GuardFlags                     uint32
	CodeIntegrity                  ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable uint32
	GuardAddressTakenIatEntryCount uint32
	GuardLongJumpTargetTable       uint32
	GuardLongJumpTargetCount       uint32
	DynamicValueRelocTable         uint32
	HybridMetadataPointer          uint32
}

ImageLoadConfigDirectory32v6 size is 0x80 since Windows 10 build 14383 (or maybe earlier).

type ImageLoadConfigDirectory32v7

type ImageLoadConfigDirectory32v7 struct {
	Size                                 uint32
	TimeDateStamp                        uint32
	MajorVersion                         uint16
	MinorVersion                         uint16
	GlobalFlagsClear                     uint32
	GlobalFlagsSet                       uint32
	CriticalSectionDefaultTimeout        uint32
	DeCommitFreeBlockThreshold           uint32
	DeCommitTotalFreeThreshold           uint32
	LockPrefixTable                      uint32
	MaximumAllocationSize                uint32
	VirtualMemoryThreshold               uint32
	ProcessHeapFlags                     uint32
	ProcessAffinityMask                  uint32
	CSDVersion                           uint16
	DependentLoadFlags                   uint16
	EditList                             uint32
	SecurityCookie                       uint32
	SEHandlerTable                       uint32
	SEHandlerCount                       uint32
	GuardCFCheckFunctionPointer          uint32
	GuardCFDispatchFunctionPointer       uint32
	GuardCFFunctionTable                 uint32
	GuardCFFunctionCount                 uint32
	GuardFlags                           uint32
	CodeIntegrity                        ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable       uint32
	GuardAddressTakenIatEntryCount       uint32
	GuardLongJumpTargetTable             uint32
	GuardLongJumpTargetCount             uint32
	DynamicValueRelocTable               uint32
	CHPEMetadataPointer                  uint32
	GuardRFFailureRoutine                uint32
	GuardRFFailureRoutineFunctionPointer uint32
	DynamicValueRelocTableOffset         uint32
	DynamicValueRelocTableSection        uint16
	Reserved2                            uint16
}

ImageLoadConfigDirectory32v7 size is 0x90 since Windows 10 build 14901 (or maybe earlier)

type ImageLoadConfigDirectory32v8

type ImageLoadConfigDirectory32v8 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint32
	DeCommitTotalFreeThreshold               uint32
	LockPrefixTable                          uint32
	MaximumAllocationSize                    uint32
	VirtualMemoryThreshold                   uint32
	ProcessHeapFlags                         uint32
	ProcessAffinityMask                      uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint32
	SecurityCookie                           uint32
	SEHandlerTable                           uint32
	SEHandlerCount                           uint32
	GuardCFCheckFunctionPointer              uint32
	GuardCFDispatchFunctionPointer           uint32
	GuardCFFunctionTable                     uint32
	GuardCFFunctionCount                     uint32
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint32
	GuardAddressTakenIatEntryCount           uint32
	GuardLongJumpTargetTable                 uint32
	GuardLongJumpTargetCount                 uint32
	DynamicValueRelocTable                   uint32
	CHPEMetadataPointer                      uint32
	GuardRFFailureRoutine                    uint32
	GuardRFFailureRoutineFunctionPointer     uint32
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint32
	HotPatchTableOffset                      uint32
}

ImageLoadConfigDirectory32v8 size is 0x98 since Windows 10 build 15002 (or maybe earlier).

type ImageLoadConfigDirectory32v9

type ImageLoadConfigDirectory32v9 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint32
	DeCommitTotalFreeThreshold               uint32
	LockPrefixTable                          uint32
	MaximumAllocationSize                    uint32
	VirtualMemoryThreshold                   uint32
	ProcessHeapFlags                         uint32
	ProcessAffinityMask                      uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint32
	SecurityCookie                           uint32
	SEHandlerTable                           uint32
	SEHandlerCount                           uint32
	GuardCFCheckFunctionPointer              uint32
	GuardCFDispatchFunctionPointer           uint32
	GuardCFFunctionTable                     uint32
	GuardCFFunctionCount                     uint32
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint32
	GuardAddressTakenIatEntryCount           uint32
	GuardLongJumpTargetTable                 uint32
	GuardLongJumpTargetCount                 uint32
	DynamicValueRelocTable                   uint32
	CHPEMetadataPointer                      uint32
	GuardRFFailureRoutine                    uint32
	GuardRFFailureRoutineFunctionPointer     uint32
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint32
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint32
}

ImageLoadConfigDirectory32v9 size is 0xA0 since Windows 10 build 16237 (or maybe earlier).

type ImageLoadConfigDirectory64

type ImageLoadConfigDirectory64 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint64
	DeCommitTotalFreeThreshold               uint64
	LockPrefixTable                          uint64
	MaximumAllocationSize                    uint64
	VirtualMemoryThreshold                   uint64
	ProcessAffinityMask                      uint64
	ProcessHeapFlags                         uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint64
	SecurityCookie                           uint64
	SEHandlerTable                           uint64
	SEHandlerCount                           uint64
	GuardCFCheckFunctionPointer              uint64
	GuardCFDispatchFunctionPointer           uint64
	GuardCFFunctionTable                     uint64
	GuardCFFunctionCount                     uint64
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint64
	GuardAddressTakenIatEntryCount           uint64
	GuardLongJumpTargetTable                 uint64
	GuardLongJumpTargetCount                 uint64
	DynamicValueRelocTable                   uint64
	CHPEMetadataPointer                      uint64
	GuardRFFailureRoutine                    uint64
	GuardRFFailureRoutineFunctionPointer     uint64
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint64
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint64
	VolatileMetadataPointer                  uint64
	GuardEHContinuationTable                 uint64
	GuardEHContinuationCount                 uint64
	GuardXFGCheckFunctionPointer             uint64
	GuardXFGDispatchFunctionPointer          uint64
	GuardXFGTableDispatchFunctionPointer     uint64
}

ImageLoadConfigDirectory64 Contains the load configuration data of an image for x64 binaries.

type ImageLoadConfigDirectory64v10

type ImageLoadConfigDirectory64v10 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint64
	DeCommitTotalFreeThreshold               uint64
	LockPrefixTable                          uint64
	MaximumAllocationSize                    uint64
	VirtualMemoryThreshold                   uint64
	ProcessAffinityMask                      uint64
	ProcessHeapFlags                         uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint64
	SecurityCookie                           uint64
	SEHandlerTable                           uint64
	SEHandlerCount                           uint64
	GuardCFCheckFunctionPointer              uint64
	GuardCFDispatchFunctionPointer           uint64
	GuardCFFunctionTable                     uint64
	GuardCFFunctionCount                     uint64
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint64
	GuardAddressTakenIatEntryCount           uint64
	GuardLongJumpTargetTable                 uint64
	GuardLongJumpTargetCount                 uint64
	DynamicValueRelocTable                   uint64
	CHPEMetadataPointer                      uint64
	GuardRFFailureRoutine                    uint64
	GuardRFFailureRoutineFunctionPointer     uint64
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint64
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint64
	VolatileMetadataPointer                  uint64
}

ImageLoadConfigDirectory64v10 for binaries compiled since Windows 10 build 18362 (or maybe earlier).

type ImageLoadConfigDirectory64v11

type ImageLoadConfigDirectory64v11 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint64
	DeCommitTotalFreeThreshold               uint64
	LockPrefixTable                          uint64
	MaximumAllocationSize                    uint64
	VirtualMemoryThreshold                   uint64
	ProcessAffinityMask                      uint64
	ProcessHeapFlags                         uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint64
	SecurityCookie                           uint64
	SEHandlerTable                           uint64
	SEHandlerCount                           uint64
	GuardCFCheckFunctionPointer              uint64
	GuardCFDispatchFunctionPointer           uint64
	GuardCFFunctionTable                     uint64
	GuardCFFunctionCount                     uint64
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint64
	GuardAddressTakenIatEntryCount           uint64
	GuardLongJumpTargetTable                 uint64
	GuardLongJumpTargetCount                 uint64
	DynamicValueRelocTable                   uint64
	CHPEMetadataPointer                      uint64
	GuardRFFailureRoutine                    uint64
	GuardRFFailureRoutineFunctionPointer     uint64
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint64
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint64
	VolatileMetadataPointer                  uint64
	GuardEHContinuationTable                 uint64
	GuardEHContinuationCount                 uint64
}

ImageLoadConfigDirectory64v11 for binaries compiled since Windows 10 build 19534 (or maybe earlier).

type ImageLoadConfigDirectory64v12

type ImageLoadConfigDirectory64v12 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint64
	DeCommitTotalFreeThreshold               uint64
	LockPrefixTable                          uint64
	MaximumAllocationSize                    uint64
	VirtualMemoryThreshold                   uint64
	ProcessAffinityMask                      uint64
	ProcessHeapFlags                         uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint64
	SecurityCookie                           uint64
	SEHandlerTable                           uint64
	SEHandlerCount                           uint64
	GuardCFCheckFunctionPointer              uint64
	GuardCFDispatchFunctionPointer           uint64
	GuardCFFunctionTable                     uint64
	GuardCFFunctionCount                     uint64
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint64
	GuardAddressTakenIatEntryCount           uint64
	GuardLongJumpTargetTable                 uint64
	GuardLongJumpTargetCount                 uint64
	DynamicValueRelocTable                   uint64
	CHPEMetadataPointer                      uint64
	GuardRFFailureRoutine                    uint64
	GuardRFFailureRoutineFunctionPointer     uint64
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint64
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint64
	VolatileMetadataPointer                  uint64
	GuardEHContinuationTable                 uint64
	GuardEHContinuationCount                 uint64
	GuardXFGCheckFunctionPointer             uint64
	GuardXFGDispatchFunctionPointer          uint64
	GuardXFGTableDispatchFunctionPointer     uint64
}

ImageLoadConfigDirectory64v12 for binaries compiled since Visual C++ 2019 / RS5_IMAGE_LOAD_CONFIG_DIRECTORY64.

type ImageLoadConfigDirectory64v2

type ImageLoadConfigDirectory64v2 struct {
	Size                          uint32
	TimeDateStamp                 uint32
	MajorVersion                  uint16
	MinorVersion                  uint16
	GlobalFlagsClear              uint32
	GlobalFlagsSet                uint32
	CriticalSectionDefaultTimeout uint32
	DeCommitFreeBlockThreshold    uint64
	DeCommitTotalFreeThreshold    uint64
	LockPrefixTable               uint64
	MaximumAllocationSize         uint64
	VirtualMemoryThreshold        uint64
	ProcessAffinityMask           uint64
	ProcessHeapFlags              uint32
	CSDVersion                    uint16
	DependentLoadFlags            uint16
	EditList                      uint64
	SecurityCookie                uint64
	SEHandlerTable                uint64
	SEHandlerCount                uint64
}

ImageLoadConfigDirectory64v2 is the first structure for x64. No _IMAGE_LOAD_CONFIG_DIRECTORY64_V1 exists

type ImageLoadConfigDirectory64v3

type ImageLoadConfigDirectory64v3 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint64
	DeCommitTotalFreeThreshold     uint64
	LockPrefixTable                uint64
	MaximumAllocationSize          uint64
	VirtualMemoryThreshold         uint64
	ProcessAffinityMask            uint64
	ProcessHeapFlags               uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint64
	SecurityCookie                 uint64
	SEHandlerTable                 uint64
	SEHandlerCount                 uint64
	GuardCFCheckFunctionPointer    uint64
	GuardCFDispatchFunctionPointer uint64
	GuardCFFunctionTable           uint64
	GuardCFFunctionCount           uint64
	GuardFlags                     uint32
}

ImageLoadConfigDirectory64v3 added #pragma pack(4).

type ImageLoadConfigDirectory64v4

type ImageLoadConfigDirectory64v4 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint64
	DeCommitTotalFreeThreshold     uint64
	LockPrefixTable                uint64
	MaximumAllocationSize          uint64
	VirtualMemoryThreshold         uint64
	ProcessAffinityMask            uint64
	ProcessHeapFlags               uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint64
	SecurityCookie                 uint64
	SEHandlerTable                 uint64
	SEHandlerCount                 uint64
	GuardCFCheckFunctionPointer    uint64
	GuardCFDispatchFunctionPointer uint64
	GuardCFFunctionTable           uint64
	GuardCFFunctionCount           uint64
	GuardFlags                     uint32
	CodeIntegrity                  ImageLoadConfigCodeIntegrity
}

ImageLoadConfigDirectory64v4 for binaries compiled since Windows 10 build 9879 (or maybe earlier).

type ImageLoadConfigDirectory64v5

type ImageLoadConfigDirectory64v5 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint64
	DeCommitTotalFreeThreshold     uint64
	LockPrefixTable                uint64
	MaximumAllocationSize          uint64
	VirtualMemoryThreshold         uint64
	ProcessAffinityMask            uint64
	ProcessHeapFlags               uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint64
	SecurityCookie                 uint64
	SEHandlerTable                 uint64
	SEHandlerCount                 uint64
	GuardCFCheckFunctionPointer    uint64
	GuardCFDispatchFunctionPointer uint64
	GuardCFFunctionTable           uint64
	GuardCFFunctionCount           uint64
	GuardFlags                     uint32
	CodeIntegrity                  ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable uint64
	GuardAddressTakenIatEntryCount uint64
	GuardLongJumpTargetTable       uint64
	GuardLongJumpTargetCount       uint64
}

ImageLoadConfigDirectory64v5 for binaries compiled since Windows 10 build 14286 (or maybe earlier).

type ImageLoadConfigDirectory64v6

type ImageLoadConfigDirectory64v6 struct {
	Size                           uint32
	TimeDateStamp                  uint32
	MajorVersion                   uint16
	MinorVersion                   uint16
	GlobalFlagsClear               uint32
	GlobalFlagsSet                 uint32
	CriticalSectionDefaultTimeout  uint32
	DeCommitFreeBlockThreshold     uint64
	DeCommitTotalFreeThreshold     uint64
	LockPrefixTable                uint64
	MaximumAllocationSize          uint64
	VirtualMemoryThreshold         uint64
	ProcessAffinityMask            uint64
	ProcessHeapFlags               uint32
	CSDVersion                     uint16
	DependentLoadFlags             uint16
	EditList                       uint64
	SecurityCookie                 uint64
	SEHandlerTable                 uint64
	SEHandlerCount                 uint64
	GuardCFCheckFunctionPointer    uint64
	GuardCFDispatchFunctionPointer uint64
	GuardCFFunctionTable           uint64
	GuardCFFunctionCount           uint64
	GuardFlags                     uint32
	CodeIntegrity                  ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable uint64
	GuardAddressTakenIatEntryCount uint64
	GuardLongJumpTargetTable       uint64
	GuardLongJumpTargetCount       uint64
	DynamicValueRelocTable         uint64
	HybridMetadataPointer          uint64
}

ImageLoadConfigDirectory64v6 for binaries compiled since Windows 10 build 14393 (or maybe earlier).

type ImageLoadConfigDirectory64v7

type ImageLoadConfigDirectory64v7 struct {
	Size                                 uint32
	TimeDateStamp                        uint32
	MajorVersion                         uint16
	MinorVersion                         uint16
	GlobalFlagsClear                     uint32
	GlobalFlagsSet                       uint32
	CriticalSectionDefaultTimeout        uint32
	DeCommitFreeBlockThreshold           uint64
	DeCommitTotalFreeThreshold           uint64
	LockPrefixTable                      uint64
	MaximumAllocationSize                uint64
	VirtualMemoryThreshold               uint64
	ProcessAffinityMask                  uint64
	ProcessHeapFlags                     uint32
	CSDVersion                           uint16
	DependentLoadFlags                   uint16
	EditList                             uint64
	SecurityCookie                       uint64
	SEHandlerTable                       uint64
	SEHandlerCount                       uint64
	GuardCFCheckFunctionPointer          uint64
	GuardCFDispatchFunctionPointer       uint64
	GuardCFFunctionTable                 uint64
	GuardCFFunctionCount                 uint64
	GuardFlags                           uint32
	CodeIntegrity                        ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable       uint64
	GuardAddressTakenIatEntryCount       uint64
	GuardLongJumpTargetTable             uint64
	GuardLongJumpTargetCount             uint64
	DynamicValueRelocTable               uint64
	CHPEMetadataPointer                  uint64
	GuardRFFailureRoutine                uint64
	GuardRFFailureRoutineFunctionPointer uint64
	DynamicValueRelocTableOffset         uint32
	DynamicValueRelocTableSection        uint16
	Reserved2                            uint16
}

ImageLoadConfigDirectory64v7 for binaries compiled since Windows 10 build 14901 (or maybe earlier).

type ImageLoadConfigDirectory64v8

type ImageLoadConfigDirectory64v8 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint64
	DeCommitTotalFreeThreshold               uint64
	LockPrefixTable                          uint64
	MaximumAllocationSize                    uint64
	VirtualMemoryThreshold                   uint64
	ProcessAffinityMask                      uint64
	ProcessHeapFlags                         uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint64
	SecurityCookie                           uint64
	SEHandlerTable                           uint64
	SEHandlerCount                           uint64
	GuardCFCheckFunctionPointer              uint64
	GuardCFDispatchFunctionPointer           uint64
	GuardCFFunctionTable                     uint64
	GuardCFFunctionCount                     uint64
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint64
	GuardAddressTakenIatEntryCount           uint64
	GuardLongJumpTargetTable                 uint64
	GuardLongJumpTargetCount                 uint64
	DynamicValueRelocTable                   uint64
	CHPEMetadataPointer                      uint64
	GuardRFFailureRoutine                    uint64
	GuardRFFailureRoutineFunctionPointer     uint64
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint64
	HotPatchTableOffset                      uint32
}

ImageLoadConfigDirectory64v8 for binaries compiled since Windows 10 build 15002 (or maybe earlier). #pragma pack(4) available here.

type ImageLoadConfigDirectory64v9

type ImageLoadConfigDirectory64v9 struct {
	Size                                     uint32
	TimeDateStamp                            uint32
	MajorVersion                             uint16
	MinorVersion                             uint16
	GlobalFlagsClear                         uint32
	GlobalFlagsSet                           uint32
	CriticalSectionDefaultTimeout            uint32
	DeCommitFreeBlockThreshold               uint64
	DeCommitTotalFreeThreshold               uint64
	LockPrefixTable                          uint64
	MaximumAllocationSize                    uint64
	VirtualMemoryThreshold                   uint64
	ProcessAffinityMask                      uint64
	ProcessHeapFlags                         uint32
	CSDVersion                               uint16
	DependentLoadFlags                       uint16
	EditList                                 uint64
	SecurityCookie                           uint64
	SEHandlerTable                           uint64
	SEHandlerCount                           uint64
	GuardCFCheckFunctionPointer              uint64
	GuardCFDispatchFunctionPointer           uint64
	GuardCFFunctionTable                     uint64
	GuardCFFunctionCount                     uint64
	GuardFlags                               uint32
	CodeIntegrity                            ImageLoadConfigCodeIntegrity
	GuardAddressTakenIatEntryTable           uint64
	GuardAddressTakenIatEntryCount           uint64
	GuardLongJumpTargetTable                 uint64
	GuardLongJumpTargetCount                 uint64
	DynamicValueRelocTable                   uint64
	CHPEMetadataPointer                      uint64
	GuardRFFailureRoutine                    uint64
	GuardRFFailureRoutineFunctionPointer     uint64
	DynamicValueRelocTableOffset             uint32
	DynamicValueRelocTableSection            uint16
	Reserved2                                uint16
	GuardRFVerifyStackPointerFunctionPointer uint64
	HotPatchTableOffset                      uint32
	Reserved3                                uint32
	EnclaveConfigurationPointer              uint64
}

ImageLoadConfigDirectory64v9 for binaries compiled since Windows 10 build 15002 (or maybe earlier). #pragma pack(4) was taken.

type ImageNtHeader

type ImageNtHeader struct {
	// Signature is a DWORD containing the value 50h, 45h, 00h, 00h.
	Signature uint32

	// IMAGE_NT_HEADERS privdes a standard COFF header. It is located
	// immediately after the PE signature. The COFF header provides the most
	// general characteristics of a PE/COFF file, applicable to both object and
	// executable files. It is represented with IMAGE_FILE_HEADER structure.
	FileHeader ImageFileHeader

	// OptionalHeader is of type *OptionalHeader32 or *OptionalHeader64.
	OptionalHeader interface{}
}

ImageNtHeader represents the PE header and is the general term for a structure named IMAGE_NT_HEADERS.

type ImageOptionalHeader32

type ImageOptionalHeader32 struct {

	// The unsigned integer that identifies the state of the image file.
	// The most common number is 0x10B, which identifies it as a normal
	// executable file. 0x107 identifies it as a ROM image, and 0x20B identifies
	// it as a PE32+ executable.
	Magic uint16

	// Linker major version number. The VC++ linker sets this field to current
	// version of Visual Studio.
	MajorLinkerVersion uint8

	// The linker minor version number.
	MinorLinkerVersion uint8

	// The size of the code (text) section, or the sum of all code sections
	// if there are multiple sections.
	SizeOfCode uint32

	// The size of the initialized data section (held in the field SizeOfRawData
	// of the respective section header), or the sum of all such sections if
	// there are multiple data sections.
	SizeOfInitializedData uint32

	// The size of the uninitialized data section (BSS), or the sum of all
	// such sections if there are multiple BSS sections. This data is not part
	// of the disk file and does not have specific values, but the OS loader
	// commits memory space for this data when the file is loaded.
	SizeOfUninitializedData uint32

	// The address of the entry point relative to the image base when the
	// executable file is loaded into memory. For program images, this is the
	// starting address. For device drivers, this is the address of the
	// initialization function. An entry point is optional for DLLs. When no
	// entry point is present, this field must be zero. For managed PE files,
	// this value always points to the common language runtime invocation stub.
	AddressOfEntryPoint uint32

	// The address that is relative to the image base of the beginning-of-code
	// section when it is loaded into memory.
	BaseOfCode uint32

	// The address that is relative to the image base of the beginning-of-data
	// section when it is loaded into memory.This entry doesn’t exist in the
	// 64-bit Optional header.
	BaseOfData uint32

	// The preferred address of the first byte of image when loaded into memory;
	// must be a multiple of 64 K. The default for DLLs is 0x10000000. The
	// default for Windows CE EXEs is 0x00010000. The default for Windows NT,
	// Windows 2000, Windows XP, Windows 95, Windows 98, and Windows Me is
	// 0x00400000.
	ImageBase uint32

	// The alignment (in bytes) of sections when they are loaded into memory.
	// It must be greater than or equal to FileAlignment. The default is the
	// page size for the architecture.
	SectionAlignment uint32

	// The alignment factor (in bytes) that is used to align the raw data of
	// sections in the image file. The value should be a power of 2 between 512
	// and 64 K, inclusive. The default is 512. If the SectionAlignment is less
	// than the architecture's page size, then FileAlignment must match
	// SectionAlignment.
	FileAlignment uint32

	// The major version number of the required operating system.
	MajorOperatingSystemVersion uint16

	// The minor version number of the required operating system.
	MinorOperatingSystemVersion uint16

	// The major version number of the image.
	MajorImageVersion uint16

	// The minor version number of the image.
	MinorImageVersion uint16

	// The major version number of the subsystem.
	MajorSubsystemVersion uint16

	// The minor version number of the subsystem.
	MinorSubsystemVersion uint16

	// Reserved, must be zero.
	Win32VersionValue uint32

	// The size (in bytes) of the image, including all headers, as the image
	// is loaded in memory. It must be a multiple of SectionAlignment.
	SizeOfImage uint32

	// The combined size of an MS-DOS stub, PE header, and section headers
	// rounded up to a multiple of FileAlignment.
	SizeOfHeaders uint32

	// The image file checksum. The algorithm for computing the checksum is
	// incorporated into IMAGHELP.DLL. The following are checked for validation
	// at load time: all drivers, any DLL loaded at boot time, and any DLL
	// that is loaded into a critical Windows process.
	CheckSum uint32

	// The subsystem that is required to run this image.
	Subsystem uint16

	// For more information, see DLL Characteristics later in this specification.
	DllCharacteristics uint16

	// Size of virtual memory to reserve for the initial thread’s stack. Only
	// the SizeOfStackCommit field is committed; the rest is available in
	// one-page increments. The default is 1MB for 32-bit images and 4MB for
	// 64-bit images.
	SizeOfStackReserve uint32

	// Size of virtual memory initially committed for the initial thread’s
	// stack. The default is one page (4KB) for 32-bit images and 16KB for
	// 64-bit images.
	SizeOfStackCommit uint32

	// size of the local heap space to reserve. Only SizeOfHeapCommit is
	// committed; the rest is made available one page at a time until the
	// reserve size is reached. The default is 1MB for both 32-bit and 64-bit
	// images.
	SizeOfHeapReserve uint32

	// Size of virtual memory initially committed for the process heap. The
	// default is 4KB (one operating system memory page) for 32-bit images and
	// 16KB for 64-bit images.
	SizeOfHeapCommit uint32

	// Reserved, must be zero.
	LoaderFlags uint32

	// Number of entries in the DataDirectory array; at least 16. Although it
	// is theoretically possible to emit more than 16 data directories, all
	// existing managed compilers emit exactly 16 data directories, with the
	// 16th (last) data directory never used (reserved).
	NumberOfRvaAndSizes uint32

	// An array of 16 IMAGE_DATA_DIRECTORY structures.
	DataDirectory [16]DataDirectory
}

ImageOptionalHeader32 represents the PE32 format structure of the optional header. PE32 contains this additional field, which is absent in PE32+.

type ImageOptionalHeader64

type ImageOptionalHeader64 struct {
	// The unsigned integer that identifies the state of the image file.
	// The most common number is 0x10B, which identifies it as a normal
	// executable file. 0x107 identifies it as a ROM image, and 0x20B identifies
	// it as a PE32+ executable.
	Magic uint16

	// Linker major version number. The VC++ linker sets this field to current
	// version of Visual Studio.
	MajorLinkerVersion uint8

	// The linker minor version number.
	MinorLinkerVersion uint8

	// The size of the code (text) section, or the sum of all code sections
	// if there are multiple sections.
	SizeOfCode uint32

	// The size of the initialized data section (held in the field SizeOfRawData
	// of the respective section header), or the sum of all such sections if
	// there are multiple data sections.
	SizeOfInitializedData uint32

	// The size of the uninitialized data section (BSS), or the sum of all
	// such sections if there are multiple BSS sections. This data is not part
	// of the disk file and does not have specific values, but the OS loader
	// commits memory space for this data when the file is loaded.
	SizeOfUninitializedData uint32

	// The address of the entry point relative to the image base when the
	// executable file is loaded into memory. For program images, this is the
	// starting address. For device drivers, this is the address of the
	// initialization function. An entry point is optional for DLLs. When no
	// entry point is present, this field must be zero. For managed PE files,
	// this value always points to the common language runtime invocation stub.
	AddressOfEntryPoint uint32

	// The address that is relative to the image base of the beginning-of-code
	// section when it is loaded into memory.
	BaseOfCode uint32

	// In PE+, ImageBase is 8 bytes size.
	ImageBase uint64

	// The alignment (in bytes) of sections when they are loaded into memory.
	// It must be greater than or equal to FileAlignment. The default is the
	// page size for the architecture.
	SectionAlignment uint32

	// The alignment factor (in bytes) that is used to align the raw data of
	// sections in the image file. The value should be a power of 2 between 512
	// and 64 K, inclusive. The default is 512. If the SectionAlignment is less
	// than the architecture's page size, then FileAlignment must match SectionAlignment.
	FileAlignment uint32

	// The major version number of the required operating system.
	MajorOperatingSystemVersion uint16

	// The minor version number of the required operating system.
	MinorOperatingSystemVersion uint16

	// The major version number of the image.
	MajorImageVersion uint16

	// The minor version number of the image.
	MinorImageVersion uint16

	// The major version number of the subsystem.
	MajorSubsystemVersion uint16

	// The minor version number of the subsystem.
	MinorSubsystemVersion uint16

	// Reserved, must be zero.
	Win32VersionValue uint32

	// The size (in bytes) of the image, including all headers, as the image
	// is loaded in memory. It must be a multiple of SectionAlignment.
	SizeOfImage uint32

	// The combined size of an MS-DOS stub, PE header, and section headers
	// rounded up to a multiple of FileAlignment.
	SizeOfHeaders uint32

	// The image file checksum. The algorithm for computing the checksum is
	// incorporated into IMAGHELP.DLL. The following are checked for validation
	// at load time: all drivers, any DLL loaded at boot time, and any DLL
	// that is loaded into a critical Windows process.
	CheckSum uint32

	// The subsystem that is required to run this image.
	Subsystem uint16

	// For more information, see DLL Characteristics later in this specification.
	DllCharacteristics uint16

	// Size of virtual memory to reserve for the initial thread’s stack. Only
	// the SizeOfStackCommit field is committed; the rest is available in
	// one-page increments. The default is 1MB for 32-bit images and 4MB for
	// 64-bit images.
	SizeOfStackReserve uint64

	// Size of virtual memory initially committed for the initial thread’s
	// stack. The default is one page (4KB) for 32-bit images and 16KB for
	// 64-bit images.
	SizeOfStackCommit uint64

	// size of the local heap space to reserve. Only SizeOfHeapCommit is
	// committed; the rest is made available one page at a time until the
	// reserve size is reached. The default is 1MB for both 32-bit and 64-bit
	// images.
	SizeOfHeapReserve uint64

	// Size of virtual memory initially committed for the process heap. The
	// default is 4KB (one operating system memory page) for 32-bit images and
	// 16KB for 64-bit images.
	SizeOfHeapCommit uint64

	// Reserved, must be zero.
	LoaderFlags uint32

	// Number of entries in the DataDirectory array; at least 16. Although it
	// is theoretically possible to emit more than 16 data directories, all
	// existing managed compilers emit exactly 16 data directories, with the
	// 16th (last) data directory never used (reserved).
	NumberOfRvaAndSizes uint32

	// An array of 16 IMAGE_DATA_DIRECTORY structures.
	DataDirectory [16]DataDirectory
}

ImageOptionalHeader64 represents the PE32+ format structure of the optional header.

type ImagePGOItem

type ImagePGOItem struct {
	Rva  uint32
	Size uint32
	Name string
}

type ImagePrologueDynamicRelocationHeader

type ImagePrologueDynamicRelocationHeader struct {
	PrologueByteCount uint8
}

type ImageResourceDataEntry

type ImageResourceDataEntry struct {
	// The address of a unit of resource data in the Resource Data area.
	OffsetToData uint32

	// The size, in bytes, of the resource data that is pointed to by the Data
	// RVA field.
	Size uint32

	// The code page that is used to decode code point values within the
	// resource data. Typically, the code page would be the Unicode code page.
	CodePage uint32

	// Reserved, must be 0.
	Reserved uint32
}

ImageResourceDataEntry Each Resource Data entry describes an actual unit of raw data in the Resource Data area.

type ImageResourceDirectory

type ImageResourceDirectory struct {
	// Resource flags. This field is reserved for future use. It is currently
	// set to zero.
	Characteristics uint32

	// The time that the resource data was created by the resource compiler.
	TimeDateStamp uint32

	// The major version number, set by the user.
	MajorVersion uint16

	// The minor version number, set by the user.
	MinorVersion uint16

	// The number of directory entries immediately following the table that use
	// strings to identify Type, Name, or Language entries (depending on the
	// level of the table).
	NumberOfNamedEntries uint16

	// The number of directory entries immediately following the Name entries
	// that use numeric IDs for Type, Name, or Language entries.
	NumberOfIDEntries uint16
}

ImageResourceDirectory represents the IMAGE_RESOURCE_DIRECTORY. This data structure should be considered the heading of a table because the table actually consists of directory entries.

type ImageResourceDirectoryEntry

type ImageResourceDirectoryEntry struct {
	// is used to identify either a type of resource, a resource name, or a
	// resource's language ID.
	Name uint32

	//is always used to point to a sibling in the tree, either a directory node
	// or a leaf node.
	OffsetToData uint32
}

ImageResourceDirectoryEntry represents an entry in the resource directory entries.

type ImageRuntimeFunctionEntry

type ImageRuntimeFunctionEntry struct {
	// The address of the start of the function.
	BeginAddress uint32

	// The address of the end of the function.
	EndAddress uint32

	// The unwind data info ructure is used to record the effects a function has
	// on the stack pointer, and where the nonvolatile registers are saved on
	// the stack.
	UnwindInfoAddress uint32
}

ImageRuntimeFunctionEntry represents an entry in the function table on 64-bit Windows. Table-based exception handling reques a table entry for all functions that allocate stack space or call another function (for example, nonleaf functions).

type ImageSectionHeader

type ImageSectionHeader struct {

	//  An 8-byte, null-padded UTF-8 encoded string. If the string is exactly 8
	// characters long, there is no terminating null. For longer names, this
	// field contains a slash (/) that is followed by an ASCII representation of
	// a decimal number that is an offset into the string table. Executable
	// images do not use a string table and do not support section names longer
	// than 8 characters. Long names in object files are truncated if they are
	// emitted to an executable file.
	Name [8]uint8

	// The total size of the section when loaded into memory. If this value is
	// greater than SizeOfRawData, the section is zero-padded. This field is
	// valid only for executable images and should be set to zero for object files.
	VirtualSize uint32

	// For executable images, the address of the first byte of the section
	// relative to the image base when the section is loaded into memory.
	// For object files, this field is the address of the first byte before
	// relocation is applied; for simplicity, compilers should set this to zero.
	// Otherwise, it is an arbitrary value that is subtracted from offsets during
	// relocation.
	VirtualAddress uint32

	// The size of the section (for object files) or the size of the initialized
	// data on disk (for image files). For executable images, this must be a
	// multiple of FileAlignment from the optional header. If this is less than
	// VirtualSize, the remainder of the section is zero-filled. Because the
	// SizeOfRawData field is rounded but the VirtualSize field is not, it is
	// possible for SizeOfRawData to be greater than VirtualSize as well. When
	// a section contains only uninitialized data, this field should be zero.
	SizeOfRawData uint32

	// The file pointer to the first page of the section within the COFF file.
	// For executable images, this must be a multiple of FileAlignment from the
	// optional header. For object files, the value should be aligned on a
	// 4-byte boundary for best performance. When a section contains only
	// uninitialized data, this field should be zero.
	PointerToRawData uint32

	// The file pointer to the beginning of relocation entries for the section.
	// This is set to zero for executable images or if there are no relocations.
	PointerToRelocations uint32

	// The file pointer to the beginning of line-number entries for the section.
	// This is set to zero if there are no COFF line numbers. This value should
	// be zero for an image because COFF debugging information is deprecated.
	PointerToLineNumbers uint32

	// The number of relocation entries for the section.
	// This is set to zero for executable images.
	NumberOfRelocations uint16

	// The number of line-number entries for the section. This value should be
	// zero for an image because COFF debugging information is deprecated.
	NumberOfLineNumbers uint16

	// The flags that describe the characteristics of the section.
	Characteristics uint32
}

ImageSectionHeader is part of the section table , in fact section table is an array of Image Section Header each contains information about one section of the whole file such as attribute,virtual offset. the array size is the number of sections in the file. Binary Spec : each struct is 40 byte and there is no padding .

type ImageTLSDirectory32

type ImageTLSDirectory32 struct {

	// The starting address of the TLS template. The template is a block of data
	// that is used to initialize TLS data.
	StartAddressOfRawData uint32

	// The address of the last byte of the TLS, except for the zero fill.
	// As with the Raw Data Start VA field, this is a VA, not an RVA.
	EndAddressOfRawData uint32

	// The location to receive the TLS index, which the loader assigns. This
	// location is in an ordinary data section, so it can be given a symbolic
	// name that is accessible to the program.
	AddressOfIndex uint32

	// The pointer to an array of TLS callback functions. The array is
	// null-terminated, so if no callback function is supported, this field
	// points to 4 bytes set to zero.
	AddressOfCallBacks uint32

	// The size in bytes of the template, beyond the initialized data delimited
	// by the Raw Data Start VA and Raw Data End VA fields. The total template
	// size should be the same as the total size of TLS data in the image file.
	// The zero fill is the amount of data that comes after the initialized
	// nonzero data.
	SizeOfZeroFill uint32

	// The four bits [23:20] describe alignment info. Possible values are those
	// defined as IMAGE_SCN_ALIGN_*, which are also used to describe alignment
	// of section in object files. The other 28 bits are reserved for future use.
	Characteristics uint32
}

ImageTLSDirectory32 represents the IMAGE_TLS_DIRECTORY32 structure. It Points to the Thread Local Storage initialization section.

type ImageTLSDirectory64

type ImageTLSDirectory64 struct {
	// The starting address of the TLS template. The template is a block of data
	// that is used to initialize TLS data.
	StartAddressOfRawData uint64

	// The address of the last byte of the TLS, except for the zero fill. As
	// with the Raw Data Start VA field, this is a VA, not an RVA.
	EndAddressOfRawData uint64

	// The location to receive the TLS index, which the loader assigns. This
	// location is in an ordinary data section, so it can be given a symbolic
	// name that is accessible to the program.
	AddressOfIndex uint64

	// The pointer to an array of TLS callback functions. The array is
	// null-terminated, so if no callback function is supported, this field
	// points to 4 bytes set to zero.
	AddressOfCallBacks uint64

	// The size in bytes of the template, beyond the initialized data delimited
	// by the Raw Data Start VA and Raw Data End VA fields. The total template
	// size should be the same as the total size of TLS data in the image file.
	// The zero fill is the amount of data that comes after the initialized
	// nonzero data.
	SizeOfZeroFill uint32

	// The four bits [23:20] describe alignment info. Possible values are those
	// defined as IMAGE_SCN_ALIGN_*, which are also used to describe alignment
	// of section in object files. The other 28 bits are reserved for future use.
	Characteristics uint32
}

ImageTLSDirectory64 represents the IMAGE_TLS_DIRECTORY64 structure. It Points to the Thread Local Storage initialization section.

type ImageThunkData32

type ImageThunkData32 struct {
	AddressOfData uint32
}

ImageThunkData32 corresponds to one imported function from the executable. The entries are an array of 32-bit numbers for PE32 or an array of 64-bit numbers for PE32+. The ends of both arrays are indicated by an IMAGE_THUNK_DATA element with a value of zero. The IMAGE_THUNK_DATA union is a DWORD with these interpretations: DWORD Function; // Memory address of the imported function DWORD Ordinal; // Ordinal value of imported API DWORD AddressOfData; // RVA to an IMAGE_IMPORT_BY_NAME with the imported API name DWORD ForwarderString;// RVA to a forwarder string

type ImageThunkData64

type ImageThunkData64 struct {
	AddressOfData uint64
}

ImageThunkData64 is the PE32+ version of IMAGE_THUNK_DATA.

type ImageVolatileMetadata

type ImageVolatileMetadata struct {
	Size                       uint32
	Version                    uint32
	VolatileAccessTable        uint32
	VolatileAccessTableSize    uint32
	VolatileInfoRangeTable     uint32
	VolatileInfoRangeTableSize uint32
}

type Import

type Import struct {
	Offset     uint32
	Name       string
	Functions  []*ImportFunction
	Descriptor ImageImportDescriptor
}

Import represents an empty entry in the emport table.

type ImportFunction

type ImportFunction struct {
	// An ASCII string that contains the name to import. This is the string that
	// must be matched to the public name in the DLL. This string is case
	// sensitive and terminated by a null byte.
	Name string

	// An index into the export name pointer table. A match is attempted first
	// with this value. If it fails, a binary search is performed on the DLL's
	// export name pointer table.
	Hint uint16

	// If this is true, import by ordinal. Otherwise, import by name.
	ByOrdinal bool

	// A 16-bit ordinal number. This field is used only if the Ordinal/Name Flag
	// bit field is 1 (import by ordinal). Bits 30-15 or 62-15 must be 0.
	Ordinal uint32

	// Name Thunk Value (OFT)
	OriginalThunkValue uint64

	// Address Thunk Value (FT)
	ThunkValue uint64

	// Address Thunk RVA.
	ThunkRVA uint32

	// Name Thunk RVA.
	OriginalThunkRVA uint32
}

ImportFunction represents an imported function in the import table.

type LoadConfig

type LoadConfig struct {
	LoadCfgStruct    interface{}       `json:",omitempty"`
	SEH              []uint32          `json:",omitempty"`
	GFIDS            []CFGFunction     `json:",omitempty"`
	CFGIAT           []CFGIATEntry     `json:",omitempty"`
	CFGLongJump      []uint32          `json:",omitempty"`
	CHPE             *HybridPE         `json:",omitempty"`
	DVRT             *DVRT             `json:",omitempty"`
	Enclave          *Enclave          `json:",omitempty"`
	VolatileMetadata *VolatileMetadata `json:",omitempty"`
}

type MetadataHeader

type MetadataHeader struct {

	// The storage signature, which must be 4-byte aligned:
	// ”Magic” signature for physical metadata, currently 0x424A5342, or, read
	// as characters, BSJB—the initials of four “founding fathers” Brian Harry,
	// Susa Radke-Sproull, Jason Zander, and Bill Evans, who started the
	// runtime development in 1998.
	Signature uint32

	// Major version.
	MajorVersion uint16

	// Minor version.
	MinorVersion uint16

	// Reserved; set to 0.
	ExtraData uint32

	// Length of the version string.
	VersionString uint32

	// Version string.
	Version string

	// Reserved; set to 0.
	Flags uint8

	// Number of streams.
	Streams uint16
}

MetadataHeader consists of a storage signature and a storage header.

type MetadataStreamHeader

type MetadataStreamHeader struct {
	// Offset in the file for this stream.
	Offset uint32

	// Size of the stream in bytes.
	Size uint32

	// Name of the stream; a zero-terminated ASCII string no longer than 31
	// characters (plus zero terminator). The name might be shorter, in which
	// case the size of the stream header is correspondingly reduced, padded to
	// the 4-byte boundary.
	Name string
}

MetadataStreamHeader represents a Metadata Stream Header Structure.

type MetadataTable

type MetadataTable struct {
	// The name of the table.
	Name string

	// Number of columns in the table
	CountCols uint8

	// Size of a record in the table/
	SizeRecord uint16

	// Every table has a different layout, defined in the ECMA-335 spec.
	// Content asbtract the type each table is pointing to.
	Content interface{}
}

MetadataTable represents the content of a particular table in the metadata. The metadata schema defines 45 tables.

type MetadataTableStreamHeader

type MetadataTableStreamHeader struct {
	// Reserved; set to 0.
	Reserved uint32

	// Major version of the table schema (1 for v1.0 and v1.1; 2 for v2.0 or later).
	MajorVersion uint8

	// Minor version of the table schema (0 for all versions).
	MinorVersion uint8

	// Binary flags indicate the offset sizes to be used within the heaps.
	// 4-byte unsigned integer offset is indicated by:
	// - 0x01 for a string heap, 0x02 for a GUID heap, and 0x04 for a blob heap.
	// If a flag is not set, the respective heap offset is a 2-byte unsigned integer.
	// A #- stream can also have special flags set:
	// - flag 0x20, indicating that the stream contains only changes made
	// during an edit-and-continue session, and;
	// - flag 0x80, indicating that the  metadata might contain items marked as
	// deleted.
	Heaps uint8

	// it width of the maximal record index to all tables of the metadata;
	// calculated at run time (during the metadata stream initialization).
	Rid uint8

	// Bit vector of present tables, each bit representing one table (1 if
	// present).
	MaskValid uint64

	// Bit vector of sorted tables, each bit representing a respective table (1
	// if sorted)
	Sorted uint64
}

MetadataTableStreamHeader represents the Metadata Table Stream Header Structure.

type ModuleTableRow

type ModuleTableRow struct {
	// Used only at run time, in edit-and-continue mode.
	Generation uint16

	// (offset in the #Strings stream) The module name, which is the same as
	// the name of the executable file with its extension but without a path.
	// The length should not exceed 512 bytes in UTF-8 encoding, counting the
	// zero terminator.
	Name uint32

	// (offset in the #GUID stream) A globally unique identifier, assigned to the module as it is generated.
	Mvid uint32

	// (offset in the #GUID stream): Used only at run time, in
	// edit-and-continue mode.
	EncID uint32

	// (offset in the #GUID stream): Used only at run time, in edit-and-continue mode.
	EncBaseID uint32
}

ModuleTableRow represents the `Module` metadata table contains a single record that provides the identification of the current module. The column structure of the table is as follows:

type Options

type Options struct {

	// Parse only the header, do not parse data directories, by default (false).
	Fast bool

	// Includes section entropy.
	SectionEntropy bool
}

Options for Parsing

type POGO

type POGO struct {
	Signature uint32 // _IMAGE_POGO_INFO
	Entries   []ImagePGOItem
}

POGO structure that information related to the Profile Guided Optimization.

type REPRO

type REPRO struct {
	Size uint32
	Hash []byte
}

type RangeTableEntry

type RangeTableEntry struct {
	Rva  uint32
	Size uint32
}

type RelocBlock

type RelocBlock struct {
	ImgBaseReloc ImageBaseRelocation
	TypeOffsets  []TypeOffset
}

type RelocEntry

type RelocEntry struct {
	// Could be ImageDynamicRelocation32{} or ImageDynamicRelocation64{}
	ImgDynReloc interface{}
	RelocBlocks []RelocBlock
}

type Relocation

type Relocation struct {
	// Points to the ImageBaseRelocation structure.
	Data ImageBaseRelocation

	// holds the list of entries for each chunk.
	Entries []ImageBaseRelocationEntry
}

Relocation represents the relocation table which holds the data that needs to be relocated.

type ResourceDataEntry

type ResourceDataEntry struct {

	// IMAGE_RESOURCE_DATA_ENTRY structure.
	Struct ImageResourceDataEntry

	// Primary language ID
	Lang    uint32
	Sublang uint32 // Sublanguage ID
}

ResourceDataEntry represents a resource data entry.

type ResourceDirectory

type ResourceDirectory struct {
	// IMAGE_RESOURCE_DIRECTORY structure
	Struct ImageResourceDirectory

	// list of entries
	Entries []ResourceDirectoryEntry
}

ResourceDirectory represents resource directory information.

type ResourceDirectoryEntry

type ResourceDirectoryEntry struct {
	// IMAGE_RESOURCE_DIRECTORY_ENTRY structure.
	Struct ImageResourceDirectoryEntry

	// If the resource is identified by name this attribute will contain the
	// name string. Empty string otherwise. If identified by id, the id is
	// available at .Id field.
	Name string

	// The resource identifier.
	ID uint32

	// If this entry has a lower level directory this attribute will point to
	// the ResourceDirData instance representing it.
	Directory ResourceDirectory

	// If this entry has no further lower directories and points to the actual
	// resource data, this attribute will reference the corresponding
	// ResourceDataEntry instance.
	Data ResourceDataEntry
}

ResourceDirectoryEntry represents a resource directory entry.

type RichHeader

type RichHeader struct {
	XorKey     uint32
	CompIDs    []CompID
	DansOffset int
	Raw        []byte
}

RichHeader is a structure that is written right after the MZ DOS header. It consists of pairs of 4-byte integers. And it is also encrypted using a simple XOR operation using the checksum as the key. The data between the magic values encodes the ‘bill of materials’ that were collected by the linker to produce the binary.

type Section

type Section struct {
	Header  ImageSectionHeader
	Entropy float64 `json:",omitempty"`
}

Section represents a PE section header, plus additionnal data like entropy.

func (*Section) CalculateEntropy

func (section *Section) CalculateEntropy(pe *File) float64

CalculateEntropy calculates section entropy.

func (*Section) Contains

func (section *Section) Contains(rva uint32, pe *File) bool

Contains checks whether the section contains a given RVA.

func (*Section) Data

func (section *Section) Data(start, length uint32, pe *File) []byte

Data returns a data chunk from a section.

func (*Section) NameString

func (section *Section) NameString() string

NameString returns string representation of a ImageSectionHeader.Name field.

func (*Section) NextHeaderAddr

func (section *Section) NextHeaderAddr(pe *File) uint32

NextHeaderAddr returns the VirtualAddress of the next section.

type TLSDirectory

type TLSDirectory struct {

	// of type *IMAGE_TLS_DIRECTORY32 or *IMAGE_TLS_DIRECTORY64 structure.
	Struct interface{}

	// of type uint32 or uint64.
	Callbacks interface{}
}

TLSDirectory represents tls directory information with callback entries.

type ThunkData32

type ThunkData32 struct {
	ImageThunkData ImageThunkData32
	Offset         uint32
}

type ThunkData64

type ThunkData64 struct {
	ImageThunkData ImageThunkData64
	Offset         uint32
}

type TypeOffset

type TypeOffset struct {
	Value               uint16
	Type                uint8
	DynamicSymbolOffset uint16
}

type UnwindCode

type UnwindCode struct {
	// Offset (from the beginng of the prolog) of the end of the instruction
	// that performs is operation, plus 1 (that is, the offset of the start of
	// the next instruction).
	CodeOffset uint8

	// The unwind operation code
	UnwindOp uint8

	// Operation info
	OpInfo uint8

	// Allocation size
	Operand     string
	FrameOffset uint16
}

UnwindCode is used to record the sequence of operations in the prolog that affect the nonvolatile registers and RSP. Each code item has this format:

 typedef union _UNWIND_CODE {
    struct {
        UCHAR CodeOffset;
        UCHAR UnwindOp : 4;
        UCHAR OpInfo : 4;
    } DUMMYUNIONNAME;

    struct {
        UCHAR OffsetLow;
        UCHAR UnwindOp : 4;
        UCHAR OffsetHigh : 4;
    } EpilogueCode;

    USHORT FrameOffset;
} UNWIND_CODE, *PUNWIND_CODE;

type UnwindInfo

type UnwindInfo struct {
	// (3 bits) Version number of the unwind data, currently 1 and 2.
	Version uint8

	// (5 bits) Three flags are currently defined above.
	Flags uint8

	// Length of the function prolog in bytes.
	SizeOfProlog uint8

	// The number of slots in the unwind codes array. Some unwind codes,
	// for example, UWOP_SAVE_NONVOL, require more than one slot in the array.
	CountOfCodes uint8

	// If nonzero, then the function uses a frame pointer (FP), and this field
	// is the number of the nonvolatile register used as the frame pointer,
	// using the same encoding for the operation info field of UNWIND_CODE nodes.
	FrameRegister uint8

	// If the frame register field  nonzero, this field is the scaled offset
	// from RSP that is applied to the FP register when it's established. The
	// actual FP register is set to RSP + 16 * this number, allowing offsets
	// from 0 to 240. This offset permits pointing the FP register into the
	// middle of the local stack allocation for dynamic stack frames, allowing
	// better code density through shorter instructions. (That is, more
	// instructions can use the 8-bit signed offset form.)
	FrameOffset uint8

	// An array of items that explains the effect of the prolog on the
	// nonvolatile registers and RSP. See the section on UNWIND_CODE for the
	// meanings of individual items. For alignment purposes, this array always
	// has an even number of entries, and the final entry is potentially
	// unused. In that case, the array is one longer than indicated by the
	// count of unwind codes field.
	UnwindCodes []UnwindCode

	// Address of exception handler.
	ExceptionHandler uint32

	// If flag UNW_FLAG_CHAININFO is set, then the UNWIND_INFO structure ends
	// with three UWORDs. These UWORDs represent the RUNTIME_FUNCTION
	// information for the function of the chained unwind.
	FunctionEntry ImageRuntimeFunctionEntry
}

UnwindInfo represents the _UNWIND_INFO structure. It is used to record the effects a function has on the stack pointer, and where the nonvolatile registers are saved on the stack.

type VCFeature

type VCFeature struct {
	PreVC11 uint32 `json:"Pre VC 11"`
	CCpp    uint32 `json:"C/C++"`
	Gs      uint32 `json:"/GS"`
	Sdl     uint32 `json:"/sdl"`
	GuardN  uint32
}

type VolatileMetadata

type VolatileMetadata struct {
	Struct         ImageVolatileMetadata
	AccessRVATable []uint32
	InfoRangeTable []RangeTableEntry
}

type WinCertificate

type WinCertificate struct {
	// Specifies the length, in bytes, of the signature.
	Length uint32

	// Specifies the certificate revision.
	Revision uint16

	// Specifies the type of certificate.
	CertificateType uint16
}

WinCertificate encapsulates a signature used in verifying executable files.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL