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