Mercurial > projects > ddmd
view dbg/image/PE.d @ 0:10317f0c89a5
Initial commit
author | korDen |
---|---|
date | Sat, 24 Oct 2009 08:42:06 +0400 |
parents | |
children | 6bdecc3f4569 |
line wrap: on
line source
/** A simple PE/COFF image format reader. Authors: Jeremie Pelletier References: $(LINK http://www.csn.ul.ie/~caolan/publink/winresdump/winresdump/doc/pefile.html) License: Public Domain */ module dbg.image.PE; version(Windows) { import std.c.string : strncmp; import dbg.Debug; import dbg.symbol.CodeView; //import dbg.symbol.COFF; //import sys.windows.FileSystem; //import sys.windows.Memory; //import sys.windows.Security : GENERIC_READ; //import sys.windows.Information : CloseHandle; //import sys.windows.Image; import win32.windows; import win32.winbase; enum IMAGE_SIZEOF_NT_OPTIONAL64_HEADER = 240; struct IMAGE_NT_HEADERS64 { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } auto IMAGE_FIRST_SECTION64( const(IMAGE_NT_HEADERS64*) ntheader ) { return cast(PIMAGE_SECTION_HEADER) ((cast(UINT_PTR)ntheader) + IMAGE_NT_HEADERS64.OptionalHeader.offsetof + (cast(PIMAGE_NT_HEADERS64)(ntheader)).FileHeader.SizeOfOptionalHeader); } auto IMAGE_FIRST_SECTION32( const(IMAGE_NT_HEADERS32*) ntheader ) { return cast(PIMAGE_SECTION_HEADER)((cast(UINT_PTR)ntheader) + IMAGE_NT_HEADERS32.OptionalHeader.offsetof + (cast(PIMAGE_NT_HEADERS32)ntheader).FileHeader.SizeOfOptionalHeader); } class PEImage : IExecutableImage { /** Loads and validate the image file. Params: fileName = Path to the image file. */ this(string fileName) in { assert(fileName.length && fileName.ptr); } body { _filename = fileName; // Create the file mapping _file = CreateFileA((fileName ~ '\0').ptr, GENERIC_READ, FILE_SHARE_READ, null, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, null); if(_file == INVALID_HANDLE_VALUE) SystemException(); GetFileSizeEx(_file, &_fileSize); _map = CreateFileMapping(_file, null, PAGE_READONLY, 0, 0, null); if(!_map) SystemException(); _view = cast(const(ubyte)*)MapViewOfFile(_map, FILE_MAP_READ, 0, 0, 0); if(!_view) SystemException(); // Verify image headers if(_dos.e_magic != IMAGE_DOS_SIGNATURE) goto Error; CheckOffset(_dos.e_lfanew); _nt = cast(IMAGE_NT_HEADERS32*)(_view + _dos.e_lfanew); if(_nt.Signature != IMAGE_NT_SIGNATURE) goto Error; _is64 = _nt.FileHeader.SizeOfOptionalHeader == IMAGE_SIZEOF_NT_OPTIONAL64_HEADER; if(_is64) { if(_nt64.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) goto Error; } else { if(_nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) goto Error; } // Create the RVA lookup table auto sections = this.sections; RVAEntry* e = void; _rvaTable.length = sections.length; foreach(i, ref s; sections) with(s) { e = &_rvaTable[i]; e.start = VirtualAddress; e.end = VirtualAddress + SizeOfRawData; e.base = PointerToRawData; } return; Error: throw new PEInvalidException(this); } /** Unloads the PE file. */ ~this() { if(_dos && !UnmapViewOfFile(cast(void*)_dos)) SystemException(); if(_map && !CloseHandle(_map)) SystemException(); if(_file && !CloseHandle(_file)) SystemException(); } /** Get the filename of the image */ string filename() const { return _filename; } /** Get whether the image uses the 64bit structures or not */ bool is64() const { return _is64; } /** Get the base address of the image */ long imageBase() const { return _is64 ? _nt64.OptionalHeader.ImageBase : _nt.OptionalHeader.ImageBase; } /** Get the raw image data */ const(ubyte)[] data() const { return _view[0 .. cast(size_t)_fileSize.QuadPart]; } /** Get the dos, nt or nt64 headers */ const(IMAGE_DOS_HEADER)* dosHeader() const { return _dos; } const(IMAGE_NT_HEADERS32)* ntHeaders32() const { return _nt; } const(IMAGE_NT_HEADERS64)* ntHeaders64() const { return _nt64; } /** Get the array of data directories */ const(IMAGE_DATA_DIRECTORY)[] dataDirectory() const { return _is64 ? _nt64.OptionalHeader.DataDirectory : _nt.OptionalHeader.DataDirectory; } /** Get the array of section headers */ const(IMAGE_SECTION_HEADER)[] sections() const { return (_is64 ? IMAGE_FIRST_SECTION64(_nt64) : IMAGE_FIRST_SECTION32(_nt)) [0 .. _nt.FileHeader.NumberOfSections]; } /** Translate the given Virtual Address to its corresponding data offset. */ long LookupVA(long va) const { return LookupRVA(va - imageBase); } /** Translate the given Relative Virtual Address to its corresponding data offset. */ long LookupRVA(long rva) const { foreach(ref e; _rvaTable) with(e) { if(rva >= start && rva < end) { long offset = base + (rva - start); CheckOffset(offset); return offset; } } return 0; } /** Get a data structure in the image from its RVA */ const(T)* GetDataFromRVA(T : T*)(long rva) const { long offset = LookupRVA(rva); return offset ? cast(T*)(_view + offset) : null; } /** Get a data directory in the image from its ID */ const(T)* GetDirectory(T)(uint id) const { const IMAGE_DATA_DIRECTORY* dir = &dataDirectory[id]; return dir.VirtualAddress && dir.Size ? GetDataFromRVA!(T*)(dir.VirtualAddress) : null; } /** Find the first section matching the given flags mask */ const(IMAGE_SECTION_HEADER)* FindSection(uint mask) const in { assert(mask); } body { foreach(ref section; sections) if(section.Characteristics & mask) return §ion; return null; } /** Find a section by its name */ const(IMAGE_SECTION_HEADER)* FindSection(string name) const in { assert(name.length && name.ptr); } body { foreach(ref section; sections) if(strncmp(cast(char*)section.Name.ptr, name.ptr, section.Name.length) == 0) return §ion; return null; } /** Get the offset to the code segment */ uint codeOffset() const { const(IMAGE_SECTION_HEADER)* section = FindSection(IMAGE_SCN_MEM_EXECUTE); return section ? section.VirtualAddress : 0; } /** Get the symbolic debug info object for this image */ ISymbolicDebugInfo debugInfo() { uint va = _nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress; if(!va) return null; const(IMAGE_DEBUG_DIRECTORY)* dir = void; uint size = _nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size; uint offset = void; // Borland directory const(IMAGE_SECTION_HEADER)* section = FindSection(".debug"); if(section && section.VirtualAddress == va) { CheckOffset(section.PointerToRawData); dir = cast(IMAGE_DEBUG_DIRECTORY*)(_view + section.PointerToRawData); } // Microsoft directory else { section = FindSection(".rdata"); if(!section) goto NoDebug; offset = section.PointerToRawData + (va - section.VirtualAddress); CheckOffset(offset); dir = cast(IMAGE_DEBUG_DIRECTORY*)(_view + offset); } const(void)* end = cast(void*)dir + size; Scan: for(; dir < end; dir++) { switch(dir.Type) { //case IMAGE_DEBUG_TYPE_COFF: case IMAGE_DEBUG_TYPE_CODEVIEW: // TODO: support more types break Scan; default: } } if(dir >= end) goto NoDebug; offset = dir.PointerToRawData + dir.SizeOfData; CheckOffset(offset); auto debugView = _view[dir.PointerToRawData .. offset]; switch(dir.Type) { //case IMAGE_DEBUG_TYPE_COFF: // return new COFFDebugInfo(debugView); case IMAGE_DEBUG_TYPE_CODEVIEW: return new CodeViewDebugInfo(debugView); default: assert(0); } NoDebug: // TODO: we have no debug section or directory, but there csould still // be external symbol files we can use. return null; } private: /** Verify a file offset before accessing it */ void CheckOffset(long offset) const { if(offset > _fileSize.QuadPart) throw new PECorruptedException(this); } string _filename; HANDLE _file; HANDLE _map; LARGE_INTEGER _fileSize; bool _is64; union { const(ubyte)* _view; const(IMAGE_DOS_HEADER)* _dos; } union { const(IMAGE_NT_HEADERS32)* _nt; const(IMAGE_NT_HEADERS64)* _nt64; } struct RVAEntry { uint start; uint end; uint base; } RVAEntry[] _rvaTable; } /// Thrown if file open failed. class PEException : Exception { this(string msg) { super("PEImage: " ~ msg); } } /// Thrown if not a valid module file class PEInvalidException : PEException { this(in PEImage img) { super("Invalid PE file."); } } /// Thrown on corrupted module file. class PECorruptedException : PEException { this(in PEImage img) { super("Corrupted PE file."); } } } // version(Windows)