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