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