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