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