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