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/COFF.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/ModuleSpec.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/StreamFile.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Core/Timer.h"
25 #include "lldb/Core/UUID.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Target/SectionLoadList.h"
28 #include "lldb/Target/Target.h"
29 
30 #define IMAGE_DOS_SIGNATURE             0x5A4D      // MZ
31 #define IMAGE_NT_SIGNATURE              0x00004550  // PE00
32 #define OPT_HEADER_MAGIC_PE32           0x010b
33 #define OPT_HEADER_MAGIC_PE32_PLUS      0x020b
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 void
39 ObjectFilePECOFF::Initialize()
40 {
41     PluginManager::RegisterPlugin (GetPluginNameStatic(),
42                                    GetPluginDescriptionStatic(),
43                                    CreateInstance,
44                                    CreateMemoryInstance,
45                                    GetModuleSpecifications);
46 }
47 
48 void
49 ObjectFilePECOFF::Terminate()
50 {
51     PluginManager::UnregisterPlugin (CreateInstance);
52 }
53 
54 
55 lldb_private::ConstString
56 ObjectFilePECOFF::GetPluginNameStatic()
57 {
58     static ConstString g_name("pe-coff");
59     return g_name;
60 }
61 
62 const char *
63 ObjectFilePECOFF::GetPluginDescriptionStatic()
64 {
65     return "Portable Executable and Common Object File Format object file reader (32 and 64 bit)";
66 }
67 
68 
69 ObjectFile *
70 ObjectFilePECOFF::CreateInstance (const lldb::ModuleSP &module_sp,
71                                   DataBufferSP& data_sp,
72                                   lldb::offset_t data_offset,
73                                   const lldb_private::FileSpec* file,
74                                   lldb::offset_t file_offset,
75                                   lldb::offset_t length)
76 {
77     if (!data_sp)
78     {
79         data_sp = file->MemoryMapFileContentsIfLocal(file_offset, length);
80         data_offset = 0;
81     }
82 
83     if (ObjectFilePECOFF::MagicBytesMatch(data_sp))
84     {
85         // Update the data to contain the entire file if it doesn't already
86         if (data_sp->GetByteSize() < length)
87             data_sp = file->MemoryMapFileContentsIfLocal(file_offset, length);
88         std::unique_ptr<ObjectFile> objfile_ap(new ObjectFilePECOFF (module_sp, data_sp, data_offset, file, file_offset, length));
89         if (objfile_ap.get() && objfile_ap->ParseHeader())
90             return objfile_ap.release();
91     }
92     return NULL;
93 }
94 
95 ObjectFile *
96 ObjectFilePECOFF::CreateMemoryInstance (const lldb::ModuleSP &module_sp,
97                                         lldb::DataBufferSP& data_sp,
98                                         const lldb::ProcessSP &process_sp,
99                                         lldb::addr_t header_addr)
100 {
101     return NULL;
102 }
103 
104 size_t
105 ObjectFilePECOFF::GetModuleSpecifications (const lldb_private::FileSpec& file,
106                                            lldb::DataBufferSP& data_sp,
107                                            lldb::offset_t data_offset,
108                                            lldb::offset_t file_offset,
109                                            lldb::offset_t length,
110                                            lldb_private::ModuleSpecList &specs)
111 {
112     const size_t initial_count = specs.GetSize();
113 
114     if (ObjectFilePECOFF::MagicBytesMatch(data_sp))
115     {
116         DataExtractor data;
117         data.SetData(data_sp, data_offset, length);
118         data.SetByteOrder(eByteOrderLittle);
119 
120         dos_header_t dos_header;
121         coff_header_t coff_header;
122 
123         if (ParseDOSHeader(data, dos_header))
124         {
125             lldb::offset_t offset = dos_header.e_lfanew;
126             uint32_t pe_signature = data.GetU32(&offset);
127             if (pe_signature != IMAGE_NT_SIGNATURE)
128                 return false;
129             if (ParseCOFFHeader(data, &offset, coff_header))
130             {
131                 ArchSpec spec;
132                 if (coff_header.machine == MachineAmd64)
133                 {
134                     spec.SetTriple("x86_64-pc-windows");
135                     specs.Append(ModuleSpec(file, spec));
136                 }
137                 else if (coff_header.machine == MachineX86)
138                 {
139                     spec.SetTriple("i386-pc-windows");
140                     specs.Append(ModuleSpec(file, spec));
141                     spec.SetTriple("i686-pc-windows");
142                     specs.Append(ModuleSpec(file, spec));
143                 }
144             }
145         }
146     }
147 
148     return specs.GetSize() - initial_count;
149 }
150 
151 
152 bool
153 ObjectFilePECOFF::MagicBytesMatch (DataBufferSP& data_sp)
154 {
155     DataExtractor data(data_sp, eByteOrderLittle, 4);
156     lldb::offset_t offset = 0;
157     uint16_t magic = data.GetU16 (&offset);
158     return magic == IMAGE_DOS_SIGNATURE;
159 }
160 
161 
162 ObjectFilePECOFF::ObjectFilePECOFF (const lldb::ModuleSP &module_sp,
163                                     DataBufferSP& data_sp,
164                                     lldb::offset_t data_offset,
165                                     const FileSpec* file,
166                                     lldb::offset_t file_offset,
167                                     lldb::offset_t length) :
168     ObjectFile (module_sp, file, file_offset, length, data_sp, data_offset),
169     m_dos_header (),
170     m_coff_header (),
171     m_coff_header_opt (),
172     m_sect_headers ()
173 {
174     ::memset (&m_dos_header, 0, sizeof(m_dos_header));
175     ::memset (&m_coff_header, 0, sizeof(m_coff_header));
176     ::memset (&m_coff_header_opt, 0, sizeof(m_coff_header_opt));
177 }
178 
179 
180 ObjectFilePECOFF::~ObjectFilePECOFF()
181 {
182 }
183 
184 
185 bool
186 ObjectFilePECOFF::ParseHeader ()
187 {
188     ModuleSP module_sp(GetModule());
189     if (module_sp)
190     {
191         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
192         m_sect_headers.clear();
193         m_data.SetByteOrder (eByteOrderLittle);
194         lldb::offset_t offset = 0;
195 
196         if (ParseDOSHeader(m_data, m_dos_header))
197         {
198             offset = m_dos_header.e_lfanew;
199             uint32_t pe_signature = m_data.GetU32 (&offset);
200             if (pe_signature != IMAGE_NT_SIGNATURE)
201                 return false;
202             if (ParseCOFFHeader(m_data, &offset, m_coff_header))
203             {
204                 if (m_coff_header.hdrsize > 0)
205                     ParseCOFFOptionalHeader(&offset);
206                 ParseSectionHeaders (offset);
207             }
208             return true;
209         }
210     }
211     return false;
212 }
213 
214 bool
215 ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value, bool value_is_offset)
216 {
217     bool changed = false;
218     ModuleSP module_sp = GetModule();
219     if (module_sp)
220     {
221         size_t num_loaded_sections = 0;
222         SectionList *section_list = GetSectionList ();
223         if (section_list)
224         {
225             if (!value_is_offset)
226             {
227                 value -= m_image_base;
228             }
229 
230             const size_t num_sections = section_list->GetSize();
231             size_t sect_idx = 0;
232 
233             for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
234             {
235                 // Iterate through the object file sections to find all
236                 // of the sections that have SHF_ALLOC in their flag bits.
237                 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
238                 if (section_sp && !section_sp->IsThreadSpecific())
239                 {
240                     if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + value))
241                         ++num_loaded_sections;
242                 }
243             }
244             changed = num_loaded_sections > 0;
245         }
246     }
247     return changed;
248 }
249 
250 
251 ByteOrder
252 ObjectFilePECOFF::GetByteOrder () const
253 {
254     return eByteOrderLittle;
255 }
256 
257 bool
258 ObjectFilePECOFF::IsExecutable() const
259 {
260     return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
261 }
262 
263 uint32_t
264 ObjectFilePECOFF::GetAddressByteSize () const
265 {
266     if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
267         return 8;
268     else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
269         return 4;
270     return 4;
271 }
272 
273 //----------------------------------------------------------------------
274 // NeedsEndianSwap
275 //
276 // Return true if an endian swap needs to occur when extracting data
277 // from this file.
278 //----------------------------------------------------------------------
279 bool
280 ObjectFilePECOFF::NeedsEndianSwap() const
281 {
282 #if defined(__LITTLE_ENDIAN__)
283     return false;
284 #else
285     return true;
286 #endif
287 }
288 //----------------------------------------------------------------------
289 // ParseDOSHeader
290 //----------------------------------------------------------------------
291 bool
292 ObjectFilePECOFF::ParseDOSHeader (DataExtractor &data, dos_header_t &dos_header)
293 {
294     bool success = false;
295     lldb::offset_t offset = 0;
296     success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
297 
298     if (success)
299     {
300         dos_header.e_magic = data.GetU16(&offset); // Magic number
301         success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
302 
303         if (success)
304         {
305             dos_header.e_cblp     = data.GetU16(&offset); // Bytes on last page of file
306             dos_header.e_cp       = data.GetU16(&offset); // Pages in file
307             dos_header.e_crlc     = data.GetU16(&offset); // Relocations
308             dos_header.e_cparhdr  = data.GetU16(&offset); // Size of header in paragraphs
309             dos_header.e_minalloc = data.GetU16(&offset); // Minimum extra paragraphs needed
310             dos_header.e_maxalloc = data.GetU16(&offset); // Maximum extra paragraphs needed
311             dos_header.e_ss       = data.GetU16(&offset); // Initial (relative) SS value
312             dos_header.e_sp       = data.GetU16(&offset); // Initial SP value
313             dos_header.e_csum     = data.GetU16(&offset); // Checksum
314             dos_header.e_ip       = data.GetU16(&offset); // Initial IP value
315             dos_header.e_cs       = data.GetU16(&offset); // Initial (relative) CS value
316             dos_header.e_lfarlc   = data.GetU16(&offset); // File address of relocation table
317             dos_header.e_ovno     = data.GetU16(&offset); // Overlay number
318 
319             dos_header.e_res[0]   = data.GetU16(&offset); // Reserved words
320             dos_header.e_res[1]   = data.GetU16(&offset); // Reserved words
321             dos_header.e_res[2]   = data.GetU16(&offset); // Reserved words
322             dos_header.e_res[3]   = data.GetU16(&offset); // Reserved words
323 
324             dos_header.e_oemid    = data.GetU16(&offset); // OEM identifier (for e_oeminfo)
325             dos_header.e_oeminfo  = data.GetU16(&offset); // OEM information; e_oemid specific
326             dos_header.e_res2[0]  = data.GetU16(&offset); // Reserved words
327             dos_header.e_res2[1]  = data.GetU16(&offset); // Reserved words
328             dos_header.e_res2[2]  = data.GetU16(&offset); // Reserved words
329             dos_header.e_res2[3]  = data.GetU16(&offset); // Reserved words
330             dos_header.e_res2[4]  = data.GetU16(&offset); // Reserved words
331             dos_header.e_res2[5]  = data.GetU16(&offset); // Reserved words
332             dos_header.e_res2[6]  = data.GetU16(&offset); // Reserved words
333             dos_header.e_res2[7]  = data.GetU16(&offset); // Reserved words
334             dos_header.e_res2[8]  = data.GetU16(&offset); // Reserved words
335             dos_header.e_res2[9]  = data.GetU16(&offset); // Reserved words
336 
337             dos_header.e_lfanew   = data.GetU32(&offset); // File address of new exe header
338         }
339     }
340     if (!success)
341         memset(&dos_header, 0, sizeof(dos_header));
342     return success;
343 }
344 
345 
346 //----------------------------------------------------------------------
347 // ParserCOFFHeader
348 //----------------------------------------------------------------------
349 bool
350 ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data, lldb::offset_t *offset_ptr, coff_header_t &coff_header)
351 {
352     bool success = data.ValidOffsetForDataOfSize (*offset_ptr, sizeof(coff_header));
353     if (success)
354     {
355         coff_header.machine   = data.GetU16(offset_ptr);
356         coff_header.nsects    = data.GetU16(offset_ptr);
357         coff_header.modtime   = data.GetU32(offset_ptr);
358         coff_header.symoff    = data.GetU32(offset_ptr);
359         coff_header.nsyms     = data.GetU32(offset_ptr);
360         coff_header.hdrsize   = data.GetU16(offset_ptr);
361         coff_header.flags     = data.GetU16(offset_ptr);
362     }
363     if (!success)
364         memset(&coff_header, 0, sizeof(coff_header));
365     return success;
366 }
367 
368 bool
369 ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr)
370 {
371     bool success = false;
372     const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
373     if (*offset_ptr < end_offset)
374     {
375         success = true;
376         m_coff_header_opt.magic                         = m_data.GetU16(offset_ptr);
377         m_coff_header_opt.major_linker_version          = m_data.GetU8 (offset_ptr);
378         m_coff_header_opt.minor_linker_version          = m_data.GetU8 (offset_ptr);
379         m_coff_header_opt.code_size                     = m_data.GetU32(offset_ptr);
380         m_coff_header_opt.data_size                     = m_data.GetU32(offset_ptr);
381         m_coff_header_opt.bss_size                      = m_data.GetU32(offset_ptr);
382         m_coff_header_opt.entry                         = m_data.GetU32(offset_ptr);
383         m_coff_header_opt.code_offset                   = m_data.GetU32(offset_ptr);
384 
385         const uint32_t addr_byte_size = GetAddressByteSize ();
386 
387         if (*offset_ptr < end_offset)
388         {
389             if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
390             {
391                 // PE32 only
392                 m_coff_header_opt.data_offset               = m_data.GetU32(offset_ptr);
393             }
394             else
395                 m_coff_header_opt.data_offset = 0;
396 
397             if (*offset_ptr < end_offset)
398             {
399                 m_coff_header_opt.image_base                    = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
400                 m_coff_header_opt.sect_alignment                = m_data.GetU32(offset_ptr);
401                 m_coff_header_opt.file_alignment                = m_data.GetU32(offset_ptr);
402                 m_coff_header_opt.major_os_system_version       = m_data.GetU16(offset_ptr);
403                 m_coff_header_opt.minor_os_system_version       = m_data.GetU16(offset_ptr);
404                 m_coff_header_opt.major_image_version           = m_data.GetU16(offset_ptr);
405                 m_coff_header_opt.minor_image_version           = m_data.GetU16(offset_ptr);
406                 m_coff_header_opt.major_subsystem_version       = m_data.GetU16(offset_ptr);
407                 m_coff_header_opt.minor_subsystem_version       = m_data.GetU16(offset_ptr);
408                 m_coff_header_opt.reserved1                     = m_data.GetU32(offset_ptr);
409                 m_coff_header_opt.image_size                    = m_data.GetU32(offset_ptr);
410                 m_coff_header_opt.header_size                   = m_data.GetU32(offset_ptr);
411                 m_coff_header_opt.checksum                      = m_data.GetU32(offset_ptr);
412                 m_coff_header_opt.subsystem                     = m_data.GetU16(offset_ptr);
413                 m_coff_header_opt.dll_flags                     = m_data.GetU16(offset_ptr);
414                 m_coff_header_opt.stack_reserve_size            = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
415                 m_coff_header_opt.stack_commit_size             = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
416                 m_coff_header_opt.heap_reserve_size             = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
417                 m_coff_header_opt.heap_commit_size              = m_data.GetMaxU64 (offset_ptr, addr_byte_size);
418                 m_coff_header_opt.loader_flags                  = m_data.GetU32(offset_ptr);
419                 uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
420                 m_coff_header_opt.data_dirs.clear();
421                 m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
422                 uint32_t i;
423                 for (i=0; i<num_data_dir_entries; i++)
424                 {
425                     m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
426                     m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
427                 }
428 
429                 m_file_offset = m_coff_header_opt.image_base;
430                 m_image_base = m_coff_header_opt.image_base;
431             }
432         }
433     }
434     // Make sure we are on track for section data which follows
435     *offset_ptr = end_offset;
436     return success;
437 }
438 
439 
440 //----------------------------------------------------------------------
441 // ParseSectionHeaders
442 //----------------------------------------------------------------------
443 bool
444 ObjectFilePECOFF::ParseSectionHeaders (uint32_t section_header_data_offset)
445 {
446     const uint32_t nsects = m_coff_header.nsects;
447     m_sect_headers.clear();
448 
449     if (nsects > 0)
450     {
451         const uint32_t addr_byte_size = GetAddressByteSize ();
452         const size_t section_header_byte_size = nsects * sizeof(section_header_t);
453         DataBufferSP section_header_data_sp(m_file.ReadFileContents (section_header_data_offset, section_header_byte_size));
454         DataExtractor section_header_data (section_header_data_sp, GetByteOrder(), addr_byte_size);
455 
456         lldb::offset_t offset = 0;
457         if (section_header_data.ValidOffsetForDataOfSize (offset, section_header_byte_size))
458         {
459             m_sect_headers.resize(nsects);
460 
461             for (uint32_t idx = 0; idx<nsects; ++idx)
462             {
463                 const void *name_data = section_header_data.GetData(&offset, 8);
464                 if (name_data)
465                 {
466                     memcpy(m_sect_headers[idx].name, name_data, 8);
467                     m_sect_headers[idx].vmsize  = section_header_data.GetU32(&offset);
468                     m_sect_headers[idx].vmaddr  = section_header_data.GetU32(&offset);
469                     m_sect_headers[idx].size    = section_header_data.GetU32(&offset);
470                     m_sect_headers[idx].offset  = section_header_data.GetU32(&offset);
471                     m_sect_headers[idx].reloff  = section_header_data.GetU32(&offset);
472                     m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
473                     m_sect_headers[idx].nreloc  = section_header_data.GetU16(&offset);
474                     m_sect_headers[idx].nline   = section_header_data.GetU16(&offset);
475                     m_sect_headers[idx].flags   = section_header_data.GetU32(&offset);
476                 }
477             }
478         }
479     }
480 
481     return m_sect_headers.empty() == false;
482 }
483 
484 bool
485 ObjectFilePECOFF::GetSectionName(std::string& sect_name, const section_header_t& sect)
486 {
487     if (sect.name[0] == '/')
488     {
489         lldb::offset_t stroff = strtoul(&sect.name[1], NULL, 10);
490         lldb::offset_t string_file_offset = m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
491         const char *name = m_data.GetCStr (&string_file_offset);
492         if (name)
493         {
494             sect_name = name;
495             return true;
496         }
497 
498         return false;
499     }
500     sect_name = sect.name;
501     return true;
502 }
503 
504 //----------------------------------------------------------------------
505 // GetNListSymtab
506 //----------------------------------------------------------------------
507 Symtab *
508 ObjectFilePECOFF::GetSymtab()
509 {
510     ModuleSP module_sp(GetModule());
511     if (module_sp)
512     {
513         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
514         if (m_symtab_ap.get() == NULL)
515         {
516             SectionList *sect_list = GetSectionList();
517             m_symtab_ap.reset(new Symtab(this));
518             Mutex::Locker symtab_locker (m_symtab_ap->GetMutex());
519 
520             const uint32_t num_syms = m_coff_header.nsyms;
521 
522             if (num_syms > 0 && m_coff_header.symoff > 0)
523             {
524                 const uint32_t symbol_size = 18;
525                 const uint32_t addr_byte_size = GetAddressByteSize ();
526                 const size_t symbol_data_size = num_syms * symbol_size;
527                 // Include the 4 bytes string table size at the end of the symbols
528                 DataBufferSP symtab_data_sp(m_file.ReadFileContents (m_coff_header.symoff, symbol_data_size + 4));
529                 DataExtractor symtab_data (symtab_data_sp, GetByteOrder(), addr_byte_size);
530                 lldb::offset_t offset = symbol_data_size;
531                 const uint32_t strtab_size = symtab_data.GetU32 (&offset);
532                 DataBufferSP strtab_data_sp(m_file.ReadFileContents (m_coff_header.symoff + symbol_data_size, strtab_size));
533                 DataExtractor strtab_data (strtab_data_sp, GetByteOrder(), addr_byte_size);
534 
535                 // First 4 bytes should be zeroed after strtab_size has been read,
536                 // because it is used as offset 0 to encode a NULL string.
537                 uint32_t* strtab_data_start = (uint32_t*)strtab_data_sp->GetBytes();
538                 strtab_data_start[0] = 0;
539 
540                 offset = 0;
541                 std::string symbol_name;
542                 Symbol *symbols = m_symtab_ap->Resize (num_syms);
543                 for (uint32_t i=0; i<num_syms; ++i)
544                 {
545                     coff_symbol_t symbol;
546                     const uint32_t symbol_offset = offset;
547                     const char *symbol_name_cstr = NULL;
548                     // If the first 4 bytes of the symbol string are zero, then we
549                     // it is followed by a 4 byte string table offset. Else these
550                     // 8 bytes contain the symbol name
551                     if (symtab_data.GetU32 (&offset) == 0)
552                     {
553                         // Long string that doesn't fit into the symbol table name,
554                         // so now we must read the 4 byte string table offset
555                         uint32_t strtab_offset = symtab_data.GetU32 (&offset);
556                         symbol_name_cstr = strtab_data.PeekCStr (strtab_offset);
557                         symbol_name.assign (symbol_name_cstr);
558                     }
559                     else
560                     {
561                         // Short string that fits into the symbol table name which is 8 bytes
562                         offset += sizeof(symbol.name) - 4; // Skip remaining
563                         symbol_name_cstr = symtab_data.PeekCStr (symbol_offset);
564                         if (symbol_name_cstr == NULL)
565                             break;
566                         symbol_name.assign (symbol_name_cstr, sizeof(symbol.name));
567                     }
568                     symbol.value    = symtab_data.GetU32 (&offset);
569                     symbol.sect     = symtab_data.GetU16 (&offset);
570                     symbol.type     = symtab_data.GetU16 (&offset);
571                     symbol.storage  = symtab_data.GetU8  (&offset);
572                     symbol.naux     = symtab_data.GetU8  (&offset);
573                     symbols[i].GetMangled ().SetValue (ConstString(symbol_name.c_str()));
574                     if ((int16_t)symbol.sect >= 1)
575                     {
576                         Address symbol_addr(sect_list->GetSectionAtIndex(symbol.sect-1), symbol.value);
577                         symbols[i].GetAddressRef() = symbol_addr;
578                     }
579 
580                     if (symbol.naux > 0)
581                     {
582                         i += symbol.naux;
583                         offset += symbol_size;
584                     }
585                 }
586 
587             }
588 
589             // Read export header
590             if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size()
591                 && m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 && m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0)
592             {
593                 export_directory_entry export_table;
594                 uint32_t data_start = m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
595                 Address address(m_coff_header_opt.image_base + data_start, sect_list);
596                 DataBufferSP symtab_data_sp(m_file.ReadFileContents(address.GetSection()->GetFileOffset() + address.GetOffset(), m_coff_header_opt.data_dirs[0].vmsize));
597                 DataExtractor symtab_data (symtab_data_sp, GetByteOrder(), GetAddressByteSize());
598                 lldb::offset_t offset = 0;
599 
600                 // Read export_table header
601                 export_table.characteristics = symtab_data.GetU32(&offset);
602                 export_table.time_date_stamp = symtab_data.GetU32(&offset);
603                 export_table.major_version = symtab_data.GetU16(&offset);
604                 export_table.minor_version = symtab_data.GetU16(&offset);
605                 export_table.name = symtab_data.GetU32(&offset);
606                 export_table.base = symtab_data.GetU32(&offset);
607                 export_table.number_of_functions = symtab_data.GetU32(&offset);
608                 export_table.number_of_names = symtab_data.GetU32(&offset);
609                 export_table.address_of_functions = symtab_data.GetU32(&offset);
610                 export_table.address_of_names = symtab_data.GetU32(&offset);
611                 export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
612 
613                 bool has_ordinal = export_table.address_of_name_ordinals != 0;
614 
615                 lldb::offset_t name_offset = export_table.address_of_names - data_start;
616                 lldb::offset_t name_ordinal_offset = export_table.address_of_name_ordinals - data_start;
617 
618                 Symbol *symbols = m_symtab_ap->Resize(export_table.number_of_names);
619 
620                 std::string symbol_name;
621 
622                 // Read each export table entry
623                 for (size_t i = 0; i < export_table.number_of_names; ++i)
624                 {
625                     uint32_t name_ordinal = has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
626                     uint32_t name_address = symtab_data.GetU32(&name_offset);
627 
628                     const char* symbol_name_cstr = symtab_data.PeekCStr(name_address - data_start);
629                     symbol_name.assign(symbol_name_cstr);
630 
631                     lldb::offset_t function_offset = export_table.address_of_functions - data_start + sizeof(uint32_t) * name_ordinal;
632                     uint32_t function_rva = symtab_data.GetU32(&function_offset);
633 
634                     Address symbol_addr(m_coff_header_opt.image_base + function_rva, sect_list);
635                     symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
636                     symbols[i].GetAddressRef() = symbol_addr;
637                     symbols[i].SetType(lldb::eSymbolTypeCode);
638                     symbols[i].SetDebug(true);
639                 }
640             }
641         }
642     }
643     return m_symtab_ap.get();
644 
645 }
646 
647 bool
648 ObjectFilePECOFF::IsStripped ()
649 {
650     // TODO: determine this for COFF
651     return false;
652 }
653 
654 
655 
656 void
657 ObjectFilePECOFF::CreateSections (SectionList &unified_section_list)
658 {
659     if (!m_sections_ap.get())
660     {
661         m_sections_ap.reset(new SectionList());
662 
663         ModuleSP module_sp(GetModule());
664         if (module_sp)
665         {
666             lldb_private::Mutex::Locker locker(module_sp->GetMutex());
667             const uint32_t nsects = m_sect_headers.size();
668             ModuleSP module_sp (GetModule());
669             for (uint32_t idx = 0; idx<nsects; ++idx)
670             {
671                 std::string sect_name;
672                 GetSectionName (sect_name, m_sect_headers[idx]);
673                 ConstString const_sect_name (sect_name.c_str());
674                 static ConstString g_code_sect_name (".code");
675                 static ConstString g_CODE_sect_name ("CODE");
676                 static ConstString g_data_sect_name (".data");
677                 static ConstString g_DATA_sect_name ("DATA");
678                 static ConstString g_bss_sect_name (".bss");
679                 static ConstString g_BSS_sect_name ("BSS");
680                 static ConstString g_debug_sect_name (".debug");
681                 static ConstString g_reloc_sect_name (".reloc");
682                 static ConstString g_stab_sect_name (".stab");
683                 static ConstString g_stabstr_sect_name (".stabstr");
684                 static ConstString g_sect_name_dwarf_debug_abbrev (".debug_abbrev");
685                 static ConstString g_sect_name_dwarf_debug_aranges (".debug_aranges");
686                 static ConstString g_sect_name_dwarf_debug_frame (".debug_frame");
687                 static ConstString g_sect_name_dwarf_debug_info (".debug_info");
688                 static ConstString g_sect_name_dwarf_debug_line (".debug_line");
689                 static ConstString g_sect_name_dwarf_debug_loc (".debug_loc");
690                 static ConstString g_sect_name_dwarf_debug_macinfo (".debug_macinfo");
691                 static ConstString g_sect_name_dwarf_debug_pubnames (".debug_pubnames");
692                 static ConstString g_sect_name_dwarf_debug_pubtypes (".debug_pubtypes");
693                 static ConstString g_sect_name_dwarf_debug_ranges (".debug_ranges");
694                 static ConstString g_sect_name_dwarf_debug_str (".debug_str");
695                 static ConstString g_sect_name_eh_frame (".eh_frame");
696                 SectionType section_type = eSectionTypeOther;
697                 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
698                     ((const_sect_name == g_code_sect_name) || (const_sect_name == g_CODE_sect_name)))
699                 {
700                     section_type = eSectionTypeCode;
701                 }
702                 else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
703                          ((const_sect_name == g_data_sect_name) || (const_sect_name == g_DATA_sect_name)))
704                 {
705                     section_type = eSectionTypeData;
706                 }
707                 else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
708                          ((const_sect_name == g_bss_sect_name) || (const_sect_name == g_BSS_sect_name)))
709                 {
710                     if (m_sect_headers[idx].size == 0)
711                         section_type = eSectionTypeZeroFill;
712                     else
713                         section_type = eSectionTypeData;
714                 }
715                 else if (const_sect_name == g_debug_sect_name)
716                 {
717                     section_type = eSectionTypeDebug;
718                 }
719                 else if (const_sect_name == g_stabstr_sect_name)
720                 {
721                     section_type = eSectionTypeDataCString;
722                 }
723                 else if (const_sect_name == g_reloc_sect_name)
724                 {
725                     section_type = eSectionTypeOther;
726                 }
727                 else if (const_sect_name == g_sect_name_dwarf_debug_abbrev)    section_type = eSectionTypeDWARFDebugAbbrev;
728                 else if (const_sect_name == g_sect_name_dwarf_debug_aranges)   section_type = eSectionTypeDWARFDebugAranges;
729                 else if (const_sect_name == g_sect_name_dwarf_debug_frame)     section_type = eSectionTypeDWARFDebugFrame;
730                 else if (const_sect_name == g_sect_name_dwarf_debug_info)      section_type = eSectionTypeDWARFDebugInfo;
731                 else if (const_sect_name == g_sect_name_dwarf_debug_line)      section_type = eSectionTypeDWARFDebugLine;
732                 else if (const_sect_name == g_sect_name_dwarf_debug_loc)       section_type = eSectionTypeDWARFDebugLoc;
733                 else if (const_sect_name == g_sect_name_dwarf_debug_macinfo)   section_type = eSectionTypeDWARFDebugMacInfo;
734                 else if (const_sect_name == g_sect_name_dwarf_debug_pubnames)  section_type = eSectionTypeDWARFDebugPubNames;
735                 else if (const_sect_name == g_sect_name_dwarf_debug_pubtypes)  section_type = eSectionTypeDWARFDebugPubTypes;
736                 else if (const_sect_name == g_sect_name_dwarf_debug_ranges)    section_type = eSectionTypeDWARFDebugRanges;
737                 else if (const_sect_name == g_sect_name_dwarf_debug_str)       section_type = eSectionTypeDWARFDebugStr;
738                 else if (const_sect_name == g_sect_name_eh_frame)              section_type = eSectionTypeEHFrame;
739                 else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE)
740                 {
741                     section_type = eSectionTypeCode;
742                 }
743                 else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
744                 {
745                     section_type = eSectionTypeData;
746                 }
747                 else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
748                 {
749                     if (m_sect_headers[idx].size == 0)
750                         section_type = eSectionTypeZeroFill;
751                     else
752                         section_type = eSectionTypeData;
753                 }
754 
755                 // Use a segment ID of the segment index shifted left by 8 so they
756                 // never conflict with any of the sections.
757                 SectionSP section_sp (new Section (module_sp,                    // Module to which this section belongs
758                                                    this,                         // Object file to which this section belongs
759                                                    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
760                                                    const_sect_name,              // Name of this section
761                                                    section_type,                 // This section is a container of other sections.
762                                                    m_coff_header_opt.image_base + m_sect_headers[idx].vmaddr,   // File VM address == addresses as they are found in the object file
763                                                    m_sect_headers[idx].vmsize,   // VM size in bytes of this section
764                                                    m_sect_headers[idx].offset,   // Offset to the data for this section in the file
765                                                    m_sect_headers[idx].size,     // Size in bytes of this section as found in the file
766                                                    m_coff_header_opt.sect_alignment, // Section alignment
767                                                    m_sect_headers[idx].flags));  // Flags for this section
768 
769                 //section_sp->SetIsEncrypted (segment_is_encrypted);
770 
771                 unified_section_list.AddSection(section_sp);
772                 m_sections_ap->AddSection (section_sp);
773             }
774         }
775     }
776 }
777 
778 bool
779 ObjectFilePECOFF::GetUUID (UUID* uuid)
780 {
781     return false;
782 }
783 
784 uint32_t
785 ObjectFilePECOFF::GetDependentModules (FileSpecList& files)
786 {
787     return 0;
788 }
789 
790 
791 //----------------------------------------------------------------------
792 // Dump
793 //
794 // Dump the specifics of the runtime file container (such as any headers
795 // segments, sections, etc).
796 //----------------------------------------------------------------------
797 void
798 ObjectFilePECOFF::Dump(Stream *s)
799 {
800     ModuleSP module_sp(GetModule());
801     if (module_sp)
802     {
803         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
804         s->Printf("%p: ", static_cast<void*>(this));
805         s->Indent();
806         s->PutCString("ObjectFilePECOFF");
807 
808         ArchSpec header_arch;
809         GetArchitecture (header_arch);
810 
811         *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n";
812 
813         SectionList *sections = GetSectionList();
814         if (sections)
815             sections->Dump(s, NULL, true, UINT32_MAX);
816 
817         if (m_symtab_ap.get())
818             m_symtab_ap->Dump(s, NULL, eSortOrderNone);
819 
820         if (m_dos_header.e_magic)
821             DumpDOSHeader (s, m_dos_header);
822         if (m_coff_header.machine)
823         {
824             DumpCOFFHeader (s, m_coff_header);
825             if (m_coff_header.hdrsize)
826                 DumpOptCOFFHeader (s, m_coff_header_opt);
827         }
828         s->EOL();
829         DumpSectionHeaders(s);
830         s->EOL();
831     }
832 }
833 
834 //----------------------------------------------------------------------
835 // DumpDOSHeader
836 //
837 // Dump the MS-DOS header to the specified output stream
838 //----------------------------------------------------------------------
839 void
840 ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t& header)
841 {
842     s->PutCString ("MSDOS Header\n");
843     s->Printf ("  e_magic    = 0x%4.4x\n", header.e_magic);
844     s->Printf ("  e_cblp     = 0x%4.4x\n", header.e_cblp);
845     s->Printf ("  e_cp       = 0x%4.4x\n", header.e_cp);
846     s->Printf ("  e_crlc     = 0x%4.4x\n", header.e_crlc);
847     s->Printf ("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
848     s->Printf ("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
849     s->Printf ("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
850     s->Printf ("  e_ss       = 0x%4.4x\n", header.e_ss);
851     s->Printf ("  e_sp       = 0x%4.4x\n", header.e_sp);
852     s->Printf ("  e_csum     = 0x%4.4x\n", header.e_csum);
853     s->Printf ("  e_ip       = 0x%4.4x\n", header.e_ip);
854     s->Printf ("  e_cs       = 0x%4.4x\n", header.e_cs);
855     s->Printf ("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
856     s->Printf ("  e_ovno     = 0x%4.4x\n", header.e_ovno);
857     s->Printf ("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
858                header.e_res[0],
859                header.e_res[1],
860                header.e_res[2],
861                header.e_res[3]);
862     s->Printf ("  e_oemid    = 0x%4.4x\n", header.e_oemid);
863     s->Printf ("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
864     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",
865                header.e_res2[0],
866                header.e_res2[1],
867                header.e_res2[2],
868                header.e_res2[3],
869                header.e_res2[4],
870                header.e_res2[5],
871                header.e_res2[6],
872                header.e_res2[7],
873                header.e_res2[8],
874                header.e_res2[9]);
875     s->Printf ("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
876 }
877 
878 //----------------------------------------------------------------------
879 // DumpCOFFHeader
880 //
881 // Dump the COFF header to the specified output stream
882 //----------------------------------------------------------------------
883 void
884 ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t& header)
885 {
886     s->PutCString ("COFF Header\n");
887     s->Printf ("  machine = 0x%4.4x\n", header.machine);
888     s->Printf ("  nsects  = 0x%4.4x\n", header.nsects);
889     s->Printf ("  modtime = 0x%8.8x\n", header.modtime);
890     s->Printf ("  symoff  = 0x%8.8x\n", header.symoff);
891     s->Printf ("  nsyms   = 0x%8.8x\n", header.nsyms);
892     s->Printf ("  hdrsize = 0x%4.4x\n", header.hdrsize);
893 }
894 
895 //----------------------------------------------------------------------
896 // DumpOptCOFFHeader
897 //
898 // Dump the optional COFF header to the specified output stream
899 //----------------------------------------------------------------------
900 void
901 ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s, const coff_opt_header_t& header)
902 {
903     s->PutCString ("Optional COFF Header\n");
904     s->Printf ("  magic                   = 0x%4.4x\n", header.magic);
905     s->Printf ("  major_linker_version    = 0x%2.2x\n", header.major_linker_version);
906     s->Printf ("  minor_linker_version    = 0x%2.2x\n", header.minor_linker_version);
907     s->Printf ("  code_size               = 0x%8.8x\n", header.code_size);
908     s->Printf ("  data_size               = 0x%8.8x\n", header.data_size);
909     s->Printf ("  bss_size                = 0x%8.8x\n", header.bss_size);
910     s->Printf ("  entry                   = 0x%8.8x\n", header.entry);
911     s->Printf ("  code_offset             = 0x%8.8x\n", header.code_offset);
912     s->Printf ("  data_offset             = 0x%8.8x\n", header.data_offset);
913     s->Printf ("  image_base              = 0x%16.16" PRIx64 "\n", header.image_base);
914     s->Printf ("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
915     s->Printf ("  file_alignment          = 0x%8.8x\n", header.file_alignment);
916     s->Printf ("  major_os_system_version = 0x%4.4x\n", header.major_os_system_version);
917     s->Printf ("  minor_os_system_version = 0x%4.4x\n", header.minor_os_system_version);
918     s->Printf ("  major_image_version     = 0x%4.4x\n", header.major_image_version);
919     s->Printf ("  minor_image_version     = 0x%4.4x\n", header.minor_image_version);
920     s->Printf ("  major_subsystem_version = 0x%4.4x\n", header.major_subsystem_version);
921     s->Printf ("  minor_subsystem_version = 0x%4.4x\n", header.minor_subsystem_version);
922     s->Printf ("  reserved1               = 0x%8.8x\n", header.reserved1);
923     s->Printf ("  image_size              = 0x%8.8x\n", header.image_size);
924     s->Printf ("  header_size             = 0x%8.8x\n", header.header_size);
925     s->Printf ("  checksum                = 0x%8.8x\n", header.checksum);
926     s->Printf ("  subsystem               = 0x%4.4x\n", header.subsystem);
927     s->Printf ("  dll_flags               = 0x%4.4x\n", header.dll_flags);
928     s->Printf ("  stack_reserve_size      = 0x%16.16" PRIx64 "\n", header.stack_reserve_size);
929     s->Printf ("  stack_commit_size       = 0x%16.16" PRIx64 "\n", header.stack_commit_size);
930     s->Printf ("  heap_reserve_size       = 0x%16.16" PRIx64 "\n", header.heap_reserve_size);
931     s->Printf ("  heap_commit_size        = 0x%16.16" PRIx64 "\n", header.heap_commit_size);
932     s->Printf ("  loader_flags            = 0x%8.8x\n", header.loader_flags);
933     s->Printf ("  num_data_dir_entries    = 0x%8.8x\n", (uint32_t)header.data_dirs.size());
934     uint32_t i;
935     for (i=0; i<header.data_dirs.size(); i++)
936     {
937         s->Printf ("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n",
938                    i,
939                    header.data_dirs[i].vmaddr,
940                    header.data_dirs[i].vmsize);
941     }
942 }
943 //----------------------------------------------------------------------
944 // DumpSectionHeader
945 //
946 // Dump a single ELF section header to the specified output stream
947 //----------------------------------------------------------------------
948 void
949 ObjectFilePECOFF::DumpSectionHeader(Stream *s, const section_header_t& sh)
950 {
951     std::string name;
952     GetSectionName(name, sh);
953     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",
954                name.c_str(),
955                sh.vmaddr,
956                sh.vmsize,
957                sh.offset,
958                sh.size,
959                sh.reloff,
960                sh.lineoff,
961                sh.nreloc,
962                sh.nline,
963                sh.flags);
964 }
965 
966 
967 //----------------------------------------------------------------------
968 // DumpSectionHeaders
969 //
970 // Dump all of the ELF section header to the specified output stream
971 //----------------------------------------------------------------------
972 void
973 ObjectFilePECOFF::DumpSectionHeaders(Stream *s)
974 {
975 
976     s->PutCString ("Section Headers\n");
977     s->PutCString ("IDX  name             vm addr    vm size    file off   file size  reloc off  line off   nreloc nline  flags\n");
978     s->PutCString ("==== ---------------- ---------- ---------- ---------- ---------- ---------- ---------- ------ ------ ----------\n");
979 
980     uint32_t idx = 0;
981     SectionHeaderCollIter pos, end = m_sect_headers.end();
982 
983     for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx)
984     {
985         s->Printf ("[%2u] ", idx);
986         ObjectFilePECOFF::DumpSectionHeader(s, *pos);
987     }
988 }
989 
990 bool
991 ObjectFilePECOFF::GetArchitecture (ArchSpec &arch)
992 {
993     uint16_t machine = m_coff_header.machine;
994     switch (machine)
995     {
996         case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
997         case llvm::COFF::IMAGE_FILE_MACHINE_I386:
998         case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
999         case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1000         case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
1001         case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1002         case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1003             arch.SetArchitecture (eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE);
1004             return true;
1005         default:
1006             break;
1007     }
1008     return false;
1009 }
1010 
1011 ObjectFile::Type
1012 ObjectFilePECOFF::CalculateType()
1013 {
1014     if (m_coff_header.machine != 0)
1015     {
1016         if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1017             return eTypeExecutable;
1018         else
1019             return eTypeSharedLibrary;
1020     }
1021     return eTypeExecutable;
1022 }
1023 
1024 ObjectFile::Strata
1025 ObjectFilePECOFF::CalculateStrata()
1026 {
1027     return eStrataUser;
1028 }
1029 //------------------------------------------------------------------
1030 // PluginInterface protocol
1031 //------------------------------------------------------------------
1032 ConstString
1033 ObjectFilePECOFF::GetPluginName()
1034 {
1035     return GetPluginNameStatic();
1036 }
1037 
1038 uint32_t
1039 ObjectFilePECOFF::GetPluginVersion()
1040 {
1041     return 1;
1042 }
1043 
1044