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