1 //===-- ObjectFilePECOFF.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ObjectFilePECOFF.h"
11 
12 #include "llvm/Support/MachO.h"
13 
14 #include "lldb/Core/ArchSpec.h"
15 #include "lldb/Core/DataBuffer.h"
16 #include "lldb/Host/FileSpec.h"
17 #include "lldb/Core/FileSpecList.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Core/StreamString.h"
23 #include "lldb/Core/Timer.h"
24 #include "lldb/Core/UUID.h"
25 #include "lldb/Symbol/ObjectFile.h"
26 
27 static uint32_t COFFMachineToMachCPU(uint16_t machine);
28 
29 #define IMAGE_FILE_MACHINE_UNKNOWN      0x0000
30 #define IMAGE_FILE_MACHINE_AM33         0x01d3  // Matsushita AM33
31 #define IMAGE_FILE_MACHINE_AMD64        0x8664  // x64
32 #define IMAGE_FILE_MACHINE_ARM          0x01c0  // ARM little endian
33 #define IMAGE_FILE_MACHINE_EBC          0x0ebc  // EFI byte code
34 #define IMAGE_FILE_MACHINE_I386         0x014c  // Intel 386 or later processors and compatible processors
35 #define IMAGE_FILE_MACHINE_IA64         0x0200  // Intel Itanium processor family
36 #define IMAGE_FILE_MACHINE_M32R         0x9041  // Mitsubishi M32R little endian
37 #define IMAGE_FILE_MACHINE_MIPS16       0x0266  // MIPS16
38 #define IMAGE_FILE_MACHINE_MIPSFPU      0x0366  // MIPS with FPU
39 #define IMAGE_FILE_MACHINE_MIPSFPU16    0x0466  // MIPS16 with FPU
40 #define IMAGE_FILE_MACHINE_POWERPC      0x01f0  // Power PC little endian
41 #define IMAGE_FILE_MACHINE_POWERPCFP    0x01f1  // Power PC with floating point support
42 #define IMAGE_FILE_MACHINE_R4000        0x0166  // MIPS little endian
43 #define IMAGE_FILE_MACHINE_SH3          0x01a2  // Hitachi SH3
44 #define IMAGE_FILE_MACHINE_SH3DSP       0x01a3  // Hitachi SH3 DSP
45 #define IMAGE_FILE_MACHINE_SH4          0x01a6  // Hitachi SH4
46 #define IMAGE_FILE_MACHINE_SH5          0x01a8  // Hitachi SH5
47 #define IMAGE_FILE_MACHINE_THUMB        0x01c2  // Thumb
48 #define IMAGE_FILE_MACHINE_WCEMIPSV2    0x0169  // MIPS little-endian WCE v2
49 
50 
51 #define IMAGE_DOS_SIGNATURE             0x5A4D      // MZ
52 #define IMAGE_OS2_SIGNATURE             0x454E      // NE
53 #define IMAGE_OS2_SIGNATURE_LE          0x454C      // LE
54 #define IMAGE_NT_SIGNATURE              0x00004550  // PE00
55 #define OPT_HEADER_MAGIC_PE32           0x010b
56 #define OPT_HEADER_MAGIC_PE32_PLUS      0x020b
57 
58 #define IMAGE_FILE_RELOCS_STRIPPED          0x0001
59 #define IMAGE_FILE_EXECUTABLE_IMAGE         0x0002
60 #define IMAGE_FILE_LINE_NUMS_STRIPPED       0x0004
61 #define IMAGE_FILE_LOCAL_SYMS_STRIPPED      0x0008
62 #define IMAGE_FILE_AGGRESSIVE_WS_TRIM       0x0010
63 #define IMAGE_FILE_LARGE_ADDRESS_AWARE      0x0020
64 //#define                                   0x0040  // Reserved
65 #define IMAGE_FILE_BYTES_REVERSED_LO        0x0080
66 #define IMAGE_FILE_32BIT_MACHINE            0x0100
67 #define IMAGE_FILE_DEBUG_STRIPPED           0x0200
68 #define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP  0x0400
69 #define IMAGE_FILE_NET_RUN_FROM_SWAP        0x0800
70 #define IMAGE_FILE_SYSTEM                   0x1000
71 #define IMAGE_FILE_DLL                      0x2000
72 #define IMAGE_FILE_UP_SYSTEM_ONLY           0x4000
73 #define IMAGE_FILE_BYTES_REVERSED_HI        0x8000
74 
75 
76 // Section Flags
77 // The section flags in the Characteristics field of the section header indicate
78 // characteristics of the section.
79 #define IMAGE_SCN_TYPE_NO_PAD               0x00000008 // The section should not be padded to the next boundary. This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. This is valid only for object files.
80 #define IMAGE_SCN_CNT_CODE                  0x00000020 // The section contains executable code.
81 #define IMAGE_SCN_CNT_INITIALIZED_DATA      0x00000040 // The section contains initialized data.
82 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA    0x00000080 // The section contains uninitialized data.
83 #define IMAGE_SCN_LNK_OTHER                 0x00000100 // Reserved for future use.
84 #define IMAGE_SCN_LNK_INFO                  0x00000200 // The section contains comments or other information. The .drectve section has this type. This is valid for object files only.
85 #define IMAGE_SCN_LNK_REMOVE                0x00000800 // The section will not become part of the image. This is valid only for object files.
86 #define IMAGE_SCN_LNK_COMDAT                0x00001000 // The section contains COMDAT data. For more information, see section 5.5.6, “COMDAT Sections (Object Only).” This is valid only for object files.
87 #define IMAGE_SCN_GPREL                     0x00008000 // The section contains data referenced through the global pointer (GP).
88 #define IMAGE_SCN_MEM_PURGEABLE             0x00020000
89 #define IMAGE_SCN_MEM_16BIT                 0x00020000 // For ARM machine types, the section contains Thumb code.  Reserved for future use with other machine types.
90 #define IMAGE_SCN_MEM_LOCKED                0x00040000
91 #define IMAGE_SCN_MEM_PRELOAD               0x00080000
92 #define IMAGE_SCN_ALIGN_1BYTES              0x00100000 // Align data on a 1-byte boundary. Valid only for object files.
93 #define IMAGE_SCN_ALIGN_2BYTES              0x00200000 // Align data on a 2-byte boundary. Valid only for object files.
94 #define IMAGE_SCN_ALIGN_4BYTES              0x00300000 // Align data on a 4-byte boundary. Valid only for object files.
95 #define IMAGE_SCN_ALIGN_8BYTES              0x00400000 // Align data on an 8-byte boundary. Valid only for object files.
96 #define IMAGE_SCN_ALIGN_16BYTES             0x00500000 // Align data on a 16-byte boundary. Valid only for object files.
97 #define IMAGE_SCN_ALIGN_32BYTES             0x00600000 // Align data on a 32-byte boundary. Valid only for object files.
98 #define IMAGE_SCN_ALIGN_64BYTES             0x00700000 // Align data on a 64-byte boundary. Valid only for object files.
99 #define IMAGE_SCN_ALIGN_128BYTES            0x00800000 // Align data on a 128-byte boundary. Valid only for object files.
100 #define IMAGE_SCN_ALIGN_256BYTES            0x00900000 // Align data on a 256-byte boundary. Valid only for object files.
101 #define IMAGE_SCN_ALIGN_512BYTES            0x00A00000 // Align data on a 512-byte boundary. Valid only for object files.
102 #define IMAGE_SCN_ALIGN_1024BYTES           0x00B00000 // Align data on a 1024-byte boundary. Valid only for object files.
103 #define IMAGE_SCN_ALIGN_2048BYTES           0x00C00000 // Align data on a 2048-byte boundary. Valid only for object files.
104 #define IMAGE_SCN_ALIGN_4096BYTES           0x00D00000 // Align data on a 4096-byte boundary. Valid only for object files.
105 #define IMAGE_SCN_ALIGN_8192BYTES           0x00E00000 // Align data on an 8192-byte boundary. Valid only for object files.
106 #define IMAGE_SCN_LNK_NRELOC_OVFL           0x01000000 // The section contains extended relocations.
107 #define IMAGE_SCN_MEM_DISCARDABLE           0x02000000 // The section can be discarded as needed.
108 #define IMAGE_SCN_MEM_NOT_CACHED            0x04000000 // The section cannot be cached.
109 #define IMAGE_SCN_MEM_NOT_PAGED             0x08000000 // The section is not pageable.
110 #define IMAGE_SCN_MEM_SHARED                0x10000000 // The section can be shared in memory.
111 #define IMAGE_SCN_MEM_EXECUTE               0x20000000 // The section can be executed as code.
112 #define IMAGE_SCN_MEM_READ                  0x40000000 // The section can be read.
113 #define IMAGE_SCN_MEM_WRITE                 0x80000000 // The section can be written to.
114 
115 using namespace lldb;
116 using namespace lldb_private;
117 
118 void
119 ObjectFilePECOFF::Initialize()
120 {
121     PluginManager::RegisterPlugin (GetPluginNameStatic(),
122                                    GetPluginDescriptionStatic(),
123                                    CreateInstance,
124                                    CreateMemoryInstance);
125 }
126 
127 void
128 ObjectFilePECOFF::Terminate()
129 {
130     PluginManager::UnregisterPlugin (CreateInstance);
131 }
132 
133 
134 const char *
135 ObjectFilePECOFF::GetPluginNameStatic()
136 {
137     return "object-file.pe-coff";
138 }
139 
140 const char *
141 ObjectFilePECOFF::GetPluginDescriptionStatic()
142 {
143     return "Portable Executable and Common Object File Format object file reader (32 and 64 bit)";
144 }
145 
146 
147 ObjectFile *
148 ObjectFilePECOFF::CreateInstance (const lldb::ModuleSP &module_sp,
149                                   DataBufferSP& data_sp,
150                                   lldb::offset_t data_offset,
151                                   const lldb_private::FileSpec* file,
152                                   lldb::offset_t file_offset,
153                                   lldb::offset_t length)
154 {
155     if (!data_sp)
156     {
157         data_sp = file->MemoryMapFileContents(file_offset, length);
158         data_offset = 0;
159     }
160 
161     if (ObjectFilePECOFF::MagicBytesMatch(data_sp))
162     {
163         // Update the data to contain the entire file if it doesn't already
164         if (data_sp->GetByteSize() < length)
165             data_sp = file->MemoryMapFileContents(file_offset, length);
166         std::auto_ptr<ObjectFile> objfile_ap(new ObjectFilePECOFF (module_sp, data_sp, data_offset, file, file_offset, length));
167         if (objfile_ap.get() && objfile_ap->ParseHeader())
168             return objfile_ap.release();
169     }
170     return NULL;
171 }
172 
173 ObjectFile *
174 ObjectFilePECOFF::CreateMemoryInstance (const lldb::ModuleSP &module_sp,
175                                         lldb::DataBufferSP& data_sp,
176                                         const lldb::ProcessSP &process_sp,
177                                         lldb::addr_t header_addr)
178 {
179     return NULL;
180 }
181 
182 bool
183 ObjectFilePECOFF::MagicBytesMatch (DataBufferSP& data_sp)
184 {
185     DataExtractor data(data_sp, eByteOrderLittle, 4);
186     lldb::offset_t offset = 0;
187     uint16_t magic = data.GetU16 (&offset);
188     return magic == IMAGE_DOS_SIGNATURE;
189 }
190 
191 
192 ObjectFilePECOFF::ObjectFilePECOFF (const lldb::ModuleSP &module_sp,
193                                     DataBufferSP& data_sp,
194                                     lldb::offset_t data_offset,
195                                     const FileSpec* file,
196                                     lldb::offset_t file_offset,
197                                     lldb::offset_t length) :
198     ObjectFile (module_sp, file, file_offset, length, data_sp, data_offset),
199     m_dos_header (),
200     m_coff_header (),
201     m_coff_header_opt (),
202     m_sect_headers ()
203 {
204     ::memset (&m_dos_header, 0, sizeof(m_dos_header));
205     ::memset (&m_coff_header, 0, sizeof(m_coff_header));
206     ::memset (&m_coff_header_opt, 0, sizeof(m_coff_header_opt));
207 }
208 
209 
210 ObjectFilePECOFF::~ObjectFilePECOFF()
211 {
212 }
213 
214 
215 bool
216 ObjectFilePECOFF::ParseHeader ()
217 {
218     ModuleSP module_sp(GetModule());
219     if (module_sp)
220     {
221         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
222         m_sect_headers.clear();
223         m_data.SetByteOrder (eByteOrderLittle);
224         lldb::offset_t offset = 0;
225 
226         if (ParseDOSHeader())
227         {
228             offset = m_dos_header.e_lfanew;
229             uint32_t pe_signature = m_data.GetU32 (&offset);
230             if (pe_signature != IMAGE_NT_SIGNATURE)
231                 return false;
232             if (ParseCOFFHeader(&offset))
233             {
234                 if (m_coff_header.hdrsize > 0)
235                     ParseCOFFOptionalHeader(&offset);
236                 ParseSectionHeaders (offset);
237             }
238             return true;
239         }
240     }
241     return false;
242 }
243 
244 
245 ByteOrder
246 ObjectFilePECOFF::GetByteOrder () const
247 {
248     return eByteOrderLittle;
249 }
250 
251 bool
252 ObjectFilePECOFF::IsExecutable() const
253 {
254     return (m_coff_header.flags & IMAGE_FILE_DLL) == 0;
255 }
256 
257 uint32_t
258 ObjectFilePECOFF::GetAddressByteSize () const
259 {
260     if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
261         return 8;
262     else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
263         return 4;
264     return 4;
265 }
266 
267 //----------------------------------------------------------------------
268 // NeedsEndianSwap
269 //
270 // Return true if an endian swap needs to occur when extracting data
271 // from this file.
272 //----------------------------------------------------------------------
273 bool
274 ObjectFilePECOFF::NeedsEndianSwap() const
275 {
276 #if defined(__LITTLE_ENDIAN__)
277     return false;
278 #else
279     return true;
280 #endif
281 }
282 //----------------------------------------------------------------------
283 // ParseDOSHeader
284 //----------------------------------------------------------------------
285 bool
286 ObjectFilePECOFF::ParseDOSHeader ()
287 {
288     bool success = false;
289     lldb::offset_t offset = 0;
290     success = m_data.ValidOffsetForDataOfSize(0, sizeof(m_dos_header));
291 
292     if (success)
293     {
294         m_dos_header.e_magic = m_data.GetU16(&offset); // Magic number
295         success = m_dos_header.e_magic == IMAGE_DOS_SIGNATURE;
296 
297         if (success)
298         {
299             m_dos_header.e_cblp     = m_data.GetU16(&offset); // Bytes on last page of file
300             m_dos_header.e_cp       = m_data.GetU16(&offset); // Pages in file
301             m_dos_header.e_crlc     = m_data.GetU16(&offset); // Relocations
302             m_dos_header.e_cparhdr  = m_data.GetU16(&offset); // Size of header in paragraphs
303             m_dos_header.e_minalloc = m_data.GetU16(&offset); // Minimum extra paragraphs needed
304             m_dos_header.e_maxalloc = m_data.GetU16(&offset); // Maximum extra paragraphs needed
305             m_dos_header.e_ss       = m_data.GetU16(&offset); // Initial (relative) SS value
306             m_dos_header.e_sp       = m_data.GetU16(&offset); // Initial SP value
307             m_dos_header.e_csum     = m_data.GetU16(&offset); // Checksum
308             m_dos_header.e_ip       = m_data.GetU16(&offset); // Initial IP value
309             m_dos_header.e_cs       = m_data.GetU16(&offset); // Initial (relative) CS value
310             m_dos_header.e_lfarlc   = m_data.GetU16(&offset); // File address of relocation table
311             m_dos_header.e_ovno     = m_data.GetU16(&offset); // Overlay number
312 
313             m_dos_header.e_res[0]   = m_data.GetU16(&offset); // Reserved words
314             m_dos_header.e_res[1]   = m_data.GetU16(&offset); // Reserved words
315             m_dos_header.e_res[2]   = m_data.GetU16(&offset); // Reserved words
316             m_dos_header.e_res[3]   = m_data.GetU16(&offset); // Reserved words
317 
318             m_dos_header.e_oemid    = m_data.GetU16(&offset); // OEM identifier (for e_oeminfo)
319             m_dos_header.e_oeminfo  = m_data.GetU16(&offset); // OEM information; e_oemid specific
320             m_dos_header.e_res2[0]  = m_data.GetU16(&offset); // Reserved words
321             m_dos_header.e_res2[1]  = m_data.GetU16(&offset); // Reserved words
322             m_dos_header.e_res2[2]  = m_data.GetU16(&offset); // Reserved words
323             m_dos_header.e_res2[3]  = m_data.GetU16(&offset); // Reserved words
324             m_dos_header.e_res2[4]  = m_data.GetU16(&offset); // Reserved words
325             m_dos_header.e_res2[5]  = m_data.GetU16(&offset); // Reserved words
326             m_dos_header.e_res2[6]  = m_data.GetU16(&offset); // Reserved words
327             m_dos_header.e_res2[7]  = m_data.GetU16(&offset); // Reserved words
328             m_dos_header.e_res2[8]  = m_data.GetU16(&offset); // Reserved words
329             m_dos_header.e_res2[9]  = m_data.GetU16(&offset); // Reserved words
330 
331             m_dos_header.e_lfanew   = m_data.GetU32(&offset); // File address of new exe header
332         }
333     }
334     if (!success)
335         memset(&m_dos_header, 0, sizeof(m_dos_header));
336     return success;
337 }
338 
339 
340 //----------------------------------------------------------------------
341 // ParserCOFFHeader
342 //----------------------------------------------------------------------
343 bool
344 ObjectFilePECOFF::ParseCOFFHeader(lldb::offset_t *offset_ptr)
345 {
346     bool success = m_data.ValidOffsetForDataOfSize (*offset_ptr, sizeof(m_coff_header));
347     if (success)
348     {
349         m_coff_header.machine   = m_data.GetU16(offset_ptr);
350         m_coff_header.nsects    = m_data.GetU16(offset_ptr);
351         m_coff_header.modtime   = m_data.GetU32(offset_ptr);
352         m_coff_header.symoff    = m_data.GetU32(offset_ptr);
353         m_coff_header.nsyms     = m_data.GetU32(offset_ptr);
354         m_coff_header.hdrsize   = m_data.GetU16(offset_ptr);
355         m_coff_header.flags     = m_data.GetU16(offset_ptr);
356     }
357     if (!success)
358         memset(&m_coff_header, 0, sizeof(m_coff_header));
359     return success;
360 }
361 
362 bool
363 ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr)
364 {
365     bool success = false;
366     const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
367     if (*offset_ptr < end_offset)
368     {
369         success = true;
370         m_coff_header_opt.magic                         = m_data.GetU16(offset_ptr);
371         m_coff_header_opt.major_linker_version          = m_data.GetU8 (offset_ptr);
372         m_coff_header_opt.minor_linker_version          = m_data.GetU8 (offset_ptr);
373         m_coff_header_opt.code_size                     = m_data.GetU32(offset_ptr);
374         m_coff_header_opt.data_size                     = m_data.GetU32(offset_ptr);
375         m_coff_header_opt.bss_size                      = m_data.GetU32(offset_ptr);
376         m_coff_header_opt.entry                         = m_data.GetU32(offset_ptr);
377         m_coff_header_opt.code_offset                   = m_data.GetU32(offset_ptr);
378 
379         const uint32_t addr_byte_size = GetAddressByteSize ();
380 
381         if (*offset_ptr < end_offset)
382         {
383             if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
384             {
385                 // PE32 only
386                 m_coff_header_opt.data_offset               = m_data.GetU32(offset_ptr);
387             }
388             else
389                 m_coff_header_opt.data_offset = 0;
390 
391             if (*offset_ptr < end_offset)
392             {
393                 m_coff_header_opt.image_base                    = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
394                 m_coff_header_opt.sect_alignment                = m_data.GetU32(offset_ptr);
395                 m_coff_header_opt.file_alignment                = m_data.GetU32(offset_ptr);
396                 m_coff_header_opt.major_os_system_version       = m_data.GetU16(offset_ptr);
397                 m_coff_header_opt.minor_os_system_version       = m_data.GetU16(offset_ptr);
398                 m_coff_header_opt.major_image_version           = m_data.GetU16(offset_ptr);
399                 m_coff_header_opt.minor_image_version           = m_data.GetU16(offset_ptr);
400                 m_coff_header_opt.major_subsystem_version       = m_data.GetU16(offset_ptr);
401                 m_coff_header_opt.minor_subsystem_version       = m_data.GetU16(offset_ptr);
402                 m_coff_header_opt.reserved1                     = m_data.GetU32(offset_ptr);
403                 m_coff_header_opt.image_size                    = m_data.GetU32(offset_ptr);
404                 m_coff_header_opt.header_size                   = m_data.GetU32(offset_ptr);
405                 m_coff_header_opt.checksum                      = m_data.GetU32(offset_ptr);
406                 m_coff_header_opt.subsystem                     = m_data.GetU16(offset_ptr);
407                 m_coff_header_opt.dll_flags                     = m_data.GetU16(offset_ptr);
408                 m_coff_header_opt.stack_reserve_size            = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
409                 m_coff_header_opt.stack_commit_size             = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
410                 m_coff_header_opt.heap_reserve_size             = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
411                 m_coff_header_opt.heap_commit_size              = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
412                 m_coff_header_opt.loader_flags                  = m_data.GetU32(offset_ptr);
413                 uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
414                 m_coff_header_opt.data_dirs.clear();
415                 m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
416                 uint32_t i;
417                 for (i=0; i<num_data_dir_entries; i++)
418                 {
419                     m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
420                     m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
421                 }
422             }
423         }
424     }
425     // Make sure we are on track for section data which follows
426     *offset_ptr = end_offset;
427     return success;
428 }
429 
430 
431 //----------------------------------------------------------------------
432 // ParseSectionHeaders
433 //----------------------------------------------------------------------
434 bool
435 ObjectFilePECOFF::ParseSectionHeaders (uint32_t section_header_data_offset)
436 {
437     const uint32_t nsects = m_coff_header.nsects;
438     m_sect_headers.clear();
439 
440     if (nsects > 0)
441     {
442         const uint32_t addr_byte_size = GetAddressByteSize ();
443         const size_t section_header_byte_size = nsects * sizeof(section_header_t);
444         DataBufferSP section_header_data_sp(m_file.ReadFileContents (section_header_data_offset, section_header_byte_size));
445         DataExtractor section_header_data (section_header_data_sp, GetByteOrder(), addr_byte_size);
446 
447         lldb::offset_t offset = 0;
448         if (section_header_data.ValidOffsetForDataOfSize (offset, section_header_byte_size))
449         {
450             m_sect_headers.resize(nsects);
451 
452             for (uint32_t idx = 0; idx<nsects; ++idx)
453             {
454                 const void *name_data = section_header_data.GetData(&offset, 8);
455                 if (name_data)
456                 {
457                     memcpy(m_sect_headers[idx].name, name_data, 8);
458                     m_sect_headers[idx].vmsize  = section_header_data.GetU32(&offset);
459                     m_sect_headers[idx].vmaddr  = section_header_data.GetU32(&offset);
460                     m_sect_headers[idx].size    = section_header_data.GetU32(&offset);
461                     m_sect_headers[idx].offset  = section_header_data.GetU32(&offset);
462                     m_sect_headers[idx].reloff  = section_header_data.GetU32(&offset);
463                     m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
464                     m_sect_headers[idx].nreloc  = section_header_data.GetU16(&offset);
465                     m_sect_headers[idx].nline   = section_header_data.GetU16(&offset);
466                     m_sect_headers[idx].flags   = section_header_data.GetU32(&offset);
467                 }
468             }
469         }
470     }
471 
472     return m_sect_headers.empty() == false;
473 }
474 
475 bool
476 ObjectFilePECOFF::GetSectionName(std::string& sect_name, const section_header_t& sect)
477 {
478     if (sect.name[0] == '/')
479     {
480         lldb::offset_t stroff = strtoul(&sect.name[1], NULL, 10);
481         lldb::offset_t string_file_offset = m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
482         const char *name = m_data.GetCStr (&string_file_offset);
483         if (name)
484         {
485             sect_name = name;
486             return true;
487         }
488 
489         return false;
490     }
491     sect_name = sect.name;
492     return true;
493 }
494 
495 //----------------------------------------------------------------------
496 // GetNListSymtab
497 //----------------------------------------------------------------------
498 Symtab *
499 ObjectFilePECOFF::GetSymtab()
500 {
501     ModuleSP module_sp(GetModule());
502     if (module_sp)
503     {
504         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
505         if (m_symtab_ap.get() == NULL)
506         {
507             SectionList *sect_list = GetSectionList();
508             m_symtab_ap.reset(new Symtab(this));
509             Mutex::Locker symtab_locker (m_symtab_ap->GetMutex());
510 
511             const uint32_t num_syms = m_coff_header.nsyms;
512 
513             if (num_syms > 0 && m_coff_header.symoff > 0)
514             {
515                 const uint32_t symbol_size = sizeof(section_header_t);
516                 const uint32_t addr_byte_size = GetAddressByteSize ();
517                 const size_t symbol_data_size = num_syms * symbol_size;
518                 // Include the 4 bytes string table size at the end of the symbols
519                 DataBufferSP symtab_data_sp(m_file.ReadFileContents (m_coff_header.symoff, symbol_data_size + 4));
520                 DataExtractor symtab_data (symtab_data_sp, GetByteOrder(), addr_byte_size);
521                 lldb::offset_t offset = symbol_data_size;
522                 const uint32_t strtab_size = symtab_data.GetU32 (&offset);
523                 DataBufferSP strtab_data_sp(m_file.ReadFileContents (m_coff_header.symoff + symbol_data_size + 4, strtab_size));
524                 DataExtractor strtab_data (strtab_data_sp, GetByteOrder(), addr_byte_size);
525 
526                 offset = 0;
527                 std::string symbol_name;
528                 Symbol *symbols = m_symtab_ap->Resize (num_syms);
529                 for (uint32_t i=0; i<num_syms; ++i)
530                 {
531                     coff_symbol_t symbol;
532                     const uint32_t symbol_offset = offset;
533                     const char *symbol_name_cstr = NULL;
534                     // If the first 4 bytes of the symbol string are zero, then we
535                     // it is followed by a 4 byte string table offset. Else these
536                     // 8 bytes contain the symbol name
537                     if (symtab_data.GetU32 (&offset) == 0)
538                     {
539                         // Long string that doesn't fit into the symbol table name,
540                         // so now we must read the 4 byte string table offset
541                         uint32_t strtab_offset = symtab_data.GetU32 (&offset);
542                         symbol_name_cstr = strtab_data.PeekCStr (strtab_offset);
543                         symbol_name.assign (symbol_name_cstr);
544                     }
545                     else
546                     {
547                         // Short string that fits into the symbol table name which is 8 bytes
548                         offset += sizeof(symbol.name) - 4; // Skip remaining
549                         symbol_name_cstr = symtab_data.PeekCStr (symbol_offset);
550                         if (symbol_name_cstr == NULL)
551                             break;
552                         symbol_name.assign (symbol_name_cstr, sizeof(symbol.name));
553                     }
554                     symbol.value    = symtab_data.GetU32 (&offset);
555                     symbol.sect     = symtab_data.GetU16 (&offset);
556                     symbol.type     = symtab_data.GetU16 (&offset);
557                     symbol.storage  = symtab_data.GetU8  (&offset);
558                     symbol.naux     = symtab_data.GetU8  (&offset);
559                     Address symbol_addr(sect_list->GetSectionAtIndex(symbol.sect-1), symbol.value);
560                     symbols[i].GetMangled ().SetValue (ConstString(symbol_name.c_str()));
561                     symbols[i].GetAddress() = symbol_addr;
562 
563                     if (symbol.naux > 0)
564                         i += symbol.naux;
565                 }
566 
567             }
568         }
569     }
570     return m_symtab_ap.get();
571 
572 }
573 
574 SectionList *
575 ObjectFilePECOFF::GetSectionList()
576 {
577     ModuleSP module_sp(GetModule());
578     if (module_sp)
579     {
580         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
581         if (m_sections_ap.get() == NULL)
582         {
583             m_sections_ap.reset(new SectionList());
584             const uint32_t nsects = m_sect_headers.size();
585             ModuleSP module_sp (GetModule());
586             for (uint32_t idx = 0; idx<nsects; ++idx)
587             {
588                 std::string sect_name;
589                 GetSectionName (sect_name, m_sect_headers[idx]);
590                 ConstString const_sect_name (sect_name.c_str());
591                 static ConstString g_code_sect_name (".code");
592                 static ConstString g_CODE_sect_name ("CODE");
593                 static ConstString g_data_sect_name (".data");
594                 static ConstString g_DATA_sect_name ("DATA");
595                 static ConstString g_bss_sect_name (".bss");
596                 static ConstString g_BSS_sect_name ("BSS");
597                 static ConstString g_debug_sect_name (".debug");
598                 static ConstString g_reloc_sect_name (".reloc");
599                 static ConstString g_stab_sect_name (".stab");
600                 static ConstString g_stabstr_sect_name (".stabstr");
601                 SectionType section_type = eSectionTypeOther;
602                 if (m_sect_headers[idx].flags & IMAGE_SCN_CNT_CODE &&
603                     ((const_sect_name == g_code_sect_name) || (const_sect_name == g_CODE_sect_name)))
604                 {
605                     section_type = eSectionTypeCode;
606                 }
607                 else if (m_sect_headers[idx].flags & IMAGE_SCN_CNT_INITIALIZED_DATA &&
608                          ((const_sect_name == g_data_sect_name) || (const_sect_name == g_DATA_sect_name)))
609                 {
610                     section_type = eSectionTypeData;
611                 }
612                 else if (m_sect_headers[idx].flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
613                          ((const_sect_name == g_bss_sect_name) || (const_sect_name == g_BSS_sect_name)))
614                 {
615                     if (m_sect_headers[idx].size == 0)
616                         section_type = eSectionTypeZeroFill;
617                     else
618                         section_type = eSectionTypeData;
619                 }
620                 else if (const_sect_name == g_debug_sect_name)
621                 {
622                     section_type = eSectionTypeDebug;
623                 }
624                 else if (const_sect_name == g_stabstr_sect_name)
625                 {
626                     section_type = eSectionTypeDataCString;
627                 }
628                 else if (const_sect_name == g_reloc_sect_name)
629                 {
630                     section_type = eSectionTypeOther;
631                 }
632                 else if (m_sect_headers[idx].flags & IMAGE_SCN_CNT_CODE)
633                 {
634                     section_type = eSectionTypeCode;
635                 }
636                 else if (m_sect_headers[idx].flags & IMAGE_SCN_CNT_INITIALIZED_DATA)
637                 {
638                     section_type = eSectionTypeData;
639                 }
640                 else if (m_sect_headers[idx].flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
641                 {
642                     if (m_sect_headers[idx].size == 0)
643                         section_type = eSectionTypeZeroFill;
644                     else
645                         section_type = eSectionTypeData;
646                 }
647 
648                 // Use a segment ID of the segment index shifted left by 8 so they
649                 // never conflict with any of the sections.
650                 SectionSP section_sp (new Section (module_sp,                    // Module to which this section belongs
651                                                    idx + 1,                      // Section ID is the 1 based segment index shifted right by 8 bits as not to collide with any of the 256 section IDs that are possible
652                                                    const_sect_name,              // Name of this section
653                                                    section_type,                    // This section is a container of other sections.
654                                                    m_sect_headers[idx].vmaddr,   // File VM address == addresses as they are found in the object file
655                                                    m_sect_headers[idx].vmsize,   // VM size in bytes of this section
656                                                    m_sect_headers[idx].offset,   // Offset to the data for this section in the file
657                                                    m_sect_headers[idx].size,     // Size in bytes of this section as found in the the file
658                                                    m_sect_headers[idx].flags));  // Flags for this section
659 
660                 //section_sp->SetIsEncrypted (segment_is_encrypted);
661 
662                 m_sections_ap->AddSection(section_sp);
663             }
664 
665             m_sections_ap->Finalize(); // Now that we're done adding sections, finalize to build fast-lookup caches
666         }
667     }
668     return m_sections_ap.get();
669 }
670 
671 bool
672 ObjectFilePECOFF::GetUUID (UUID* uuid)
673 {
674     return false;
675 }
676 
677 uint32_t
678 ObjectFilePECOFF::GetDependentModules (FileSpecList& files)
679 {
680     return 0;
681 }
682 
683 
684 //----------------------------------------------------------------------
685 // Dump
686 //
687 // Dump the specifics of the runtime file container (such as any headers
688 // segments, sections, etc).
689 //----------------------------------------------------------------------
690 void
691 ObjectFilePECOFF::Dump(Stream *s)
692 {
693     ModuleSP module_sp(GetModule());
694     if (module_sp)
695     {
696         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
697         s->Printf("%p: ", this);
698         s->Indent();
699         s->PutCString("ObjectFilePECOFF");
700 
701         ArchSpec header_arch;
702         GetArchitecture (header_arch);
703 
704         *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n";
705 
706         if (m_sections_ap.get())
707             m_sections_ap->Dump(s, NULL, true, UINT32_MAX);
708 
709         if (m_symtab_ap.get())
710             m_symtab_ap->Dump(s, NULL, eSortOrderNone);
711 
712         if (m_dos_header.e_magic)
713             DumpDOSHeader (s, m_dos_header);
714         if (m_coff_header.machine)
715         {
716             DumpCOFFHeader (s, m_coff_header);
717             if (m_coff_header.hdrsize)
718                 DumpOptCOFFHeader (s, m_coff_header_opt);
719         }
720         s->EOL();
721         DumpSectionHeaders(s);
722         s->EOL();
723     }
724 }
725 
726 //----------------------------------------------------------------------
727 // DumpDOSHeader
728 //
729 // Dump the MS-DOS header to the specified output stream
730 //----------------------------------------------------------------------
731 void
732 ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t& header)
733 {
734     s->PutCString ("MSDOS Header\n");
735     s->Printf ("  e_magic    = 0x%4.4x\n", header.e_magic);
736     s->Printf ("  e_cblp     = 0x%4.4x\n", header.e_cblp);
737     s->Printf ("  e_cp       = 0x%4.4x\n", header.e_cp);
738     s->Printf ("  e_crlc     = 0x%4.4x\n", header.e_crlc);
739     s->Printf ("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
740     s->Printf ("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
741     s->Printf ("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
742     s->Printf ("  e_ss       = 0x%4.4x\n", header.e_ss);
743     s->Printf ("  e_sp       = 0x%4.4x\n", header.e_sp);
744     s->Printf ("  e_csum     = 0x%4.4x\n", header.e_csum);
745     s->Printf ("  e_ip       = 0x%4.4x\n", header.e_ip);
746     s->Printf ("  e_cs       = 0x%4.4x\n", header.e_cs);
747     s->Printf ("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
748     s->Printf ("  e_ovno     = 0x%4.4x\n", header.e_ovno);
749     s->Printf ("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
750                header.e_res[0],
751                header.e_res[1],
752                header.e_res[2],
753                header.e_res[3]);
754     s->Printf ("  e_oemid    = 0x%4.4x\n", header.e_oemid);
755     s->Printf ("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
756     s->Printf ("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
757                header.e_res2[0],
758                header.e_res2[1],
759                header.e_res2[2],
760                header.e_res2[3],
761                header.e_res2[4],
762                header.e_res2[5],
763                header.e_res2[6],
764                header.e_res2[7],
765                header.e_res2[8],
766                header.e_res2[9]);
767     s->Printf ("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
768 }
769 
770 //----------------------------------------------------------------------
771 // DumpCOFFHeader
772 //
773 // Dump the COFF header to the specified output stream
774 //----------------------------------------------------------------------
775 void
776 ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t& header)
777 {
778     s->PutCString ("COFF Header\n");
779     s->Printf ("  machine = 0x%4.4x\n", header.machine);
780     s->Printf ("  nsects  = 0x%4.4x\n", header.nsects);
781     s->Printf ("  modtime = 0x%8.8x\n", header.modtime);
782     s->Printf ("  symoff  = 0x%8.8x\n", header.symoff);
783     s->Printf ("  nsyms   = 0x%8.8x\n", header.nsyms);
784     s->Printf ("  hdrsize = 0x%4.4x\n", header.hdrsize);
785 }
786 
787 //----------------------------------------------------------------------
788 // DumpOptCOFFHeader
789 //
790 // Dump the optional COFF header to the specified output stream
791 //----------------------------------------------------------------------
792 void
793 ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s, const coff_opt_header_t& header)
794 {
795     s->PutCString ("Optional COFF Header\n");
796     s->Printf ("  magic                   = 0x%4.4x\n", header.magic);
797     s->Printf ("  major_linker_version    = 0x%2.2x\n", header.major_linker_version);
798     s->Printf ("  minor_linker_version    = 0x%2.2x\n", header.minor_linker_version);
799     s->Printf ("  code_size               = 0x%8.8x\n", header.code_size);
800     s->Printf ("  data_size               = 0x%8.8x\n", header.data_size);
801     s->Printf ("  bss_size                = 0x%8.8x\n", header.bss_size);
802     s->Printf ("  entry                   = 0x%8.8x\n", header.entry);
803     s->Printf ("  code_offset             = 0x%8.8x\n", header.code_offset);
804     s->Printf ("  data_offset             = 0x%8.8x\n", header.data_offset);
805     s->Printf ("  image_base              = 0x%16.16" PRIx64 "\n", header.image_base);
806     s->Printf ("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
807     s->Printf ("  file_alignment          = 0x%8.8x\n", header.file_alignment);
808     s->Printf ("  major_os_system_version = 0x%4.4x\n", header.major_os_system_version);
809     s->Printf ("  minor_os_system_version = 0x%4.4x\n", header.minor_os_system_version);
810     s->Printf ("  major_image_version     = 0x%4.4x\n", header.major_image_version);
811     s->Printf ("  minor_image_version     = 0x%4.4x\n", header.minor_image_version);
812     s->Printf ("  major_subsystem_version = 0x%4.4x\n", header.major_subsystem_version);
813     s->Printf ("  minor_subsystem_version = 0x%4.4x\n", header.minor_subsystem_version);
814     s->Printf ("  reserved1               = 0x%8.8x\n", header.reserved1);
815     s->Printf ("  image_size              = 0x%8.8x\n", header.image_size);
816     s->Printf ("  header_size             = 0x%8.8x\n", header.header_size);
817     s->Printf ("  checksum                = 0x%8.8x\n", header.checksum);
818     s->Printf ("  subsystem               = 0x%4.4x\n", header.subsystem);
819     s->Printf ("  dll_flags               = 0x%4.4x\n", header.dll_flags);
820     s->Printf ("  stack_reserve_size      = 0x%16.16" PRIx64 "\n", header.stack_reserve_size);
821     s->Printf ("  stack_commit_size       = 0x%16.16" PRIx64 "\n", header.stack_commit_size);
822     s->Printf ("  heap_reserve_size       = 0x%16.16" PRIx64 "\n", header.heap_reserve_size);
823     s->Printf ("  heap_commit_size        = 0x%16.16" PRIx64 "\n", header.heap_commit_size);
824     s->Printf ("  loader_flags            = 0x%8.8x\n", header.loader_flags);
825     s->Printf ("  num_data_dir_entries    = 0x%8.8zx\n", header.data_dirs.size());
826     uint32_t i;
827     for (i=0; i<header.data_dirs.size(); i++)
828     {
829         s->Printf ("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n",
830                    i,
831                    header.data_dirs[i].vmaddr,
832                    header.data_dirs[i].vmsize);
833     }
834 }
835 //----------------------------------------------------------------------
836 // DumpSectionHeader
837 //
838 // Dump a single ELF section header to the specified output stream
839 //----------------------------------------------------------------------
840 void
841 ObjectFilePECOFF::DumpSectionHeader(Stream *s, const section_header_t& sh)
842 {
843     std::string name;
844     GetSectionName(name, sh);
845     s->Printf ("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x 0x%4.4x 0x%8.8x\n",
846                name.c_str(),
847                sh.vmaddr,
848                sh.vmsize,
849                sh.offset,
850                sh.size,
851                sh.reloff,
852                sh.lineoff,
853                sh.nreloc,
854                sh.nline,
855                sh.flags);
856 }
857 
858 
859 //----------------------------------------------------------------------
860 // DumpSectionHeaders
861 //
862 // Dump all of the ELF section header to the specified output stream
863 //----------------------------------------------------------------------
864 void
865 ObjectFilePECOFF::DumpSectionHeaders(Stream *s)
866 {
867 
868     s->PutCString ("Section Headers\n");
869     s->PutCString ("IDX  name             vm addr    vm size    file off   file size  reloc off  line off   nreloc nline  flags\n");
870     s->PutCString ("==== ---------------- ---------- ---------- ---------- ---------- ---------- ---------- ------ ------ ----------\n");
871 
872     uint32_t idx = 0;
873     SectionHeaderCollIter pos, end = m_sect_headers.end();
874 
875     for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx)
876     {
877         s->Printf ("[%2u] ", idx);
878         ObjectFilePECOFF::DumpSectionHeader(s, *pos);
879     }
880 }
881 
882 static bool
883 COFFMachineToMachCPU (uint16_t machine, ArchSpec &arch)
884 {
885     switch (machine)
886     {
887         case IMAGE_FILE_MACHINE_AMD64:
888         case IMAGE_FILE_MACHINE_IA64:
889             arch.SetArchitecture (eArchTypeMachO,
890                                   llvm::MachO::CPUTypeX86_64,
891                                   llvm::MachO::CPUSubType_X86_64_ALL);
892             return true;
893 
894         case IMAGE_FILE_MACHINE_I386:
895             arch.SetArchitecture (eArchTypeMachO,
896                                   llvm::MachO::CPUTypeI386,
897                                   llvm::MachO::CPUSubType_I386_ALL);
898             return true;
899 
900         case IMAGE_FILE_MACHINE_POWERPC:
901         case IMAGE_FILE_MACHINE_POWERPCFP:
902             arch.SetArchitecture (eArchTypeMachO,
903                                   llvm::MachO::CPUTypePowerPC,
904                                   llvm::MachO::CPUSubType_POWERPC_ALL);
905             return true;
906         case IMAGE_FILE_MACHINE_ARM:
907         case IMAGE_FILE_MACHINE_THUMB:
908             arch.SetArchitecture (eArchTypeMachO,
909                                   llvm::MachO::CPUTypeARM,
910                                   llvm::MachO::CPUSubType_ARM_V7);
911             return true;
912     }
913     return false;
914 }
915 bool
916 ObjectFilePECOFF::GetArchitecture (ArchSpec &arch)
917 {
918     // For index zero return our cpu type
919     return COFFMachineToMachCPU (m_coff_header.machine, arch);
920 }
921 
922 ObjectFile::Type
923 ObjectFilePECOFF::CalculateType()
924 {
925     if (m_coff_header.machine != 0)
926     {
927         if ((m_coff_header.flags & IMAGE_FILE_DLL) == 0)
928             return eTypeExecutable;
929         else
930             return eTypeSharedLibrary;
931     }
932     return eTypeExecutable;
933 }
934 
935 ObjectFile::Strata
936 ObjectFilePECOFF::CalculateStrata()
937 {
938     return eStrataUser;
939 }
940 //------------------------------------------------------------------
941 // PluginInterface protocol
942 //------------------------------------------------------------------
943 const char *
944 ObjectFilePECOFF::GetPluginName()
945 {
946     return "ObjectFilePECOFF";
947 }
948 
949 const char *
950 ObjectFilePECOFF::GetShortPluginName()
951 {
952     return GetPluginNameStatic();
953 }
954 
955 uint32_t
956 ObjectFilePECOFF::GetPluginVersion()
957 {
958     return 1;
959 }
960 
961