pe

package
v0.0.0-...-26db732 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: BSD-3-Clause Imports: 10 Imported by: 51

Documentation

Overview

Package pe implements access to PE (Microsoft Windows Portable Executable) files.

Index

Constants

View Source
const (
	IMAGE_FILE_MACHINE_UNKNOWN   = 0x0
	IMAGE_FILE_MACHINE_AM33      = 0x1d3
	IMAGE_FILE_MACHINE_AMD64     = 0x8664
	IMAGE_FILE_MACHINE_ARM       = 0x1c0
	IMAGE_FILE_MACHINE_ARMNT     = 0x1c4
	IMAGE_FILE_MACHINE_ARM64     = 0xaa64
	IMAGE_FILE_MACHINE_EBC       = 0xebc
	IMAGE_FILE_MACHINE_I386      = 0x14c
	IMAGE_FILE_MACHINE_IA64      = 0x200
	IMAGE_FILE_MACHINE_M32R      = 0x9041
	IMAGE_FILE_MACHINE_MIPS16    = 0x266
	IMAGE_FILE_MACHINE_MIPSFPU   = 0x366
	IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466
	IMAGE_FILE_MACHINE_POWERPC   = 0x1f0
	IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1
	IMAGE_FILE_MACHINE_R4000     = 0x166
	IMAGE_FILE_MACHINE_SH3       = 0x1a2
	IMAGE_FILE_MACHINE_SH3DSP    = 0x1a3
	IMAGE_FILE_MACHINE_SH4       = 0x1a6
	IMAGE_FILE_MACHINE_SH5       = 0x1a8
	IMAGE_FILE_MACHINE_THUMB     = 0x1c2
	IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169
)
View Source
const (
	IMAGE_DIRECTORY_ENTRY_EXPORT         = 0
	IMAGE_DIRECTORY_ENTRY_IMPORT         = 1
	IMAGE_DIRECTORY_ENTRY_RESOURCE       = 2
	IMAGE_DIRECTORY_ENTRY_EXCEPTION      = 3
	IMAGE_DIRECTORY_ENTRY_SECURITY       = 4
	IMAGE_DIRECTORY_ENTRY_BASERELOC      = 5
	IMAGE_DIRECTORY_ENTRY_DEBUG          = 6
	IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   = 7
	IMAGE_DIRECTORY_ENTRY_GLOBALPTR      = 8
	IMAGE_DIRECTORY_ENTRY_TLS            = 9
	IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    = 10
	IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   = 11
	IMAGE_DIRECTORY_ENTRY_IAT            = 12
	IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   = 13
	IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
)

IMAGE_DIRECTORY_ENTRY constants

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

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

	//IMAGE_REL_BASED_HIGHADJ        = 4
	//IMAGE_REL_BASED_MIPS_JMPADDR   = 5
	//IMAGE_REL_BASED_ARM_MOV32      = 5
	//IMAGE_REL_BASED_RISCV_HIGH20   = 5
	//IMAGE_REL_BASED_THUMB_MOV32    = 7
	//IMAGE_REL_BASED_RISCV_LOW12I   = 7
	//IMAGE_REL_BASED_RISCV_LOW12S   = 8
	//IMAGE_REL_BASED_MIPS_JMPADDR16 = 9
	IMAGE_REL_BASED_DIR64 = 10
)
View Source
const (
	IMAGE_SCN_CNT_CODE    = 0x00000020 // Section contains code
	IMAGE_SCN_MEM_EXECUTE = 0x20000000 // Section is executable
	IMAGE_SCN_MEM_READ    = 0x40000000 // Section is readable

	IMAGE_FILE_RELOCS_STRIPPED = 0x0001 // Relocation info stripped from file

	IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100 // Image is NX compatable

	IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040 // DLL can move
)

Section Flags (Characteristics field)

View Source
const CERTIFICATE_TABLE = 4

CERTIFICATE_TABLE is the index of the Certificate Table info in the Data Directory structure in the PE header

View Source
const COFFSymbolSize = 18

Variables

This section is empty.

Functions

This section is empty.

Types

type BlockItem

type BlockItem struct {
	Type   byte   // 4 bits
	Offset uint16 // 12 bits
}

BlockItem - relocation block item

type COFFSymbol

type COFFSymbol struct {
	Name               [8]uint8
	Value              uint32
	SectionNumber      int16
	Type               uint16
	StorageClass       uint8
	NumberOfAuxSymbols uint8
}

COFFSymbol represents single COFF symbol table record.

func (*COFFSymbol) FullName

func (sym *COFFSymbol) FullName(st StringTable) (string, error)

FullName finds real name of symbol sym. Normally name is stored in sym.Name, but if it is longer then 8 characters, it is stored in COFF string table st instead.

type DataDirectory

type DataDirectory struct {
	VirtualAddress uint32
	Size           uint32
}

type DosHeader

type DosHeader struct {
	MZSignature              uint16
	UsedBytesInTheLastPage   uint16
	FileSizeInPages          uint16
	NumberOfRelocationItems  uint16
	HeaderSizeInParagraphs   uint16
	MinimumExtraParagraphs   uint16
	MaximumExtraParagraphs   uint16
	InitialRelativeSS        uint16
	InitialSP                uint16
	CheckSum                 uint16
	InitialIP                uint16
	InitialRelativeCS        uint16
	AddressOfRelocationTable uint16
	OverlayNumber            uint16
	Reserved                 [4]uint16
	OEMid                    uint16
	OEMinfo                  uint16
	Reserved2                [10]uint16
	AddressOfNewExeHeader    uint32
}

type Export

type Export struct {
	Ordinal        uint32
	Name           string
	VirtualAddress uint32
	Forward        string
}

Export - describes a single export entry

type ExportDirectory

type ExportDirectory struct {
	ExportFlags       uint32 // reserved, must be zero
	TimeDateStamp     uint32
	MajorVersion      uint16
	MinorVersion      uint16
	NameRVA           uint32 // pointer to the name of the DLL
	OrdinalBase       uint32
	NumberOfFunctions uint32
	NumberOfNames     uint32 // also Ordinal Table Len
	AddressTableAddr  uint32 // RVA of EAT, relative to image base
	NameTableAddr     uint32 // RVA of export name pointer table, relative to image base
	OrdinalTableAddr  uint32 // address of the ordinal table, relative to iamge base

	DllName string
}

ExportDirectory - data directory definition for exported functions

type File

type File struct {
	DosHeader
	DosExists  bool
	DosStub    [64]byte // TODO(capnspacehook) make slice and correctly parse any DOS stub
	RichHeader []byte
	FileHeader
	OptionalHeader      interface{} // of type *OptionalHeader32 or *OptionalHeader64
	Sections            []*Section
	BaseRelocationTable *[]RelocationTableEntry
	Symbols             []*Symbol    // COFF symbols with auxiliary symbol records removed
	COFFSymbols         []COFFSymbol // all COFF symbols (including auxiliary symbol records)
	StringTable         StringTable
	CertificateTable    []byte

	OptionalHeaderOffset int64 // offset of the start of the Optional Header
	InsertionAddr        uint32
	InsertionBytes       []byte

	Net Net //If a managed executable, Net provides an interface to some of the metadata
	// contains filtered or unexported fields
}

A File represents an open PE file.

func NewFile

func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new pe.File for accessing a PE binary file in an underlying reader.

func NewFileFromMemory

func NewFileFromMemory(r io.ReaderAt) (*File, error)

NewFileFromMemory creates a new pe.File for accessing a PE binary in-memory image in an underlying reader.

func Open

func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a PE binary.

func (*File) Bytes

func (peFile *File) Bytes() ([]byte, error)

func (*File) Close

func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

func (*File) DWARF

func (f *File) DWARF() (*dwarf.Data, error)

func (*File) Exports

func (f *File) Exports() ([]Export, error)

Exports - gets exports

func (*File) IAT

func (f *File) IAT() *DataDirectory

IAT returns the DataDirectory for the IAT

func (*File) ImportDelayDirectoryTable

func (f *File) ImportDelayDirectoryTable() ([]ImgDelayDescr, *Section, *[]byte, error)

ImportDelayDirectoryTable - returns the Import Directory Table, a pointer to the section, and the section raw data

func (*File) ImportDirectoryTable

func (f *File) ImportDirectoryTable() ([]ImportDirectory, *Section, *[]byte, error)

ImportDirectoryTable - returns the Import Directory Table, a pointer to the section, and the section raw data

func (*File) ImportedDelayLibraries

func (f *File) ImportedDelayLibraries() ([]string, error)

ImportedDelayLibraries returns the names of all libraries referred to by the binary f that are added to the delay imports directory. These libraries are not loaded at initialisation, but may be loaded during runtime.

func (*File) ImportedLibraries

func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

func (*File) ImportedSymbols

func (f *File) ImportedSymbols() ([]string, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

func (*File) IsManaged

func (f *File) IsManaged() bool

IsManaged returns true if the loaded PE file references the CLR header (aka is a .net exe)

func (File) NetCLRVersion

func (f File) NetCLRVersion() string

NetCLRVersion returns the CLR version specified by the binary. Returns an empty string if not a net binary. String has had trailing nulls stripped.

func (*File) RVAToFileOffset

func (f *File) RVAToFileOffset(rva uint32) uint32

RVAToFileOffset Converts a Relative offset to the actual offset in the file.

func (*File) Relocate

func (f *File) Relocate(baseAddr uint64, image *[]byte)

Relocate - performs base relocations on this image to the given offset

func (*File) Section

func (f *File) Section(name string) *Section

Section returns the first section with the given name, or nil if no such section exists.

func (*File) WriteFile

func (peFile *File) WriteFile(destFile string) error

type FileHeader

type FileHeader struct {
	Machine              uint16
	NumberOfSections     uint16
	TimeDateStamp        uint32
	PointerToSymbolTable uint32
	NumberOfSymbols      uint32
	SizeOfOptionalHeader uint16
	Characteristics      uint16
}

type FormatError

type FormatError struct {
}

FormatError is unused. The type is retained for compatibility.

func (*FormatError) Error

func (e *FormatError) Error() string

type IMAGE_COR20_HEADER

type IMAGE_COR20_HEADER struct {
	Cb                        uint32
	MajorRuntimeVersion       uint16
	MinorRuntimeVersion       uint16
	MetaDataRVA, MetaDataSize uint32
	Flags                     uint32 //todo: define flags
	EntryPointToken           uint32
	ResourcesRVA, ResourcesSize,
	StrongNameSignatureRVA, StrongNameSignatureSize,
	CodeManagerTableRVA, CodeManagerTableSize,
	VTableFixupsRVA, VTableFixupsSize,
	ExportAddressTableJumpsRVA, ExportAddressTableJumpsSize,
	ManagedNativeHeaderRVA, ManagedNativeHeaderSize uint32
}

type ImgDelayDescr

type ImgDelayDescr struct {
	GrAttrs,
	RVADLLName,
	RVAHmod,
	RVAIAT,
	RVAINT,
	RVABoundIAT,
	RVAUnloadIAT,
	DwTimeStamp uint32

	DllName string
}

ImgDelayDescr entry for delayloaded libraries

type ImportDirectory

type ImportDirectory struct {
	OriginalFirstThunk uint32
	TimeDateStamp      uint32
	ForwarderChain     uint32
	NameRVA            uint32
	FirstThunk         uint32

	DllName string
}

ImportDirectory entry

type Net

type Net struct {
	NetDirectory IMAGE_COR20_HEADER //Net directory information
	MetaData     NetMetaData        //MetaData Header
}

Net provides a public interface for getting at some net info.

type NetMetaData

type NetMetaData struct {
	Signature       [4]byte //should be 0x424a4542
	MajorVersion    uint16
	MinorVersion    uint16
	Reserved        uint32
	VersionLength   uint32
	VersionString   []byte
	Flags           uint16 //todo: define flags betterer
	NumberOfStreams uint16
}

type OptionalHeader32

type OptionalHeader32 struct {
	Magic                       uint16
	MajorLinkerVersion          uint8
	MinorLinkerVersion          uint8
	SizeOfCode                  uint32
	SizeOfInitializedData       uint32
	SizeOfUninitializedData     uint32
	AddressOfEntryPoint         uint32
	BaseOfCode                  uint32
	BaseOfData                  uint32
	ImageBase                   uint32
	SectionAlignment            uint32
	FileAlignment               uint32
	MajorOperatingSystemVersion uint16
	MinorOperatingSystemVersion uint16
	MajorImageVersion           uint16
	MinorImageVersion           uint16
	MajorSubsystemVersion       uint16
	MinorSubsystemVersion       uint16
	Win32VersionValue           uint32
	SizeOfImage                 uint32
	SizeOfHeaders               uint32
	CheckSum                    uint32
	Subsystem                   uint16
	DllCharacteristics          uint16
	SizeOfStackReserve          uint32
	SizeOfStackCommit           uint32
	SizeOfHeapReserve           uint32
	SizeOfHeapCommit            uint32
	LoaderFlags                 uint32
	NumberOfRvaAndSizes         uint32
	DataDirectory               [16]DataDirectory
}

type OptionalHeader64

type OptionalHeader64 struct {
	Magic                       uint16
	MajorLinkerVersion          uint8
	MinorLinkerVersion          uint8
	SizeOfCode                  uint32
	SizeOfInitializedData       uint32
	SizeOfUninitializedData     uint32
	AddressOfEntryPoint         uint32
	BaseOfCode                  uint32
	ImageBase                   uint64
	SectionAlignment            uint32
	FileAlignment               uint32
	MajorOperatingSystemVersion uint16
	MinorOperatingSystemVersion uint16
	MajorImageVersion           uint16
	MinorImageVersion           uint16
	MajorSubsystemVersion       uint16
	MinorSubsystemVersion       uint16
	Win32VersionValue           uint32
	SizeOfImage                 uint32
	SizeOfHeaders               uint32
	CheckSum                    uint32
	Subsystem                   uint16
	DllCharacteristics          uint16
	SizeOfStackReserve          uint64
	SizeOfStackCommit           uint64
	SizeOfHeapReserve           uint64
	SizeOfHeapCommit            uint64
	LoaderFlags                 uint32
	NumberOfRvaAndSizes         uint32
	DataDirectory               [16]DataDirectory
}

type Reloc

type Reloc struct {
	VirtualAddress   uint32
	SymbolTableIndex uint32
	Type             uint16
}

Reloc represents a PE COFF relocation. Each section contains its own relocation list.

type RelocationBlock

type RelocationBlock struct {
	VirtualAddress uint32
	SizeOfBlock    uint32
}

RelocationBlock - for base relocation entries

type RelocationTableEntry

type RelocationTableEntry struct {
	RelocationBlock
	BlockItems []BlockItem
}

RelocationTable - for base relocation entries

type Section

type Section struct {
	SectionHeader
	Relocs []Reloc

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	io.ReaderAt
	// contains filtered or unexported fields
}

Section provides access to PE COFF section.

func (*Section) Data

func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the PE section s.

func (*Section) Open

func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the PE section s.

func (*Section) Replace

func (s *Section) Replace(reader io.ReaderAt, length int64)

Replace Section's Data

type SectionHeader

type SectionHeader struct {
	Name                 string
	OriginalName         [8]uint8
	VirtualSize          uint32
	VirtualAddress       uint32
	Size                 uint32
	Offset               uint32
	PointerToRelocations uint32
	PointerToLineNumbers uint32
	NumberOfRelocations  uint16
	NumberOfLineNumbers  uint16
	Characteristics      uint32
}

SectionHeader is similar to SectionHeader32 with Name field replaced by Go string. OriginalName is the original name of the section on disk.

type SectionHeader32

type SectionHeader32 struct {
	Name                 [8]uint8
	VirtualSize          uint32
	VirtualAddress       uint32
	SizeOfRawData        uint32
	PointerToRawData     uint32
	PointerToRelocations uint32
	PointerToLineNumbers uint32
	NumberOfRelocations  uint16
	NumberOfLineNumbers  uint16
	Characteristics      uint32
}

SectionHeader32 represents real PE COFF section header.

type StringTable

type StringTable []byte

StringTable is a COFF string table.

func (StringTable) String

func (st StringTable) String(start uint32) (string, error)

String extracts string from COFF string table st at offset start.

type Symbol

type Symbol struct {
	Name          string
	Value         uint32
	SectionNumber int16
	Type          uint16
	StorageClass  uint8
}

Symbol is similar to COFFSymbol with Name field replaced by Go string. Symbol also does not have NumberOfAuxSymbols.

Jump to

Keyboard shortcuts

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