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