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