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