comparison dbg/image/PE.d @ 0:10317f0c89a5

Initial commit
author korDen
date Sat, 24 Oct 2009 08:42:06 +0400
parents
children 6bdecc3f4569
comparison
equal deleted inserted replaced
-1:000000000000 0:10317f0c89a5
1 /**
2 A simple PE/COFF image format reader.
3
4 Authors:
5 Jeremie Pelletier
6
7 References:
8 $(LINK http://www.csn.ul.ie/~caolan/publink/winresdump/winresdump/doc/pefile.html)
9
10 License:
11 Public Domain
12 */
13 module dbg.image.PE;
14
15 version(Windows) {
16
17 import std.c.string : strncmp;
18 import dbg.Debug;
19 import dbg.symbol.CodeView;
20 //import dbg.symbol.COFF;
21 //import sys.windows.FileSystem;
22 //import sys.windows.Memory;
23 //import sys.windows.Security : GENERIC_READ;
24 //import sys.windows.Information : CloseHandle;
25 //import sys.windows.Image;
26
27 import win32.windows;
28 import win32.winbase;
29
30 enum IMAGE_SIZEOF_NT_OPTIONAL64_HEADER = 240;
31
32 struct IMAGE_NT_HEADERS64 {
33 DWORD Signature;
34 IMAGE_FILE_HEADER FileHeader;
35 IMAGE_OPTIONAL_HEADER64 OptionalHeader;
36 }
37
38 auto IMAGE_FIRST_SECTION64( const(IMAGE_NT_HEADERS64*) ntheader ) {
39 return cast(PIMAGE_SECTION_HEADER) ((cast(UINT_PTR)ntheader) + IMAGE_NT_HEADERS64.OptionalHeader.offsetof + (cast(PIMAGE_NT_HEADERS64)(ntheader)).FileHeader.SizeOfOptionalHeader);
40 }
41
42 auto IMAGE_FIRST_SECTION32( const(IMAGE_NT_HEADERS32*) ntheader ) {
43 return cast(PIMAGE_SECTION_HEADER)((cast(UINT_PTR)ntheader) + IMAGE_NT_HEADERS32.OptionalHeader.offsetof + (cast(PIMAGE_NT_HEADERS32)ntheader).FileHeader.SizeOfOptionalHeader);
44 }
45
46 class PEImage : IExecutableImage {
47 /**
48 Loads and validate the image file.
49
50 Params:
51 fileName = Path to the image file.
52 */
53 this(string fileName)
54 in {
55 assert(fileName.length && fileName.ptr);
56 }
57 body {
58 _filename = fileName;
59
60 // Create the file mapping
61 _file = CreateFileA((fileName ~ '\0').ptr, GENERIC_READ, FILE_SHARE_READ,
62 null, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, null);
63 if(_file == INVALID_HANDLE_VALUE) SystemException();
64
65 GetFileSizeEx(_file, &_fileSize);
66
67 _map = CreateFileMapping(_file, null, PAGE_READONLY, 0, 0, null);
68 if(!_map) SystemException();
69
70 _view = cast(const(ubyte)*)MapViewOfFile(_map, FILE_MAP_READ, 0, 0, 0);
71 if(!_view) SystemException();
72
73 // Verify image headers
74 if(_dos.e_magic != IMAGE_DOS_SIGNATURE) goto Error;
75 CheckOffset(_dos.e_lfanew);
76
77 _nt = cast(IMAGE_NT_HEADERS32*)(_view + _dos.e_lfanew);
78 if(_nt.Signature != IMAGE_NT_SIGNATURE) goto Error;
79
80 _is64 = _nt.FileHeader.SizeOfOptionalHeader == IMAGE_SIZEOF_NT_OPTIONAL64_HEADER;
81
82 if(_is64) {
83 if(_nt64.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
84 goto Error;
85 }
86 else {
87 if(_nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
88 goto Error;
89 }
90
91 // Create the RVA lookup table
92 auto sections = this.sections;
93 RVAEntry* e = void;
94 _rvaTable.length = sections.length;
95 foreach(i, ref s; sections) with(s) {
96 e = &_rvaTable[i];
97 e.start = VirtualAddress;
98 e.end = VirtualAddress + SizeOfRawData;
99 e.base = PointerToRawData;
100 }
101
102 return;
103
104 Error:
105 throw new PEInvalidException(this);
106 }
107
108 /**
109 Unloads the PE file.
110 */
111 ~this() {
112 if(_dos && !UnmapViewOfFile(cast(void*)_dos)) SystemException();
113 if(_map && !CloseHandle(_map)) SystemException();
114 if(_file && !CloseHandle(_file)) SystemException();
115 }
116
117 /**
118 Get the filename of the image
119 */
120 string filename() const {
121 return _filename;
122 }
123
124 /**
125 Get whether the image uses the 64bit structures or not
126 */
127 bool is64() const {
128 return _is64;
129 }
130
131 /**
132 Get the base address of the image
133 */
134 long imageBase() const {
135 return _is64 ? _nt64.OptionalHeader.ImageBase : _nt.OptionalHeader.ImageBase;
136 }
137
138 /**
139 Get the raw image data
140 */
141 const(ubyte)[] data() const {
142 return _view[0 .. cast(size_t)_fileSize.QuadPart];
143 }
144
145 /**
146 Get the dos, nt or nt64 headers
147 */
148 const(IMAGE_DOS_HEADER)* dosHeader() const { return _dos; }
149 const(IMAGE_NT_HEADERS32)* ntHeaders32() const { return _nt; }
150 const(IMAGE_NT_HEADERS64)* ntHeaders64() const { return _nt64; }
151
152 /**
153 Get the array of data directories
154 */
155 const(IMAGE_DATA_DIRECTORY)[] dataDirectory() const {
156 return _is64 ? _nt64.OptionalHeader.DataDirectory : _nt.OptionalHeader.DataDirectory;
157 }
158
159 /**
160 Get the array of section headers
161 */
162 const(IMAGE_SECTION_HEADER)[] sections() const {
163 return (_is64 ? IMAGE_FIRST_SECTION64(_nt64) : IMAGE_FIRST_SECTION32(_nt))
164 [0 .. _nt.FileHeader.NumberOfSections];
165 }
166
167 /**
168 Translate the given Virtual Address to its corresponding data offset.
169 */
170 long LookupVA(long va) const {
171 return LookupRVA(va - imageBase);
172 }
173
174 /**
175 Translate the given Relative Virtual Address to its corresponding
176 data offset.
177 */
178 long LookupRVA(long rva) const {
179 foreach(ref e; _rvaTable) with(e) {
180 if(rva >= start && rva < end) {
181 long offset = base + (rva - start);
182 CheckOffset(offset);
183 return offset;
184 }
185 }
186
187 return 0;
188 }
189
190 /**
191 Get a data structure in the image from its RVA
192 */
193 const(T)* GetDataFromRVA(T : T*)(long rva) const {
194 long offset = LookupRVA(rva);
195 return offset ? cast(T*)(_view + offset) : null;
196 }
197
198 /**
199 Get a data directory in the image from its ID
200 */
201 const(T)* GetDirectory(T)(uint id) const {
202 const IMAGE_DATA_DIRECTORY* dir = &dataDirectory[id];
203 return dir.VirtualAddress && dir.Size ?
204 GetDataFromRVA!(T*)(dir.VirtualAddress) : null;
205 }
206
207 /**
208 Find the first section matching the given flags mask
209 */
210 const(IMAGE_SECTION_HEADER)* FindSection(uint mask) const
211 in {
212 assert(mask);
213 }
214 body {
215 foreach(ref section; sections)
216 if(section.Characteristics & mask)
217 return &section;
218
219 return null;
220 }
221
222 /**
223 Find a section by its name
224 */
225 const(IMAGE_SECTION_HEADER)* FindSection(string name) const
226 in {
227 assert(name.length && name.ptr);
228 }
229 body {
230 foreach(ref section; sections)
231 if(strncmp(cast(char*)section.Name.ptr, name.ptr, section.Name.length) == 0)
232 return &section;
233
234 return null;
235 }
236
237 /**
238 Get the offset to the code segment
239 */
240 uint codeOffset() const {
241 const(IMAGE_SECTION_HEADER)* section = FindSection(IMAGE_SCN_MEM_EXECUTE);
242 return section ? section.VirtualAddress : 0;
243 }
244
245 /**
246 Get the symbolic debug info object for this image
247 */
248 ISymbolicDebugInfo debugInfo() {
249 uint va = _nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
250 if(!va) return null;
251
252 const(IMAGE_DEBUG_DIRECTORY)* dir = void;
253 uint size = _nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
254 uint offset = void;
255
256 // Borland directory
257 const(IMAGE_SECTION_HEADER)* section = FindSection(".debug");
258 if(section && section.VirtualAddress == va) {
259 CheckOffset(section.PointerToRawData);
260
261 dir = cast(IMAGE_DEBUG_DIRECTORY*)(_view + section.PointerToRawData);
262 }
263 // Microsoft directory
264 else {
265 section = FindSection(".rdata");
266 if(!section) goto NoDebug;
267
268 offset = section.PointerToRawData + (va - section.VirtualAddress);
269 CheckOffset(offset);
270
271 dir = cast(IMAGE_DEBUG_DIRECTORY*)(_view + offset);
272 }
273
274 const(void)* end = cast(void*)dir + size;
275 Scan: for(; dir < end; dir++) {
276 switch(dir.Type) {
277 //case IMAGE_DEBUG_TYPE_COFF:
278 case IMAGE_DEBUG_TYPE_CODEVIEW:
279 // TODO: support more types
280 break Scan;
281
282 default:
283 }
284 }
285
286 if(dir >= end) goto NoDebug;
287
288 offset = dir.PointerToRawData + dir.SizeOfData;
289 CheckOffset(offset);
290 auto debugView = _view[dir.PointerToRawData .. offset];
291
292 switch(dir.Type) {
293 //case IMAGE_DEBUG_TYPE_COFF:
294 // return new COFFDebugInfo(debugView);
295 case IMAGE_DEBUG_TYPE_CODEVIEW:
296 return new CodeViewDebugInfo(debugView);
297 default:
298 assert(0);
299 }
300
301 NoDebug:
302 // TODO: we have no debug section or directory, but there csould still
303 // be external symbol files we can use.
304 return null;
305 }
306
307 private:
308
309 /**
310 Verify a file offset before accessing it
311 */
312 void CheckOffset(long offset) const {
313 if(offset > _fileSize.QuadPart) throw new PECorruptedException(this);
314 }
315
316 string _filename;
317 HANDLE _file;
318 HANDLE _map;
319 LARGE_INTEGER _fileSize;
320 bool _is64;
321
322 union {
323 const(ubyte)* _view;
324 const(IMAGE_DOS_HEADER)* _dos;
325 }
326 union {
327 const(IMAGE_NT_HEADERS32)* _nt;
328 const(IMAGE_NT_HEADERS64)* _nt64;
329 }
330
331 struct RVAEntry {
332 uint start;
333 uint end;
334 uint base;
335 }
336
337 RVAEntry[] _rvaTable;
338 }
339
340 /// Thrown if file open failed.
341 class PEException : Exception {
342 this(string msg) {
343 super("PEImage: " ~ msg);
344 }
345 }
346
347 /// Thrown if not a valid module file
348 class PEInvalidException : PEException {
349 this(in PEImage img) {
350 super("Invalid PE file.");
351 }
352 }
353
354 /// Thrown on corrupted module file.
355 class PECorruptedException : PEException {
356 this(in PEImage img) {
357 super("Corrupted PE file.");
358 }
359 }
360
361 } // version(Windows)