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