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