1 //===-- ObjectFilePECOFF.cpp ------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ObjectFilePECOFF.h"
10 #include "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 struct CVInfoPdb70 {
45   // 16-byte GUID
46   struct _Guid {
47     llvm::support::ulittle32_t Data1;
48     llvm::support::ulittle16_t Data2;
49     llvm::support::ulittle16_t Data3;
50     uint8_t Data4[8];
51   } Guid;
52 
53   llvm::support::ulittle32_t Age;
54 };
55 
56 static UUID GetCoffUUID(llvm::object::COFFObjectFile *coff_obj) {
57   if (!coff_obj)
58     return UUID();
59 
60   const llvm::codeview::DebugInfo *pdb_info = nullptr;
61   llvm::StringRef pdb_file;
62 
63   // This part is similar with what has done in minidump parser.
64   if (!coff_obj->getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
65     if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
66       using llvm::support::endian::read16be;
67       using llvm::support::endian::read32be;
68 
69       const uint8_t *sig = pdb_info->PDB70.Signature;
70       struct CVInfoPdb70 info;
71       info.Guid.Data1 = read32be(sig);
72       sig += 4;
73       info.Guid.Data2 = read16be(sig);
74       sig += 2;
75       info.Guid.Data3 = read16be(sig);
76       sig += 2;
77       memcpy(info.Guid.Data4, sig, 8);
78 
79       // Return 20-byte UUID if the Age is not zero
80       if (pdb_info->PDB70.Age) {
81         info.Age = read32be(&pdb_info->PDB70.Age);
82         return UUID::fromOptionalData(&info, sizeof(info));
83       }
84       // Otherwise return 16-byte GUID
85       return UUID::fromOptionalData(&info.Guid, sizeof(info.Guid));
86     }
87   }
88 
89   return UUID();
90 }
91 
92 char ObjectFilePECOFF::ID;
93 
94 void ObjectFilePECOFF::Initialize() {
95   PluginManager::RegisterPlugin(
96       GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
97       CreateMemoryInstance, GetModuleSpecifications, SaveCore);
98 }
99 
100 void ObjectFilePECOFF::Terminate() {
101   PluginManager::UnregisterPlugin(CreateInstance);
102 }
103 
104 lldb_private::ConstString ObjectFilePECOFF::GetPluginNameStatic() {
105   static ConstString g_name("pe-coff");
106   return g_name;
107 }
108 
109 const char *ObjectFilePECOFF::GetPluginDescriptionStatic() {
110   return "Portable Executable and Common Object File Format object file reader "
111          "(32 and 64 bit)";
112 }
113 
114 ObjectFile *ObjectFilePECOFF::CreateInstance(const lldb::ModuleSP &module_sp,
115                                              DataBufferSP &data_sp,
116                                              lldb::offset_t data_offset,
117                                              const lldb_private::FileSpec *file,
118                                              lldb::offset_t file_offset,
119                                              lldb::offset_t length) {
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, 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   auto binary = llvm::object::createBinary(file.GetPath());
171   if (!binary)
172     return initial_count;
173 
174   if (!binary->getBinary()->isCOFF() &&
175       !binary->getBinary()->isCOFFImportFile())
176     return initial_count;
177 
178   auto COFFObj =
179     llvm::cast<llvm::object::COFFObjectFile>(binary->getBinary());
180 
181   ModuleSpec module_spec(file);
182   ArchSpec &spec = module_spec.GetArchitecture();
183   lldb_private::UUID &uuid = module_spec.GetUUID();
184   if (!uuid.IsValid())
185     uuid = GetCoffUUID(COFFObj);
186 
187   switch (COFFObj->getMachine()) {
188   case MachineAmd64:
189     spec.SetTriple("x86_64-pc-windows");
190     specs.Append(module_spec);
191     break;
192   case MachineX86:
193     spec.SetTriple("i386-pc-windows");
194     specs.Append(module_spec);
195     spec.SetTriple("i686-pc-windows");
196     specs.Append(module_spec);
197     break;
198   case MachineArmNt:
199     spec.SetTriple("armv7-pc-windows");
200     specs.Append(module_spec);
201     break;
202   case MachineArm64:
203     spec.SetTriple("aarch64-pc-windows");
204     specs.Append(module_spec);
205     break;
206   default:
207     break;
208   }
209 
210   return specs.GetSize() - initial_count;
211 }
212 
213 bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
214                                 const lldb_private::FileSpec &outfile,
215                                 lldb_private::Status &error) {
216   return SaveMiniDump(process_sp, outfile, error);
217 }
218 
219 bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP &data_sp) {
220   DataExtractor data(data_sp, eByteOrderLittle, 4);
221   lldb::offset_t offset = 0;
222   uint16_t magic = data.GetU16(&offset);
223   return magic == IMAGE_DOS_SIGNATURE;
224 }
225 
226 lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
227   // TODO:  We need to complete this mapping of COFF symbol types to LLDB ones.
228   // For now, here's a hack to make sure our function have types.
229   const auto complex_type =
230       coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
231   if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
232     return lldb::eSymbolTypeCode;
233   }
234   return lldb::eSymbolTypeInvalid;
235 }
236 
237 bool ObjectFilePECOFF::CreateBinary() {
238   if (m_owningbin)
239     return true;
240 
241   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
242 
243   auto binary = llvm::object::createBinary(m_file.GetPath());
244   if (!binary) {
245     LLDB_LOGF(log,
246               "ObjectFilePECOFF::CreateBinary() - failed to create binary "
247               "for file (%s): %s",
248               m_file ? m_file.GetPath().c_str() : "<NULL>",
249               errorToErrorCode(binary.takeError()).message().c_str());
250     return false;
251   }
252 
253   // Make sure we only handle COFF format.
254   if (!binary->getBinary()->isCOFF() &&
255       !binary->getBinary()->isCOFFImportFile())
256     return false;
257 
258   m_owningbin = OWNBINType(std::move(*binary));
259   LLDB_LOGF(log,
260             "%p ObjectFilePECOFF::CreateBinary() module = %p (%s), file = "
261             "%s, binary = %p (Bin = %p)",
262             static_cast<void *>(this), static_cast<void *>(GetModule().get()),
263             GetModule()->GetSpecificationDescription().c_str(),
264             m_file ? m_file.GetPath().c_str() : "<NULL>",
265             static_cast<void *>(m_owningbin.getPointer()),
266             static_cast<void *>(m_owningbin->getBinary()));
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(), m_owningbin() {
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(), m_owningbin() {
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       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_file) {
543     // A bit of a hack, but we intend to write to this buffer, so we can't
544     // mmap it.
545     auto buffer_sp = MapFileData(m_file, size, offset);
546     return DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize());
547   }
548   ProcessSP process_sp(m_process_wp.lock());
549   DataExtractor data;
550   if (process_sp) {
551     auto data_up = std::make_unique<DataBufferHeap>(size, 0);
552     Status readmem_error;
553     size_t bytes_read =
554         process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
555                                data_up->GetByteSize(), readmem_error);
556     if (bytes_read == size) {
557       DataBufferSP buffer_sp(data_up.release());
558       data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
559     }
560   }
561   return data;
562 }
563 
564 DataExtractor ObjectFilePECOFF::ReadImageDataByRVA(uint32_t rva, size_t size) {
565   if (m_file) {
566     Address addr = GetAddress(rva);
567     rva = addr.GetSection()->GetFileOffset() + addr.GetOffset();
568   }
569 
570   return ReadImageData(rva, size);
571 }
572 
573 // ParseSectionHeaders
574 bool ObjectFilePECOFF::ParseSectionHeaders(
575     uint32_t section_header_data_offset) {
576   const uint32_t nsects = m_coff_header.nsects;
577   m_sect_headers.clear();
578 
579   if (nsects > 0) {
580     const size_t section_header_byte_size = nsects * sizeof(section_header_t);
581     DataExtractor section_header_data =
582         ReadImageData(section_header_data_offset, section_header_byte_size);
583 
584     lldb::offset_t offset = 0;
585     if (section_header_data.ValidOffsetForDataOfSize(
586             offset, section_header_byte_size)) {
587       m_sect_headers.resize(nsects);
588 
589       for (uint32_t idx = 0; idx < nsects; ++idx) {
590         const void *name_data = section_header_data.GetData(&offset, 8);
591         if (name_data) {
592           memcpy(m_sect_headers[idx].name, name_data, 8);
593           m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
594           m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
595           m_sect_headers[idx].size = section_header_data.GetU32(&offset);
596           m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
597           m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
598           m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
599           m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
600           m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
601           m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
602         }
603       }
604     }
605   }
606 
607   return !m_sect_headers.empty();
608 }
609 
610 llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t &sect) {
611   llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name));
612   hdr_name = hdr_name.split('\0').first;
613   if (hdr_name.consume_front("/")) {
614     lldb::offset_t stroff;
615     if (!to_integer(hdr_name, stroff, 10))
616       return "";
617     lldb::offset_t string_file_offset =
618         m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
619     if (const char *name = m_data.GetCStr(&string_file_offset))
620       return name;
621     return "";
622   }
623   return hdr_name;
624 }
625 
626 // GetNListSymtab
627 Symtab *ObjectFilePECOFF::GetSymtab() {
628   ModuleSP module_sp(GetModule());
629   if (module_sp) {
630     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
631     if (m_symtab_up == nullptr) {
632       SectionList *sect_list = GetSectionList();
633       m_symtab_up.reset(new Symtab(this));
634       std::lock_guard<std::recursive_mutex> guard(m_symtab_up->GetMutex());
635 
636       const uint32_t num_syms = m_coff_header.nsyms;
637 
638       if (m_file && num_syms > 0 && m_coff_header.symoff > 0) {
639         const uint32_t symbol_size = 18;
640         const size_t symbol_data_size = num_syms * symbol_size;
641         // Include the 4-byte string table size at the end of the symbols
642         DataExtractor symtab_data =
643             ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
644         lldb::offset_t offset = symbol_data_size;
645         const uint32_t strtab_size = symtab_data.GetU32(&offset);
646         if (strtab_size > 0) {
647           DataExtractor strtab_data = ReadImageData(
648               m_coff_header.symoff + symbol_data_size, strtab_size);
649 
650           // First 4 bytes should be zeroed after strtab_size has been read,
651           // because it is used as offset 0 to encode a NULL string.
652           uint32_t *strtab_data_start = const_cast<uint32_t *>(
653               reinterpret_cast<const uint32_t *>(strtab_data.GetDataStart()));
654           strtab_data_start[0] = 0;
655 
656           offset = 0;
657           std::string symbol_name;
658           Symbol *symbols = m_symtab_up->Resize(num_syms);
659           for (uint32_t i = 0; i < num_syms; ++i) {
660             coff_symbol_t symbol;
661             const uint32_t symbol_offset = offset;
662             const char *symbol_name_cstr = nullptr;
663             // If the first 4 bytes of the symbol string are zero, then they
664             // are followed by a 4-byte string table offset. Else these
665             // 8 bytes contain the symbol name
666             if (symtab_data.GetU32(&offset) == 0) {
667               // Long string that doesn't fit into the symbol table name, so
668               // now we must read the 4 byte string table offset
669               uint32_t strtab_offset = symtab_data.GetU32(&offset);
670               symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
671               symbol_name.assign(symbol_name_cstr);
672             } else {
673               // Short string that fits into the symbol table name which is 8
674               // bytes
675               offset += sizeof(symbol.name) - 4; // Skip remaining
676               symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
677               if (symbol_name_cstr == nullptr)
678                 break;
679               symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
680             }
681             symbol.value = symtab_data.GetU32(&offset);
682             symbol.sect = symtab_data.GetU16(&offset);
683             symbol.type = symtab_data.GetU16(&offset);
684             symbol.storage = symtab_data.GetU8(&offset);
685             symbol.naux = symtab_data.GetU8(&offset);
686             symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
687             if ((int16_t)symbol.sect >= 1) {
688               Address symbol_addr(sect_list->FindSectionByID(symbol.sect),
689                                   symbol.value);
690               symbols[i].GetAddressRef() = symbol_addr;
691               symbols[i].SetType(MapSymbolType(symbol.type));
692             }
693 
694             if (symbol.naux > 0) {
695               i += symbol.naux;
696               offset += symbol_size;
697             }
698           }
699         }
700       }
701 
702       // Read export header
703       if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
704           m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
705           m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) {
706         export_directory_entry export_table;
707         uint32_t data_start =
708             m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
709 
710         DataExtractor symtab_data = ReadImageDataByRVA(
711             data_start, m_coff_header_opt.data_dirs[0].vmsize);
712         lldb::offset_t offset = 0;
713 
714         // Read export_table header
715         export_table.characteristics = symtab_data.GetU32(&offset);
716         export_table.time_date_stamp = symtab_data.GetU32(&offset);
717         export_table.major_version = symtab_data.GetU16(&offset);
718         export_table.minor_version = symtab_data.GetU16(&offset);
719         export_table.name = symtab_data.GetU32(&offset);
720         export_table.base = symtab_data.GetU32(&offset);
721         export_table.number_of_functions = symtab_data.GetU32(&offset);
722         export_table.number_of_names = symtab_data.GetU32(&offset);
723         export_table.address_of_functions = symtab_data.GetU32(&offset);
724         export_table.address_of_names = symtab_data.GetU32(&offset);
725         export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
726 
727         bool has_ordinal = export_table.address_of_name_ordinals != 0;
728 
729         lldb::offset_t name_offset = export_table.address_of_names - data_start;
730         lldb::offset_t name_ordinal_offset =
731             export_table.address_of_name_ordinals - data_start;
732 
733         Symbol *symbols = m_symtab_up->Resize(export_table.number_of_names);
734 
735         std::string symbol_name;
736 
737         // Read each export table entry
738         for (size_t i = 0; i < export_table.number_of_names; ++i) {
739           uint32_t name_ordinal =
740               has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
741           uint32_t name_address = symtab_data.GetU32(&name_offset);
742 
743           const char *symbol_name_cstr =
744               symtab_data.PeekCStr(name_address - data_start);
745           symbol_name.assign(symbol_name_cstr);
746 
747           lldb::offset_t function_offset = export_table.address_of_functions -
748                                            data_start +
749                                            sizeof(uint32_t) * name_ordinal;
750           uint32_t function_rva = symtab_data.GetU32(&function_offset);
751 
752           Address symbol_addr(m_coff_header_opt.image_base + function_rva,
753                               sect_list);
754           symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
755           symbols[i].GetAddressRef() = symbol_addr;
756           symbols[i].SetType(lldb::eSymbolTypeCode);
757           symbols[i].SetDebug(true);
758         }
759       }
760       m_symtab_up->CalculateSymbolSizes();
761     }
762   }
763   return m_symtab_up.get();
764 }
765 
766 std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() {
767   if (coff_data_dir_exception_table >= m_coff_header_opt.data_dirs.size())
768     return {};
769 
770   data_directory data_dir_exception =
771       m_coff_header_opt.data_dirs[coff_data_dir_exception_table];
772   if (!data_dir_exception.vmaddr)
773     return {};
774 
775   return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr,
776                                            data_dir_exception.vmsize);
777 }
778 
779 bool ObjectFilePECOFF::IsStripped() {
780   // TODO: determine this for COFF
781   return false;
782 }
783 
784 void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
785   if (m_sections_up)
786     return;
787   m_sections_up.reset(new SectionList());
788 
789   ModuleSP module_sp(GetModule());
790   if (module_sp) {
791     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
792 
793     SectionSP header_sp = std::make_shared<Section>(
794         module_sp, this, ~user_id_t(0), ConstString("PECOFF header"),
795         eSectionTypeOther, m_coff_header_opt.image_base,
796         m_coff_header_opt.header_size,
797         /*file_offset*/ 0, m_coff_header_opt.header_size,
798         m_coff_header_opt.sect_alignment,
799         /*flags*/ 0);
800     header_sp->SetPermissions(ePermissionsReadable);
801     m_sections_up->AddSection(header_sp);
802     unified_section_list.AddSection(header_sp);
803 
804     const uint32_t nsects = m_sect_headers.size();
805     ModuleSP module_sp(GetModule());
806     for (uint32_t idx = 0; idx < nsects; ++idx) {
807       ConstString const_sect_name(GetSectionName(m_sect_headers[idx]));
808       static ConstString g_code_sect_name(".code");
809       static ConstString g_CODE_sect_name("CODE");
810       static ConstString g_data_sect_name(".data");
811       static ConstString g_DATA_sect_name("DATA");
812       static ConstString g_bss_sect_name(".bss");
813       static ConstString g_BSS_sect_name("BSS");
814       static ConstString g_debug_sect_name(".debug");
815       static ConstString g_reloc_sect_name(".reloc");
816       static ConstString g_stab_sect_name(".stab");
817       static ConstString g_stabstr_sect_name(".stabstr");
818       static ConstString g_sect_name_dwarf_debug_abbrev(".debug_abbrev");
819       static ConstString g_sect_name_dwarf_debug_aranges(".debug_aranges");
820       static ConstString g_sect_name_dwarf_debug_frame(".debug_frame");
821       static ConstString g_sect_name_dwarf_debug_info(".debug_info");
822       static ConstString g_sect_name_dwarf_debug_line(".debug_line");
823       static ConstString g_sect_name_dwarf_debug_loc(".debug_loc");
824       static ConstString g_sect_name_dwarf_debug_loclists(".debug_loclists");
825       static ConstString g_sect_name_dwarf_debug_macinfo(".debug_macinfo");
826       static ConstString g_sect_name_dwarf_debug_names(".debug_names");
827       static ConstString g_sect_name_dwarf_debug_pubnames(".debug_pubnames");
828       static ConstString g_sect_name_dwarf_debug_pubtypes(".debug_pubtypes");
829       static ConstString g_sect_name_dwarf_debug_ranges(".debug_ranges");
830       static ConstString g_sect_name_dwarf_debug_str(".debug_str");
831       static ConstString g_sect_name_dwarf_debug_types(".debug_types");
832       static ConstString g_sect_name_eh_frame(".eh_frame");
833       static ConstString g_sect_name_go_symtab(".gosymtab");
834       SectionType section_type = eSectionTypeOther;
835       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
836           ((const_sect_name == g_code_sect_name) ||
837            (const_sect_name == g_CODE_sect_name))) {
838         section_type = eSectionTypeCode;
839       } else if (m_sect_headers[idx].flags &
840                      llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
841                  ((const_sect_name == g_data_sect_name) ||
842                   (const_sect_name == g_DATA_sect_name))) {
843         if (m_sect_headers[idx].size == 0 && m_sect_headers[idx].offset == 0)
844           section_type = eSectionTypeZeroFill;
845         else
846           section_type = eSectionTypeData;
847       } else if (m_sect_headers[idx].flags &
848                      llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
849                  ((const_sect_name == g_bss_sect_name) ||
850                   (const_sect_name == g_BSS_sect_name))) {
851         if (m_sect_headers[idx].size == 0)
852           section_type = eSectionTypeZeroFill;
853         else
854           section_type = eSectionTypeData;
855       } else if (const_sect_name == g_debug_sect_name) {
856         section_type = eSectionTypeDebug;
857       } else if (const_sect_name == g_stabstr_sect_name) {
858         section_type = eSectionTypeDataCString;
859       } else if (const_sect_name == g_reloc_sect_name) {
860         section_type = eSectionTypeOther;
861       } else if (const_sect_name == g_sect_name_dwarf_debug_abbrev)
862         section_type = eSectionTypeDWARFDebugAbbrev;
863       else if (const_sect_name == g_sect_name_dwarf_debug_aranges)
864         section_type = eSectionTypeDWARFDebugAranges;
865       else if (const_sect_name == g_sect_name_dwarf_debug_frame)
866         section_type = eSectionTypeDWARFDebugFrame;
867       else if (const_sect_name == g_sect_name_dwarf_debug_info)
868         section_type = eSectionTypeDWARFDebugInfo;
869       else if (const_sect_name == g_sect_name_dwarf_debug_line)
870         section_type = eSectionTypeDWARFDebugLine;
871       else if (const_sect_name == g_sect_name_dwarf_debug_loc)
872         section_type = eSectionTypeDWARFDebugLoc;
873       else if (const_sect_name == g_sect_name_dwarf_debug_loclists)
874         section_type = eSectionTypeDWARFDebugLocLists;
875       else if (const_sect_name == g_sect_name_dwarf_debug_macinfo)
876         section_type = eSectionTypeDWARFDebugMacInfo;
877       else if (const_sect_name == g_sect_name_dwarf_debug_names)
878         section_type = eSectionTypeDWARFDebugNames;
879       else if (const_sect_name == g_sect_name_dwarf_debug_pubnames)
880         section_type = eSectionTypeDWARFDebugPubNames;
881       else if (const_sect_name == g_sect_name_dwarf_debug_pubtypes)
882         section_type = eSectionTypeDWARFDebugPubTypes;
883       else if (const_sect_name == g_sect_name_dwarf_debug_ranges)
884         section_type = eSectionTypeDWARFDebugRanges;
885       else if (const_sect_name == g_sect_name_dwarf_debug_str)
886         section_type = eSectionTypeDWARFDebugStr;
887       else if (const_sect_name == g_sect_name_dwarf_debug_types)
888         section_type = eSectionTypeDWARFDebugTypes;
889       else if (const_sect_name == g_sect_name_eh_frame)
890         section_type = eSectionTypeEHFrame;
891       else if (const_sect_name == g_sect_name_go_symtab)
892         section_type = eSectionTypeGoSymtab;
893       else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE) {
894         section_type = eSectionTypeCode;
895       } else if (m_sect_headers[idx].flags &
896                  llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) {
897         section_type = eSectionTypeData;
898       } else if (m_sect_headers[idx].flags &
899                  llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
900         if (m_sect_headers[idx].size == 0)
901           section_type = eSectionTypeZeroFill;
902         else
903           section_type = eSectionTypeData;
904       }
905 
906       SectionSP section_sp(new Section(
907           module_sp,       // Module to which this section belongs
908           this,            // Object file to which this section belongs
909           idx + 1,         // Section ID is the 1 based section index.
910           const_sect_name, // Name of this section
911           section_type,
912           m_coff_header_opt.image_base +
913               m_sect_headers[idx].vmaddr, // File VM address == addresses as
914                                           // they are found in the object file
915           m_sect_headers[idx].vmsize,     // VM size in bytes of this section
916           m_sect_headers[idx]
917               .offset, // Offset to the data for this section in the file
918           m_sect_headers[idx]
919               .size, // Size in bytes of this section as found in the file
920           m_coff_header_opt.sect_alignment, // Section alignment
921           m_sect_headers[idx].flags));      // Flags for this section
922 
923       uint32_t permissions = 0;
924       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
925         permissions |= ePermissionsExecutable;
926       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ)
927         permissions |= ePermissionsReadable;
928       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE)
929         permissions |= ePermissionsWritable;
930       section_sp->SetPermissions(permissions);
931 
932       m_sections_up->AddSection(section_sp);
933       unified_section_list.AddSection(section_sp);
934     }
935   }
936 }
937 
938 UUID ObjectFilePECOFF::GetUUID() {
939   if (m_uuid.IsValid())
940     return m_uuid;
941 
942   if (!CreateBinary())
943     return UUID();
944 
945   auto COFFObj =
946     llvm::cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary());
947 
948   m_uuid = GetCoffUUID(COFFObj);
949   return m_uuid;
950 }
951 
952 uint32_t ObjectFilePECOFF::ParseDependentModules() {
953   ModuleSP module_sp(GetModule());
954   if (!module_sp)
955     return 0;
956 
957   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
958   if (m_deps_filespec)
959     return m_deps_filespec->GetSize();
960 
961   // Cache coff binary if it is not done yet.
962   if (!CreateBinary())
963     return 0;
964 
965   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
966   LLDB_LOGF(log,
967             "%p ObjectFilePECOFF::ParseDependentModules() module = %p "
968             "(%s), binary = %p (Bin = %p)",
969             static_cast<void *>(this), static_cast<void *>(module_sp.get()),
970             module_sp->GetSpecificationDescription().c_str(),
971             static_cast<void *>(m_owningbin.getPointer()),
972             static_cast<void *>(m_owningbin->getBinary()));
973 
974   auto COFFObj =
975       llvm::dyn_cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary());
976   if (!COFFObj)
977     return 0;
978 
979   m_deps_filespec = FileSpecList();
980 
981   for (const auto &entry : COFFObj->import_directories()) {
982     llvm::StringRef dll_name;
983     auto ec = entry.getName(dll_name);
984     // Report a bogus entry.
985     if (ec != std::error_code()) {
986       LLDB_LOGF(log,
987                 "ObjectFilePECOFF::ParseDependentModules() - failed to get "
988                 "import directory entry name: %s",
989                 ec.message().c_str());
990       continue;
991     }
992 
993     // At this moment we only have the base name of the DLL. The full path can
994     // only be seen after the dynamic loading.  Our best guess is Try to get it
995     // with the help of the object file's directory.
996     llvm::SmallString<128> dll_fullpath;
997     FileSpec dll_specs(dll_name);
998     dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
999 
1000     if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
1001       m_deps_filespec->EmplaceBack(dll_fullpath);
1002     else {
1003       // Known DLLs or DLL not found in the object file directory.
1004       m_deps_filespec->EmplaceBack(dll_name);
1005     }
1006   }
1007   return m_deps_filespec->GetSize();
1008 }
1009 
1010 uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
1011   auto num_modules = ParseDependentModules();
1012   auto original_size = files.GetSize();
1013 
1014   for (unsigned i = 0; i < num_modules; ++i)
1015     files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
1016 
1017   return files.GetSize() - original_size;
1018 }
1019 
1020 lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
1021   if (m_entry_point_address.IsValid())
1022     return m_entry_point_address;
1023 
1024   if (!ParseHeader() || !IsExecutable())
1025     return m_entry_point_address;
1026 
1027   SectionList *section_list = GetSectionList();
1028   addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
1029 
1030   if (!section_list)
1031     m_entry_point_address.SetOffset(file_addr);
1032   else
1033     m_entry_point_address.ResolveAddressUsingFileSections(file_addr,
1034                                                           section_list);
1035   return m_entry_point_address;
1036 }
1037 
1038 Address ObjectFilePECOFF::GetBaseAddress() {
1039   return Address(GetSectionList()->GetSectionAtIndex(0), 0);
1040 }
1041 
1042 // Dump
1043 //
1044 // Dump the specifics of the runtime file container (such as any headers
1045 // segments, sections, etc).
1046 void ObjectFilePECOFF::Dump(Stream *s) {
1047   ModuleSP module_sp(GetModule());
1048   if (module_sp) {
1049     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1050     s->Printf("%p: ", static_cast<void *>(this));
1051     s->Indent();
1052     s->PutCString("ObjectFilePECOFF");
1053 
1054     ArchSpec header_arch = GetArchitecture();
1055 
1056     *s << ", file = '" << m_file
1057        << "', arch = " << header_arch.GetArchitectureName() << "\n";
1058 
1059     SectionList *sections = GetSectionList();
1060     if (sections)
1061       sections->Dump(s, nullptr, true, UINT32_MAX);
1062 
1063     if (m_symtab_up)
1064       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
1065 
1066     if (m_dos_header.e_magic)
1067       DumpDOSHeader(s, m_dos_header);
1068     if (m_coff_header.machine) {
1069       DumpCOFFHeader(s, m_coff_header);
1070       if (m_coff_header.hdrsize)
1071         DumpOptCOFFHeader(s, m_coff_header_opt);
1072     }
1073     s->EOL();
1074     DumpSectionHeaders(s);
1075     s->EOL();
1076 
1077     DumpDependentModules(s);
1078     s->EOL();
1079   }
1080 }
1081 
1082 // DumpDOSHeader
1083 //
1084 // Dump the MS-DOS header to the specified output stream
1085 void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
1086   s->PutCString("MSDOS Header\n");
1087   s->Printf("  e_magic    = 0x%4.4x\n", header.e_magic);
1088   s->Printf("  e_cblp     = 0x%4.4x\n", header.e_cblp);
1089   s->Printf("  e_cp       = 0x%4.4x\n", header.e_cp);
1090   s->Printf("  e_crlc     = 0x%4.4x\n", header.e_crlc);
1091   s->Printf("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
1092   s->Printf("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
1093   s->Printf("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1094   s->Printf("  e_ss       = 0x%4.4x\n", header.e_ss);
1095   s->Printf("  e_sp       = 0x%4.4x\n", header.e_sp);
1096   s->Printf("  e_csum     = 0x%4.4x\n", header.e_csum);
1097   s->Printf("  e_ip       = 0x%4.4x\n", header.e_ip);
1098   s->Printf("  e_cs       = 0x%4.4x\n", header.e_cs);
1099   s->Printf("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
1100   s->Printf("  e_ovno     = 0x%4.4x\n", header.e_ovno);
1101   s->Printf("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1102             header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1103   s->Printf("  e_oemid    = 0x%4.4x\n", header.e_oemid);
1104   s->Printf("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
1105   s->Printf("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1106             "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1107             header.e_res2[0], header.e_res2[1], header.e_res2[2],
1108             header.e_res2[3], header.e_res2[4], header.e_res2[5],
1109             header.e_res2[6], header.e_res2[7], header.e_res2[8],
1110             header.e_res2[9]);
1111   s->Printf("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
1112 }
1113 
1114 // DumpCOFFHeader
1115 //
1116 // Dump the COFF header to the specified output stream
1117 void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1118   s->PutCString("COFF Header\n");
1119   s->Printf("  machine = 0x%4.4x\n", header.machine);
1120   s->Printf("  nsects  = 0x%4.4x\n", header.nsects);
1121   s->Printf("  modtime = 0x%8.8x\n", header.modtime);
1122   s->Printf("  symoff  = 0x%8.8x\n", header.symoff);
1123   s->Printf("  nsyms   = 0x%8.8x\n", header.nsyms);
1124   s->Printf("  hdrsize = 0x%4.4x\n", header.hdrsize);
1125 }
1126 
1127 // DumpOptCOFFHeader
1128 //
1129 // Dump the optional COFF header to the specified output stream
1130 void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1131                                          const coff_opt_header_t &header) {
1132   s->PutCString("Optional COFF Header\n");
1133   s->Printf("  magic                   = 0x%4.4x\n", header.magic);
1134   s->Printf("  major_linker_version    = 0x%2.2x\n",
1135             header.major_linker_version);
1136   s->Printf("  minor_linker_version    = 0x%2.2x\n",
1137             header.minor_linker_version);
1138   s->Printf("  code_size               = 0x%8.8x\n", header.code_size);
1139   s->Printf("  data_size               = 0x%8.8x\n", header.data_size);
1140   s->Printf("  bss_size                = 0x%8.8x\n", header.bss_size);
1141   s->Printf("  entry                   = 0x%8.8x\n", header.entry);
1142   s->Printf("  code_offset             = 0x%8.8x\n", header.code_offset);
1143   s->Printf("  data_offset             = 0x%8.8x\n", header.data_offset);
1144   s->Printf("  image_base              = 0x%16.16" PRIx64 "\n",
1145             header.image_base);
1146   s->Printf("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
1147   s->Printf("  file_alignment          = 0x%8.8x\n", header.file_alignment);
1148   s->Printf("  major_os_system_version = 0x%4.4x\n",
1149             header.major_os_system_version);
1150   s->Printf("  minor_os_system_version = 0x%4.4x\n",
1151             header.minor_os_system_version);
1152   s->Printf("  major_image_version     = 0x%4.4x\n",
1153             header.major_image_version);
1154   s->Printf("  minor_image_version     = 0x%4.4x\n",
1155             header.minor_image_version);
1156   s->Printf("  major_subsystem_version = 0x%4.4x\n",
1157             header.major_subsystem_version);
1158   s->Printf("  minor_subsystem_version = 0x%4.4x\n",
1159             header.minor_subsystem_version);
1160   s->Printf("  reserved1               = 0x%8.8x\n", header.reserved1);
1161   s->Printf("  image_size              = 0x%8.8x\n", header.image_size);
1162   s->Printf("  header_size             = 0x%8.8x\n", header.header_size);
1163   s->Printf("  checksum                = 0x%8.8x\n", header.checksum);
1164   s->Printf("  subsystem               = 0x%4.4x\n", header.subsystem);
1165   s->Printf("  dll_flags               = 0x%4.4x\n", header.dll_flags);
1166   s->Printf("  stack_reserve_size      = 0x%16.16" PRIx64 "\n",
1167             header.stack_reserve_size);
1168   s->Printf("  stack_commit_size       = 0x%16.16" PRIx64 "\n",
1169             header.stack_commit_size);
1170   s->Printf("  heap_reserve_size       = 0x%16.16" PRIx64 "\n",
1171             header.heap_reserve_size);
1172   s->Printf("  heap_commit_size        = 0x%16.16" PRIx64 "\n",
1173             header.heap_commit_size);
1174   s->Printf("  loader_flags            = 0x%8.8x\n", header.loader_flags);
1175   s->Printf("  num_data_dir_entries    = 0x%8.8x\n",
1176             (uint32_t)header.data_dirs.size());
1177   uint32_t i;
1178   for (i = 0; i < header.data_dirs.size(); i++) {
1179     s->Printf("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1180               header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1181   }
1182 }
1183 // DumpSectionHeader
1184 //
1185 // Dump a single ELF section header to the specified output stream
1186 void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1187                                          const section_header_t &sh) {
1188   std::string name = GetSectionName(sh);
1189   s->Printf("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x "
1190             "0x%4.4x 0x%8.8x\n",
1191             name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1192             sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1193 }
1194 
1195 // DumpSectionHeaders
1196 //
1197 // Dump all of the ELF section header to the specified output stream
1198 void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1199 
1200   s->PutCString("Section Headers\n");
1201   s->PutCString("IDX  name             vm addr    vm size    file off   file "
1202                 "size  reloc off  line off   nreloc nline  flags\n");
1203   s->PutCString("==== ---------------- ---------- ---------- ---------- "
1204                 "---------- ---------- ---------- ------ ------ ----------\n");
1205 
1206   uint32_t idx = 0;
1207   SectionHeaderCollIter pos, end = m_sect_headers.end();
1208 
1209   for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1210     s->Printf("[%2u] ", idx);
1211     ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1212   }
1213 }
1214 
1215 // DumpDependentModules
1216 //
1217 // Dump all of the dependent modules to the specified output stream
1218 void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1219   auto num_modules = ParseDependentModules();
1220   if (num_modules > 0) {
1221     s->PutCString("Dependent Modules\n");
1222     for (unsigned i = 0; i < num_modules; ++i) {
1223       auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1224       s->Printf("  %s\n", spec.GetFilename().GetCString());
1225     }
1226   }
1227 }
1228 
1229 bool ObjectFilePECOFF::IsWindowsSubsystem() {
1230   switch (m_coff_header_opt.subsystem) {
1231   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1232   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1233   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1234   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1235   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1236   case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1237   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1238     return true;
1239   default:
1240     return false;
1241   }
1242 }
1243 
1244 ArchSpec ObjectFilePECOFF::GetArchitecture() {
1245   uint16_t machine = m_coff_header.machine;
1246   switch (machine) {
1247   default:
1248     break;
1249   case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1250   case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1251   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1252   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1253   case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
1254   case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1255   case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1256   case llvm::COFF::IMAGE_FILE_MACHINE_ARM64:
1257     ArchSpec arch;
1258     arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1259                          IsWindowsSubsystem() ? llvm::Triple::Win32
1260                                               : llvm::Triple::UnknownOS);
1261     return arch;
1262   }
1263   return ArchSpec();
1264 }
1265 
1266 ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1267   if (m_coff_header.machine != 0) {
1268     if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1269       return eTypeExecutable;
1270     else
1271       return eTypeSharedLibrary;
1272   }
1273   return eTypeExecutable;
1274 }
1275 
1276 ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }
1277 
1278 // PluginInterface protocol
1279 ConstString ObjectFilePECOFF::GetPluginName() { return GetPluginNameStatic(); }
1280 
1281 uint32_t ObjectFilePECOFF::GetPluginVersion() { return 1; }
1282