1f754f88fSGreg Clayton //===-- ObjectFilePECOFF.cpp ------------------------------------*- C++ -*-===//
2f754f88fSGreg Clayton //
3f754f88fSGreg Clayton //                     The LLVM Compiler Infrastructure
4f754f88fSGreg Clayton //
5f754f88fSGreg Clayton // This file is distributed under the University of Illinois Open Source
6f754f88fSGreg Clayton // License. See LICENSE.TXT for details.
7f754f88fSGreg Clayton //
8f754f88fSGreg Clayton //===----------------------------------------------------------------------===//
9f754f88fSGreg Clayton 
10f754f88fSGreg Clayton #include "ObjectFilePECOFF.h"
11f7d1893fSAdrian McCarthy #include "WindowsMiniDump.h"
12f754f88fSGreg Clayton 
13f754f88fSGreg Clayton #include "lldb/Core/FileSpecList.h"
14f754f88fSGreg Clayton #include "lldb/Core/Module.h"
15f4d6de6aSGreg Clayton #include "lldb/Core/ModuleSpec.h"
16f754f88fSGreg Clayton #include "lldb/Core/PluginManager.h"
17f754f88fSGreg Clayton #include "lldb/Core/Section.h"
18f754f88fSGreg Clayton #include "lldb/Core/StreamFile.h"
19f754f88fSGreg Clayton #include "lldb/Symbol/ObjectFile.h"
20f7d1893fSAdrian McCarthy #include "lldb/Target/Process.h"
212756adf3SVirgile Bello #include "lldb/Target/SectionLoadList.h"
222756adf3SVirgile Bello #include "lldb/Target/Target.h"
235f19b907SPavel Labath #include "lldb/Utility/ArchSpec.h"
24666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
255713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
26037ed1beSAaron Smith #include "lldb/Utility/Log.h"
27bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
2838d0632eSPavel Labath #include "lldb/Utility/Timer.h"
29666cc0b2SZachary Turner #include "lldb/Utility/UUID.h"
305f19b907SPavel Labath #include "llvm/BinaryFormat/COFF.h"
31f754f88fSGreg Clayton 
32037ed1beSAaron Smith #include "llvm/Object/COFFImportFile.h"
33037ed1beSAaron Smith #include "llvm/Support/Error.h"
343f4a4b36SZachary Turner #include "llvm/Support/MemoryBuffer.h"
353f4a4b36SZachary Turner 
36f754f88fSGreg Clayton #define IMAGE_DOS_SIGNATURE 0x5A4D    // MZ
37f754f88fSGreg Clayton #define IMAGE_NT_SIGNATURE 0x00004550 // PE00
38f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32 0x010b
39f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
40f754f88fSGreg Clayton 
41f754f88fSGreg Clayton using namespace lldb;
42f754f88fSGreg Clayton using namespace lldb_private;
43f754f88fSGreg Clayton 
44b9c1b51eSKate Stone void ObjectFilePECOFF::Initialize() {
45b9c1b51eSKate Stone   PluginManager::RegisterPlugin(
46b9c1b51eSKate Stone       GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
47b9c1b51eSKate Stone       CreateMemoryInstance, GetModuleSpecifications, SaveCore);
48f754f88fSGreg Clayton }
49f754f88fSGreg Clayton 
50b9c1b51eSKate Stone void ObjectFilePECOFF::Terminate() {
51f754f88fSGreg Clayton   PluginManager::UnregisterPlugin(CreateInstance);
52f754f88fSGreg Clayton }
53f754f88fSGreg Clayton 
54b9c1b51eSKate Stone lldb_private::ConstString ObjectFilePECOFF::GetPluginNameStatic() {
5557abc5d6SGreg Clayton   static ConstString g_name("pe-coff");
5657abc5d6SGreg Clayton   return g_name;
57f754f88fSGreg Clayton }
58f754f88fSGreg Clayton 
59b9c1b51eSKate Stone const char *ObjectFilePECOFF::GetPluginDescriptionStatic() {
60b9c1b51eSKate Stone   return "Portable Executable and Common Object File Format object file reader "
61b9c1b51eSKate Stone          "(32 and 64 bit)";
62f754f88fSGreg Clayton }
63f754f88fSGreg Clayton 
64b9c1b51eSKate Stone ObjectFile *ObjectFilePECOFF::CreateInstance(const lldb::ModuleSP &module_sp,
655ce9c565SGreg Clayton                                              DataBufferSP &data_sp,
665ce9c565SGreg Clayton                                              lldb::offset_t data_offset,
675ce9c565SGreg Clayton                                              const lldb_private::FileSpec *file,
685ce9c565SGreg Clayton                                              lldb::offset_t file_offset,
69b9c1b51eSKate Stone                                              lldb::offset_t length) {
70b9c1b51eSKate Stone   if (!data_sp) {
7150251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
723f4a4b36SZachary Turner     if (!data_sp)
733f4a4b36SZachary Turner       return nullptr;
745ce9c565SGreg Clayton     data_offset = 0;
755ce9c565SGreg Clayton   }
765ce9c565SGreg Clayton 
773f4a4b36SZachary Turner   if (!ObjectFilePECOFF::MagicBytesMatch(data_sp))
783f4a4b36SZachary Turner     return nullptr;
793f4a4b36SZachary Turner 
805ce9c565SGreg Clayton   // Update the data to contain the entire file if it doesn't already
813f4a4b36SZachary Turner   if (data_sp->GetByteSize() < length) {
8250251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
833f4a4b36SZachary Turner     if (!data_sp)
843f4a4b36SZachary Turner       return nullptr;
85f754f88fSGreg Clayton   }
863f4a4b36SZachary Turner 
873f4a4b36SZachary Turner   auto objfile_ap = llvm::make_unique<ObjectFilePECOFF>(
883f4a4b36SZachary Turner       module_sp, data_sp, data_offset, file, file_offset, length);
893f4a4b36SZachary Turner   if (!objfile_ap || !objfile_ap->ParseHeader())
903f4a4b36SZachary Turner     return nullptr;
913f4a4b36SZachary Turner 
92037ed1beSAaron Smith   // Cache coff binary.
93037ed1beSAaron Smith   if (!objfile_ap->CreateBinary())
94037ed1beSAaron Smith     return nullptr;
95037ed1beSAaron Smith 
963f4a4b36SZachary Turner   return objfile_ap.release();
97f754f88fSGreg Clayton }
98f754f88fSGreg Clayton 
99b9c1b51eSKate Stone ObjectFile *ObjectFilePECOFF::CreateMemoryInstance(
100b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp,
101b9c1b51eSKate Stone     const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
102344546bdSWalter Erquinigo   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
103344546bdSWalter Erquinigo     return nullptr;
104344546bdSWalter Erquinigo   auto objfile_ap = llvm::make_unique<ObjectFilePECOFF>(
105344546bdSWalter Erquinigo       module_sp, data_sp, process_sp, header_addr);
106344546bdSWalter Erquinigo   if (objfile_ap.get() && objfile_ap->ParseHeader()) {
107344546bdSWalter Erquinigo     return objfile_ap.release();
108344546bdSWalter Erquinigo   }
109344546bdSWalter Erquinigo   return nullptr;
110c9660546SGreg Clayton }
111c9660546SGreg Clayton 
112b9c1b51eSKate Stone size_t ObjectFilePECOFF::GetModuleSpecifications(
113b9c1b51eSKate Stone     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
114b9c1b51eSKate Stone     lldb::offset_t data_offset, lldb::offset_t file_offset,
115b9c1b51eSKate Stone     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
11689eb1baeSVirgile Bello   const size_t initial_count = specs.GetSize();
11789eb1baeSVirgile Bello 
118b9c1b51eSKate Stone   if (ObjectFilePECOFF::MagicBytesMatch(data_sp)) {
11989eb1baeSVirgile Bello     DataExtractor data;
12089eb1baeSVirgile Bello     data.SetData(data_sp, data_offset, length);
12189eb1baeSVirgile Bello     data.SetByteOrder(eByteOrderLittle);
12289eb1baeSVirgile Bello 
12389eb1baeSVirgile Bello     dos_header_t dos_header;
12489eb1baeSVirgile Bello     coff_header_t coff_header;
12589eb1baeSVirgile Bello 
126b9c1b51eSKate Stone     if (ParseDOSHeader(data, dos_header)) {
12789eb1baeSVirgile Bello       lldb::offset_t offset = dos_header.e_lfanew;
12889eb1baeSVirgile Bello       uint32_t pe_signature = data.GetU32(&offset);
12989eb1baeSVirgile Bello       if (pe_signature != IMAGE_NT_SIGNATURE)
13089eb1baeSVirgile Bello         return false;
131b9c1b51eSKate Stone       if (ParseCOFFHeader(data, &offset, coff_header)) {
13289eb1baeSVirgile Bello         ArchSpec spec;
133b9c1b51eSKate Stone         if (coff_header.machine == MachineAmd64) {
134ad587ae4SZachary Turner           spec.SetTriple("x86_64-pc-windows");
1355e6f4520SZachary Turner           specs.Append(ModuleSpec(file, spec));
136b9c1b51eSKate Stone         } else if (coff_header.machine == MachineX86) {
137ad587ae4SZachary Turner           spec.SetTriple("i386-pc-windows");
13889eb1baeSVirgile Bello           specs.Append(ModuleSpec(file, spec));
1395e6f4520SZachary Turner           spec.SetTriple("i686-pc-windows");
1405e6f4520SZachary Turner           specs.Append(ModuleSpec(file, spec));
141037ed1beSAaron Smith         } else if (coff_header.machine == MachineArmNt) {
1427b6e8ef6SStephane Sezer           spec.SetTriple("arm-pc-windows");
1437b6e8ef6SStephane Sezer           specs.Append(ModuleSpec(file, spec));
1447b6e8ef6SStephane Sezer         }
14589eb1baeSVirgile Bello       }
14689eb1baeSVirgile Bello     }
14789eb1baeSVirgile Bello   }
14889eb1baeSVirgile Bello 
14989eb1baeSVirgile Bello   return specs.GetSize() - initial_count;
150f4d6de6aSGreg Clayton }
151f4d6de6aSGreg Clayton 
152b9c1b51eSKate Stone bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
153f7d1893fSAdrian McCarthy                                 const lldb_private::FileSpec &outfile,
15497206d57SZachary Turner                                 lldb_private::Status &error) {
155f7d1893fSAdrian McCarthy   return SaveMiniDump(process_sp, outfile, error);
156f7d1893fSAdrian McCarthy }
157f7d1893fSAdrian McCarthy 
158b9c1b51eSKate Stone bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP &data_sp) {
1595ce9c565SGreg Clayton   DataExtractor data(data_sp, eByteOrderLittle, 4);
160c7bece56SGreg Clayton   lldb::offset_t offset = 0;
161f754f88fSGreg Clayton   uint16_t magic = data.GetU16(&offset);
162f754f88fSGreg Clayton   return magic == IMAGE_DOS_SIGNATURE;
163f754f88fSGreg Clayton }
164f754f88fSGreg Clayton 
165b9c1b51eSKate Stone lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
166c35b91ceSAdrian McCarthy   // TODO:  We need to complete this mapping of COFF symbol types to LLDB ones.
167c35b91ceSAdrian McCarthy   // For now, here's a hack to make sure our function have types.
168b9c1b51eSKate Stone   const auto complex_type =
169b9c1b51eSKate Stone       coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
170b9c1b51eSKate Stone   if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
171c35b91ceSAdrian McCarthy     return lldb::eSymbolTypeCode;
172c35b91ceSAdrian McCarthy   }
173c35b91ceSAdrian McCarthy   return lldb::eSymbolTypeInvalid;
174c35b91ceSAdrian McCarthy }
175f754f88fSGreg Clayton 
176037ed1beSAaron Smith bool ObjectFilePECOFF::CreateBinary() {
177037ed1beSAaron Smith   if (m_owningbin)
178037ed1beSAaron Smith     return true;
179037ed1beSAaron Smith 
180037ed1beSAaron Smith   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
181037ed1beSAaron Smith 
182037ed1beSAaron Smith   auto binary = llvm::object::createBinary(m_file.GetPath());
183037ed1beSAaron Smith   if (!binary) {
184037ed1beSAaron Smith     if (log)
185037ed1beSAaron Smith       log->Printf("ObjectFilePECOFF::CreateBinary() - failed to create binary "
186037ed1beSAaron Smith                   "for file (%s): %s",
187037ed1beSAaron Smith                   m_file ? m_file.GetPath().c_str() : "<NULL>",
188037ed1beSAaron Smith                   errorToErrorCode(binary.takeError()).message().c_str());
189037ed1beSAaron Smith     return false;
190037ed1beSAaron Smith   }
191037ed1beSAaron Smith 
192037ed1beSAaron Smith   // Make sure we only handle COFF format.
193037ed1beSAaron Smith   if (!binary->getBinary()->isCOFF() &&
194037ed1beSAaron Smith       !binary->getBinary()->isCOFFImportFile())
195037ed1beSAaron Smith     return false;
196037ed1beSAaron Smith 
197037ed1beSAaron Smith   m_owningbin = OWNBINType(std::move(*binary));
198037ed1beSAaron Smith   if (log)
199037ed1beSAaron Smith     log->Printf("%p ObjectFilePECOFF::CreateBinary() module = %p (%s), file = "
200037ed1beSAaron Smith                 "%s, binary = %p (Bin = %p)",
201037ed1beSAaron Smith                 static_cast<void *>(this),
202037ed1beSAaron Smith                 static_cast<void *>(GetModule().get()),
203037ed1beSAaron Smith                 GetModule()->GetSpecificationDescription().c_str(),
204037ed1beSAaron Smith                 m_file ? m_file.GetPath().c_str() : "<NULL>",
205037ed1beSAaron Smith                 static_cast<void *>(m_owningbin.getPointer()),
206037ed1beSAaron Smith                 static_cast<void *>(m_owningbin->getBinary()));
207037ed1beSAaron Smith   return true;
208037ed1beSAaron Smith }
209037ed1beSAaron Smith 
210e72dfb32SGreg Clayton ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
2115ce9c565SGreg Clayton                                    DataBufferSP &data_sp,
2125ce9c565SGreg Clayton                                    lldb::offset_t data_offset,
213f754f88fSGreg Clayton                                    const FileSpec *file,
2145ce9c565SGreg Clayton                                    lldb::offset_t file_offset,
215b9c1b51eSKate Stone                                    lldb::offset_t length)
216b9c1b51eSKate Stone     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
217b9c1b51eSKate Stone       m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
218037ed1beSAaron Smith       m_entry_point_address(), m_deps_filespec(), m_owningbin() {
219f754f88fSGreg Clayton   ::memset(&m_dos_header, 0, sizeof(m_dos_header));
220f754f88fSGreg Clayton   ::memset(&m_coff_header, 0, sizeof(m_coff_header));
221f754f88fSGreg Clayton   ::memset(&m_coff_header_opt, 0, sizeof(m_coff_header_opt));
222f754f88fSGreg Clayton }
223f754f88fSGreg Clayton 
224344546bdSWalter Erquinigo ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
225344546bdSWalter Erquinigo                                    DataBufferSP &header_data_sp,
226344546bdSWalter Erquinigo                                    const lldb::ProcessSP &process_sp,
227344546bdSWalter Erquinigo                                    addr_t header_addr)
228344546bdSWalter Erquinigo     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
229344546bdSWalter Erquinigo       m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
230037ed1beSAaron Smith       m_entry_point_address(), m_deps_filespec(), m_owningbin() {
231344546bdSWalter Erquinigo   ::memset(&m_dos_header, 0, sizeof(m_dos_header));
232344546bdSWalter Erquinigo   ::memset(&m_coff_header, 0, sizeof(m_coff_header));
233344546bdSWalter Erquinigo   ::memset(&m_coff_header_opt, 0, sizeof(m_coff_header_opt));
234344546bdSWalter Erquinigo }
235344546bdSWalter Erquinigo 
236b9c1b51eSKate Stone ObjectFilePECOFF::~ObjectFilePECOFF() {}
237f754f88fSGreg Clayton 
238b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseHeader() {
239a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
240b9c1b51eSKate Stone   if (module_sp) {
24116ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
242f754f88fSGreg Clayton     m_sect_headers.clear();
243f754f88fSGreg Clayton     m_data.SetByteOrder(eByteOrderLittle);
244c7bece56SGreg Clayton     lldb::offset_t offset = 0;
245f754f88fSGreg Clayton 
246b9c1b51eSKate Stone     if (ParseDOSHeader(m_data, m_dos_header)) {
247f754f88fSGreg Clayton       offset = m_dos_header.e_lfanew;
248f754f88fSGreg Clayton       uint32_t pe_signature = m_data.GetU32(&offset);
249f754f88fSGreg Clayton       if (pe_signature != IMAGE_NT_SIGNATURE)
250f754f88fSGreg Clayton         return false;
251b9c1b51eSKate Stone       if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
252f754f88fSGreg Clayton         if (m_coff_header.hdrsize > 0)
253f754f88fSGreg Clayton           ParseCOFFOptionalHeader(&offset);
254f754f88fSGreg Clayton         ParseSectionHeaders(offset);
25528469ca3SGreg Clayton       }
256f754f88fSGreg Clayton       return true;
257f754f88fSGreg Clayton     }
258a1743499SGreg Clayton   }
259f754f88fSGreg Clayton   return false;
260f754f88fSGreg Clayton }
261f754f88fSGreg Clayton 
262b9c1b51eSKate Stone bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value,
263b9c1b51eSKate Stone                                       bool value_is_offset) {
2642756adf3SVirgile Bello   bool changed = false;
2652756adf3SVirgile Bello   ModuleSP module_sp = GetModule();
266b9c1b51eSKate Stone   if (module_sp) {
2672756adf3SVirgile Bello     size_t num_loaded_sections = 0;
2682756adf3SVirgile Bello     SectionList *section_list = GetSectionList();
269b9c1b51eSKate Stone     if (section_list) {
270b9c1b51eSKate Stone       if (!value_is_offset) {
2712756adf3SVirgile Bello         value -= m_image_base;
2722756adf3SVirgile Bello       }
2732756adf3SVirgile Bello 
2742756adf3SVirgile Bello       const size_t num_sections = section_list->GetSize();
2752756adf3SVirgile Bello       size_t sect_idx = 0;
2762756adf3SVirgile Bello 
277b9c1b51eSKate Stone       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
27805097246SAdrian Prantl         // Iterate through the object file sections to find all of the sections
27905097246SAdrian Prantl         // that have SHF_ALLOC in their flag bits.
2802756adf3SVirgile Bello         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
281b9c1b51eSKate Stone         if (section_sp && !section_sp->IsThreadSpecific()) {
282b9c1b51eSKate Stone           if (target.GetSectionLoadList().SetSectionLoadAddress(
283b9c1b51eSKate Stone                   section_sp, section_sp->GetFileAddress() + value))
2842756adf3SVirgile Bello             ++num_loaded_sections;
2852756adf3SVirgile Bello         }
2862756adf3SVirgile Bello       }
2872756adf3SVirgile Bello       changed = num_loaded_sections > 0;
2882756adf3SVirgile Bello     }
2892756adf3SVirgile Bello   }
2902756adf3SVirgile Bello   return changed;
2912756adf3SVirgile Bello }
2922756adf3SVirgile Bello 
293b9c1b51eSKate Stone ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; }
294f754f88fSGreg Clayton 
295b9c1b51eSKate Stone bool ObjectFilePECOFF::IsExecutable() const {
296237ad974SCharles Davis   return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
297f754f88fSGreg Clayton }
298f754f88fSGreg Clayton 
299b9c1b51eSKate Stone uint32_t ObjectFilePECOFF::GetAddressByteSize() const {
300f754f88fSGreg Clayton   if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
301f754f88fSGreg Clayton     return 8;
302f754f88fSGreg Clayton   else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
303f754f88fSGreg Clayton     return 4;
304f754f88fSGreg Clayton   return 4;
305f754f88fSGreg Clayton }
306f754f88fSGreg Clayton 
307f754f88fSGreg Clayton //----------------------------------------------------------------------
308f754f88fSGreg Clayton // NeedsEndianSwap
309f754f88fSGreg Clayton //
31005097246SAdrian Prantl // Return true if an endian swap needs to occur when extracting data from this
31105097246SAdrian Prantl // file.
312f754f88fSGreg Clayton //----------------------------------------------------------------------
313b9c1b51eSKate Stone bool ObjectFilePECOFF::NeedsEndianSwap() const {
314f754f88fSGreg Clayton #if defined(__LITTLE_ENDIAN__)
315f754f88fSGreg Clayton   return false;
316f754f88fSGreg Clayton #else
317f754f88fSGreg Clayton   return true;
318f754f88fSGreg Clayton #endif
319f754f88fSGreg Clayton }
320f754f88fSGreg Clayton //----------------------------------------------------------------------
321f754f88fSGreg Clayton // ParseDOSHeader
322f754f88fSGreg Clayton //----------------------------------------------------------------------
323b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data,
324b9c1b51eSKate Stone                                       dos_header_t &dos_header) {
325f754f88fSGreg Clayton   bool success = false;
326c7bece56SGreg Clayton   lldb::offset_t offset = 0;
32789eb1baeSVirgile Bello   success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
328f754f88fSGreg Clayton 
329b9c1b51eSKate Stone   if (success) {
33089eb1baeSVirgile Bello     dos_header.e_magic = data.GetU16(&offset); // Magic number
33189eb1baeSVirgile Bello     success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
332f754f88fSGreg Clayton 
333b9c1b51eSKate Stone     if (success) {
33489eb1baeSVirgile Bello       dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
33589eb1baeSVirgile Bello       dos_header.e_cp = data.GetU16(&offset);   // Pages in file
33689eb1baeSVirgile Bello       dos_header.e_crlc = data.GetU16(&offset); // Relocations
337b9c1b51eSKate Stone       dos_header.e_cparhdr =
338b9c1b51eSKate Stone           data.GetU16(&offset); // Size of header in paragraphs
339b9c1b51eSKate Stone       dos_header.e_minalloc =
340b9c1b51eSKate Stone           data.GetU16(&offset); // Minimum extra paragraphs needed
341b9c1b51eSKate Stone       dos_header.e_maxalloc =
342b9c1b51eSKate Stone           data.GetU16(&offset);               // Maximum extra paragraphs needed
34389eb1baeSVirgile Bello       dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
34489eb1baeSVirgile Bello       dos_header.e_sp = data.GetU16(&offset); // Initial SP value
34589eb1baeSVirgile Bello       dos_header.e_csum = data.GetU16(&offset); // Checksum
34689eb1baeSVirgile Bello       dos_header.e_ip = data.GetU16(&offset);   // Initial IP value
34789eb1baeSVirgile Bello       dos_header.e_cs = data.GetU16(&offset);   // Initial (relative) CS value
348b9c1b51eSKate Stone       dos_header.e_lfarlc =
349b9c1b51eSKate Stone           data.GetU16(&offset); // File address of relocation table
35089eb1baeSVirgile Bello       dos_header.e_ovno = data.GetU16(&offset); // Overlay number
351f754f88fSGreg Clayton 
35289eb1baeSVirgile Bello       dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
35389eb1baeSVirgile Bello       dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
35489eb1baeSVirgile Bello       dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
35589eb1baeSVirgile Bello       dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
356f754f88fSGreg Clayton 
357b9c1b51eSKate Stone       dos_header.e_oemid =
358b9c1b51eSKate Stone           data.GetU16(&offset); // OEM identifier (for e_oeminfo)
359b9c1b51eSKate Stone       dos_header.e_oeminfo =
360b9c1b51eSKate Stone           data.GetU16(&offset); // OEM information; e_oemid specific
36189eb1baeSVirgile Bello       dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
36289eb1baeSVirgile Bello       dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
36389eb1baeSVirgile Bello       dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
36489eb1baeSVirgile Bello       dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
36589eb1baeSVirgile Bello       dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
36689eb1baeSVirgile Bello       dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
36789eb1baeSVirgile Bello       dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
36889eb1baeSVirgile Bello       dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
36989eb1baeSVirgile Bello       dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
37089eb1baeSVirgile Bello       dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
371f754f88fSGreg Clayton 
372b9c1b51eSKate Stone       dos_header.e_lfanew =
373b9c1b51eSKate Stone           data.GetU32(&offset); // File address of new exe header
374f754f88fSGreg Clayton     }
375f754f88fSGreg Clayton   }
376f754f88fSGreg Clayton   if (!success)
37789eb1baeSVirgile Bello     memset(&dos_header, 0, sizeof(dos_header));
378f754f88fSGreg Clayton   return success;
379f754f88fSGreg Clayton }
380f754f88fSGreg Clayton 
381f754f88fSGreg Clayton //----------------------------------------------------------------------
382f754f88fSGreg Clayton // ParserCOFFHeader
383f754f88fSGreg Clayton //----------------------------------------------------------------------
384b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data,
385b9c1b51eSKate Stone                                        lldb::offset_t *offset_ptr,
386b9c1b51eSKate Stone                                        coff_header_t &coff_header) {
387b9c1b51eSKate Stone   bool success =
388b9c1b51eSKate Stone       data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
389b9c1b51eSKate Stone   if (success) {
39089eb1baeSVirgile Bello     coff_header.machine = data.GetU16(offset_ptr);
39189eb1baeSVirgile Bello     coff_header.nsects = data.GetU16(offset_ptr);
39289eb1baeSVirgile Bello     coff_header.modtime = data.GetU32(offset_ptr);
39389eb1baeSVirgile Bello     coff_header.symoff = data.GetU32(offset_ptr);
39489eb1baeSVirgile Bello     coff_header.nsyms = data.GetU32(offset_ptr);
39589eb1baeSVirgile Bello     coff_header.hdrsize = data.GetU16(offset_ptr);
39689eb1baeSVirgile Bello     coff_header.flags = data.GetU16(offset_ptr);
397f754f88fSGreg Clayton   }
398f754f88fSGreg Clayton   if (!success)
39989eb1baeSVirgile Bello     memset(&coff_header, 0, sizeof(coff_header));
400f754f88fSGreg Clayton   return success;
401f754f88fSGreg Clayton }
402f754f88fSGreg Clayton 
403b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) {
404f754f88fSGreg Clayton   bool success = false;
405c7bece56SGreg Clayton   const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
406b9c1b51eSKate Stone   if (*offset_ptr < end_offset) {
407f754f88fSGreg Clayton     success = true;
408f754f88fSGreg Clayton     m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
409f754f88fSGreg Clayton     m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr);
410f754f88fSGreg Clayton     m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr);
411f754f88fSGreg Clayton     m_coff_header_opt.code_size = m_data.GetU32(offset_ptr);
412f754f88fSGreg Clayton     m_coff_header_opt.data_size = m_data.GetU32(offset_ptr);
413f754f88fSGreg Clayton     m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr);
414f754f88fSGreg Clayton     m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
415f754f88fSGreg Clayton     m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr);
416f754f88fSGreg Clayton 
417f754f88fSGreg Clayton     const uint32_t addr_byte_size = GetAddressByteSize();
418f754f88fSGreg Clayton 
419b9c1b51eSKate Stone     if (*offset_ptr < end_offset) {
420b9c1b51eSKate Stone       if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) {
421f754f88fSGreg Clayton         // PE32 only
422f754f88fSGreg Clayton         m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr);
423b9c1b51eSKate Stone       } else
424f754f88fSGreg Clayton         m_coff_header_opt.data_offset = 0;
425f754f88fSGreg Clayton 
426b9c1b51eSKate Stone       if (*offset_ptr < end_offset) {
427b9c1b51eSKate Stone         m_coff_header_opt.image_base =
428b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
429f754f88fSGreg Clayton         m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr);
430f754f88fSGreg Clayton         m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr);
431f754f88fSGreg Clayton         m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr);
432f754f88fSGreg Clayton         m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr);
433f754f88fSGreg Clayton         m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr);
434f754f88fSGreg Clayton         m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr);
435f754f88fSGreg Clayton         m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr);
436f754f88fSGreg Clayton         m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr);
437f754f88fSGreg Clayton         m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr);
438f754f88fSGreg Clayton         m_coff_header_opt.image_size = m_data.GetU32(offset_ptr);
439f754f88fSGreg Clayton         m_coff_header_opt.header_size = m_data.GetU32(offset_ptr);
44028469ca3SGreg Clayton         m_coff_header_opt.checksum = m_data.GetU32(offset_ptr);
441f754f88fSGreg Clayton         m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr);
442f754f88fSGreg Clayton         m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr);
443b9c1b51eSKate Stone         m_coff_header_opt.stack_reserve_size =
444b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
445b9c1b51eSKate Stone         m_coff_header_opt.stack_commit_size =
446b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
447b9c1b51eSKate Stone         m_coff_header_opt.heap_reserve_size =
448b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
449b9c1b51eSKate Stone         m_coff_header_opt.heap_commit_size =
450b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
451f754f88fSGreg Clayton         m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr);
452f754f88fSGreg Clayton         uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
453f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.clear();
454f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
455f754f88fSGreg Clayton         uint32_t i;
456b9c1b51eSKate Stone         for (i = 0; i < num_data_dir_entries; i++) {
457f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
458f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
459f754f88fSGreg Clayton         }
4602756adf3SVirgile Bello 
4612756adf3SVirgile Bello         m_file_offset = m_coff_header_opt.image_base;
4622756adf3SVirgile Bello         m_image_base = m_coff_header_opt.image_base;
463f754f88fSGreg Clayton       }
464f754f88fSGreg Clayton     }
465f754f88fSGreg Clayton   }
466f754f88fSGreg Clayton   // Make sure we are on track for section data which follows
467f754f88fSGreg Clayton   *offset_ptr = end_offset;
468f754f88fSGreg Clayton   return success;
469f754f88fSGreg Clayton }
470f754f88fSGreg Clayton 
471344546bdSWalter Erquinigo DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) {
472344546bdSWalter Erquinigo   if (m_file) {
4737f6a7a37SZachary Turner     // A bit of a hack, but we intend to write to this buffer, so we can't
4747f6a7a37SZachary Turner     // mmap it.
47550251fc7SPavel Labath     auto buffer_sp = MapFileData(m_file, size, offset);
476344546bdSWalter Erquinigo     return DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize());
477344546bdSWalter Erquinigo   }
478344546bdSWalter Erquinigo   ProcessSP process_sp(m_process_wp.lock());
479344546bdSWalter Erquinigo   DataExtractor data;
480344546bdSWalter Erquinigo   if (process_sp) {
481344546bdSWalter Erquinigo     auto data_ap = llvm::make_unique<DataBufferHeap>(size, 0);
48297206d57SZachary Turner     Status readmem_error;
483344546bdSWalter Erquinigo     size_t bytes_read =
484344546bdSWalter Erquinigo         process_sp->ReadMemory(m_image_base + offset, data_ap->GetBytes(),
485344546bdSWalter Erquinigo                                data_ap->GetByteSize(), readmem_error);
486344546bdSWalter Erquinigo     if (bytes_read == size) {
487344546bdSWalter Erquinigo       DataBufferSP buffer_sp(data_ap.release());
488344546bdSWalter Erquinigo       data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
489344546bdSWalter Erquinigo     }
490344546bdSWalter Erquinigo   }
491344546bdSWalter Erquinigo   return data;
492344546bdSWalter Erquinigo }
493344546bdSWalter Erquinigo 
494f754f88fSGreg Clayton //----------------------------------------------------------------------
495f754f88fSGreg Clayton // ParseSectionHeaders
496f754f88fSGreg Clayton //----------------------------------------------------------------------
497b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseSectionHeaders(
498b9c1b51eSKate Stone     uint32_t section_header_data_offset) {
499f754f88fSGreg Clayton   const uint32_t nsects = m_coff_header.nsects;
500f754f88fSGreg Clayton   m_sect_headers.clear();
501f754f88fSGreg Clayton 
502b9c1b51eSKate Stone   if (nsects > 0) {
503f754f88fSGreg Clayton     const size_t section_header_byte_size = nsects * sizeof(section_header_t);
504344546bdSWalter Erquinigo     DataExtractor section_header_data =
505344546bdSWalter Erquinigo         ReadImageData(section_header_data_offset, section_header_byte_size);
506f754f88fSGreg Clayton 
507c7bece56SGreg Clayton     lldb::offset_t offset = 0;
508b9c1b51eSKate Stone     if (section_header_data.ValidOffsetForDataOfSize(
509b9c1b51eSKate Stone             offset, section_header_byte_size)) {
510f754f88fSGreg Clayton       m_sect_headers.resize(nsects);
511f754f88fSGreg Clayton 
512b9c1b51eSKate Stone       for (uint32_t idx = 0; idx < nsects; ++idx) {
513f754f88fSGreg Clayton         const void *name_data = section_header_data.GetData(&offset, 8);
514b9c1b51eSKate Stone         if (name_data) {
515f754f88fSGreg Clayton           memcpy(m_sect_headers[idx].name, name_data, 8);
516f754f88fSGreg Clayton           m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
517f754f88fSGreg Clayton           m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
518f754f88fSGreg Clayton           m_sect_headers[idx].size = section_header_data.GetU32(&offset);
519f754f88fSGreg Clayton           m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
520f754f88fSGreg Clayton           m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
521f754f88fSGreg Clayton           m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
522f754f88fSGreg Clayton           m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
523f754f88fSGreg Clayton           m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
524f754f88fSGreg Clayton           m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
525f754f88fSGreg Clayton         }
526f754f88fSGreg Clayton       }
527f754f88fSGreg Clayton     }
528f754f88fSGreg Clayton   }
529f754f88fSGreg Clayton 
530a6682a41SJonas Devlieghere   return !m_sect_headers.empty();
531f754f88fSGreg Clayton }
532f754f88fSGreg Clayton 
533b9c1b51eSKate Stone bool ObjectFilePECOFF::GetSectionName(std::string &sect_name,
534b9c1b51eSKate Stone                                       const section_header_t &sect) {
535b9c1b51eSKate Stone   if (sect.name[0] == '/') {
536c7bece56SGreg Clayton     lldb::offset_t stroff = strtoul(&sect.name[1], NULL, 10);
537b9c1b51eSKate Stone     lldb::offset_t string_file_offset =
538b9c1b51eSKate Stone         m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
539f754f88fSGreg Clayton     const char *name = m_data.GetCStr(&string_file_offset);
540b9c1b51eSKate Stone     if (name) {
541f754f88fSGreg Clayton       sect_name = name;
542f754f88fSGreg Clayton       return true;
543f754f88fSGreg Clayton     }
544f754f88fSGreg Clayton 
545f754f88fSGreg Clayton     return false;
546f754f88fSGreg Clayton   }
547f754f88fSGreg Clayton   sect_name = sect.name;
548f754f88fSGreg Clayton   return true;
549f754f88fSGreg Clayton }
550f754f88fSGreg Clayton 
551f754f88fSGreg Clayton //----------------------------------------------------------------------
552f754f88fSGreg Clayton // GetNListSymtab
553f754f88fSGreg Clayton //----------------------------------------------------------------------
554b9c1b51eSKate Stone Symtab *ObjectFilePECOFF::GetSymtab() {
555a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
556b9c1b51eSKate Stone   if (module_sp) {
55716ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
558b9c1b51eSKate Stone     if (m_symtab_ap.get() == NULL) {
559f754f88fSGreg Clayton       SectionList *sect_list = GetSectionList();
560f754f88fSGreg Clayton       m_symtab_ap.reset(new Symtab(this));
561bb19a13cSSaleem Abdulrasool       std::lock_guard<std::recursive_mutex> guard(m_symtab_ap->GetMutex());
56228469ca3SGreg Clayton 
56328469ca3SGreg Clayton       const uint32_t num_syms = m_coff_header.nsyms;
56428469ca3SGreg Clayton 
565344546bdSWalter Erquinigo       if (m_file && num_syms > 0 && m_coff_header.symoff > 0) {
5660076e715SGreg Clayton         const uint32_t symbol_size = 18;
56728469ca3SGreg Clayton         const size_t symbol_data_size = num_syms * symbol_size;
568c35b91ceSAdrian McCarthy         // Include the 4-byte string table size at the end of the symbols
569344546bdSWalter Erquinigo         DataExtractor symtab_data =
570344546bdSWalter Erquinigo             ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
571c7bece56SGreg Clayton         lldb::offset_t offset = symbol_data_size;
57228469ca3SGreg Clayton         const uint32_t strtab_size = symtab_data.GetU32(&offset);
573344546bdSWalter Erquinigo         if (strtab_size > 0) {
574344546bdSWalter Erquinigo           DataExtractor strtab_data = ReadImageData(
575344546bdSWalter Erquinigo               m_coff_header.symoff + symbol_data_size, strtab_size);
57628469ca3SGreg Clayton 
5770076e715SGreg Clayton           // First 4 bytes should be zeroed after strtab_size has been read,
5780076e715SGreg Clayton           // because it is used as offset 0 to encode a NULL string.
579f76e099cSSaleem Abdulrasool           uint32_t *strtab_data_start = const_cast<uint32_t *>(
580f76e099cSSaleem Abdulrasool               reinterpret_cast<const uint32_t *>(strtab_data.GetDataStart()));
5810076e715SGreg Clayton           strtab_data_start[0] = 0;
5820076e715SGreg Clayton 
58328469ca3SGreg Clayton           offset = 0;
58428469ca3SGreg Clayton           std::string symbol_name;
585f754f88fSGreg Clayton           Symbol *symbols = m_symtab_ap->Resize(num_syms);
586b9c1b51eSKate Stone           for (uint32_t i = 0; i < num_syms; ++i) {
587f754f88fSGreg Clayton             coff_symbol_t symbol;
58828469ca3SGreg Clayton             const uint32_t symbol_offset = offset;
58928469ca3SGreg Clayton             const char *symbol_name_cstr = NULL;
590c35b91ceSAdrian McCarthy             // If the first 4 bytes of the symbol string are zero, then they
591c35b91ceSAdrian McCarthy             // are followed by a 4-byte string table offset. Else these
59228469ca3SGreg Clayton             // 8 bytes contain the symbol name
593b9c1b51eSKate Stone             if (symtab_data.GetU32(&offset) == 0) {
59405097246SAdrian Prantl               // Long string that doesn't fit into the symbol table name, so
59505097246SAdrian Prantl               // now we must read the 4 byte string table offset
59628469ca3SGreg Clayton               uint32_t strtab_offset = symtab_data.GetU32(&offset);
59728469ca3SGreg Clayton               symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
59828469ca3SGreg Clayton               symbol_name.assign(symbol_name_cstr);
599b9c1b51eSKate Stone             } else {
600b9c1b51eSKate Stone               // Short string that fits into the symbol table name which is 8
601b9c1b51eSKate Stone               // bytes
60228469ca3SGreg Clayton               offset += sizeof(symbol.name) - 4; // Skip remaining
60328469ca3SGreg Clayton               symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
60428469ca3SGreg Clayton               if (symbol_name_cstr == NULL)
605f754f88fSGreg Clayton                 break;
60628469ca3SGreg Clayton               symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
60728469ca3SGreg Clayton             }
60828469ca3SGreg Clayton             symbol.value = symtab_data.GetU32(&offset);
60928469ca3SGreg Clayton             symbol.sect = symtab_data.GetU16(&offset);
61028469ca3SGreg Clayton             symbol.type = symtab_data.GetU16(&offset);
61128469ca3SGreg Clayton             symbol.storage = symtab_data.GetU8(&offset);
61228469ca3SGreg Clayton             symbol.naux = symtab_data.GetU8(&offset);
613037520e9SGreg Clayton             symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
614b9c1b51eSKate Stone             if ((int16_t)symbol.sect >= 1) {
615b9c1b51eSKate Stone               Address symbol_addr(sect_list->GetSectionAtIndex(symbol.sect - 1),
616b9c1b51eSKate Stone                                   symbol.value);
617358cf1eaSGreg Clayton               symbols[i].GetAddressRef() = symbol_addr;
618c35b91ceSAdrian McCarthy               symbols[i].SetType(MapSymbolType(symbol.type));
6190076e715SGreg Clayton             }
620f754f88fSGreg Clayton 
621b9c1b51eSKate Stone             if (symbol.naux > 0) {
622f754f88fSGreg Clayton               i += symbol.naux;
6230076e715SGreg Clayton               offset += symbol_size;
6240076e715SGreg Clayton             }
625f754f88fSGreg Clayton           }
626f754f88fSGreg Clayton         }
627344546bdSWalter Erquinigo       }
628a4fe3a12SVirgile Bello 
629a4fe3a12SVirgile Bello       // Read export header
630b9c1b51eSKate Stone       if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
631b9c1b51eSKate Stone           m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
632b9c1b51eSKate Stone           m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) {
633a4fe3a12SVirgile Bello         export_directory_entry export_table;
634b9c1b51eSKate Stone         uint32_t data_start =
635b9c1b51eSKate Stone             m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
636344546bdSWalter Erquinigo 
637344546bdSWalter Erquinigo         uint32_t address_rva = data_start;
638344546bdSWalter Erquinigo         if (m_file) {
639a4fe3a12SVirgile Bello           Address address(m_coff_header_opt.image_base + data_start, sect_list);
640344546bdSWalter Erquinigo           address_rva =
641344546bdSWalter Erquinigo               address.GetSection()->GetFileOffset() + address.GetOffset();
642344546bdSWalter Erquinigo         }
643344546bdSWalter Erquinigo         DataExtractor symtab_data =
644344546bdSWalter Erquinigo             ReadImageData(address_rva, m_coff_header_opt.data_dirs[0].vmsize);
645a4fe3a12SVirgile Bello         lldb::offset_t offset = 0;
646a4fe3a12SVirgile Bello 
647a4fe3a12SVirgile Bello         // Read export_table header
648a4fe3a12SVirgile Bello         export_table.characteristics = symtab_data.GetU32(&offset);
649a4fe3a12SVirgile Bello         export_table.time_date_stamp = symtab_data.GetU32(&offset);
650a4fe3a12SVirgile Bello         export_table.major_version = symtab_data.GetU16(&offset);
651a4fe3a12SVirgile Bello         export_table.minor_version = symtab_data.GetU16(&offset);
652a4fe3a12SVirgile Bello         export_table.name = symtab_data.GetU32(&offset);
653a4fe3a12SVirgile Bello         export_table.base = symtab_data.GetU32(&offset);
654a4fe3a12SVirgile Bello         export_table.number_of_functions = symtab_data.GetU32(&offset);
655a4fe3a12SVirgile Bello         export_table.number_of_names = symtab_data.GetU32(&offset);
656a4fe3a12SVirgile Bello         export_table.address_of_functions = symtab_data.GetU32(&offset);
657a4fe3a12SVirgile Bello         export_table.address_of_names = symtab_data.GetU32(&offset);
658a4fe3a12SVirgile Bello         export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
659a4fe3a12SVirgile Bello 
660a4fe3a12SVirgile Bello         bool has_ordinal = export_table.address_of_name_ordinals != 0;
661a4fe3a12SVirgile Bello 
662a4fe3a12SVirgile Bello         lldb::offset_t name_offset = export_table.address_of_names - data_start;
663b9c1b51eSKate Stone         lldb::offset_t name_ordinal_offset =
664b9c1b51eSKate Stone             export_table.address_of_name_ordinals - data_start;
665a4fe3a12SVirgile Bello 
666a4fe3a12SVirgile Bello         Symbol *symbols = m_symtab_ap->Resize(export_table.number_of_names);
667a4fe3a12SVirgile Bello 
668a4fe3a12SVirgile Bello         std::string symbol_name;
669a4fe3a12SVirgile Bello 
670a4fe3a12SVirgile Bello         // Read each export table entry
671b9c1b51eSKate Stone         for (size_t i = 0; i < export_table.number_of_names; ++i) {
672b9c1b51eSKate Stone           uint32_t name_ordinal =
673b9c1b51eSKate Stone               has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
674a4fe3a12SVirgile Bello           uint32_t name_address = symtab_data.GetU32(&name_offset);
675a4fe3a12SVirgile Bello 
676b9c1b51eSKate Stone           const char *symbol_name_cstr =
677b9c1b51eSKate Stone               symtab_data.PeekCStr(name_address - data_start);
678a4fe3a12SVirgile Bello           symbol_name.assign(symbol_name_cstr);
679a4fe3a12SVirgile Bello 
680b9c1b51eSKate Stone           lldb::offset_t function_offset = export_table.address_of_functions -
681b9c1b51eSKate Stone                                            data_start +
682b9c1b51eSKate Stone                                            sizeof(uint32_t) * name_ordinal;
683a4fe3a12SVirgile Bello           uint32_t function_rva = symtab_data.GetU32(&function_offset);
684a4fe3a12SVirgile Bello 
685b9c1b51eSKate Stone           Address symbol_addr(m_coff_header_opt.image_base + function_rva,
686b9c1b51eSKate Stone                               sect_list);
687a4fe3a12SVirgile Bello           symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
688358cf1eaSGreg Clayton           symbols[i].GetAddressRef() = symbol_addr;
689a4fe3a12SVirgile Bello           symbols[i].SetType(lldb::eSymbolTypeCode);
690a4fe3a12SVirgile Bello           symbols[i].SetDebug(true);
691a4fe3a12SVirgile Bello         }
692a4fe3a12SVirgile Bello       }
693407c6910SDavide Italiano       m_symtab_ap->CalculateSymbolSizes();
694f754f88fSGreg Clayton     }
695a1743499SGreg Clayton   }
696f754f88fSGreg Clayton   return m_symtab_ap.get();
697f754f88fSGreg Clayton }
698f754f88fSGreg Clayton 
699b9c1b51eSKate Stone bool ObjectFilePECOFF::IsStripped() {
7003046e668SGreg Clayton   // TODO: determine this for COFF
7013046e668SGreg Clayton   return false;
7023046e668SGreg Clayton }
7033046e668SGreg Clayton 
704b9c1b51eSKate Stone void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
70588a2c2a4SPavel Labath   if (m_sections_ap)
70688a2c2a4SPavel Labath     return;
7073046e668SGreg Clayton   m_sections_ap.reset(new SectionList());
7083046e668SGreg Clayton 
709a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
710b9c1b51eSKate Stone   if (module_sp) {
71116ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
712f754f88fSGreg Clayton     const uint32_t nsects = m_sect_headers.size();
713e72dfb32SGreg Clayton     ModuleSP module_sp(GetModule());
714b9c1b51eSKate Stone     for (uint32_t idx = 0; idx < nsects; ++idx) {
715f754f88fSGreg Clayton       std::string sect_name;
716f754f88fSGreg Clayton       GetSectionName(sect_name, m_sect_headers[idx]);
717f754f88fSGreg Clayton       ConstString const_sect_name(sect_name.c_str());
71828469ca3SGreg Clayton       static ConstString g_code_sect_name(".code");
71928469ca3SGreg Clayton       static ConstString g_CODE_sect_name("CODE");
72028469ca3SGreg Clayton       static ConstString g_data_sect_name(".data");
72128469ca3SGreg Clayton       static ConstString g_DATA_sect_name("DATA");
72228469ca3SGreg Clayton       static ConstString g_bss_sect_name(".bss");
72328469ca3SGreg Clayton       static ConstString g_BSS_sect_name("BSS");
72428469ca3SGreg Clayton       static ConstString g_debug_sect_name(".debug");
72528469ca3SGreg Clayton       static ConstString g_reloc_sect_name(".reloc");
72628469ca3SGreg Clayton       static ConstString g_stab_sect_name(".stab");
72728469ca3SGreg Clayton       static ConstString g_stabstr_sect_name(".stabstr");
7280076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_abbrev(".debug_abbrev");
7290076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_aranges(".debug_aranges");
7300076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_frame(".debug_frame");
7310076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_info(".debug_info");
7320076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_line(".debug_line");
7330076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_loc(".debug_loc");
734e4dee269SGeorge Rimar       static ConstString g_sect_name_dwarf_debug_loclists(".debug_loclists");
7350076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_macinfo(".debug_macinfo");
736a041d848SPavel Labath       static ConstString g_sect_name_dwarf_debug_names(".debug_names");
7370076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_pubnames(".debug_pubnames");
7380076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_pubtypes(".debug_pubtypes");
7390076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_ranges(".debug_ranges");
7400076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_str(".debug_str");
7412550ca1eSGreg Clayton       static ConstString g_sect_name_dwarf_debug_types(".debug_types");
7420076e715SGreg Clayton       static ConstString g_sect_name_eh_frame(".eh_frame");
74365d4d5c3SRyan Brown       static ConstString g_sect_name_go_symtab(".gosymtab");
74428469ca3SGreg Clayton       SectionType section_type = eSectionTypeOther;
745237ad974SCharles Davis       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
746b9c1b51eSKate Stone 	  ((const_sect_name == g_code_sect_name) ||
747b9c1b51eSKate Stone 	   (const_sect_name == g_CODE_sect_name))) {
74828469ca3SGreg Clayton 	section_type = eSectionTypeCode;
749b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
750b9c1b51eSKate Stone 		     llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
751b9c1b51eSKate Stone 		 ((const_sect_name == g_data_sect_name) ||
752b9c1b51eSKate Stone 		  (const_sect_name == g_DATA_sect_name))) {
7539cad24a7SZachary Turner 	if (m_sect_headers[idx].size == 0 && m_sect_headers[idx].offset == 0)
7549cad24a7SZachary Turner 	  section_type = eSectionTypeZeroFill;
7559cad24a7SZachary Turner 	else
75628469ca3SGreg Clayton 	  section_type = eSectionTypeData;
757b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
758b9c1b51eSKate Stone 		     llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
759b9c1b51eSKate Stone 		 ((const_sect_name == g_bss_sect_name) ||
760b9c1b51eSKate Stone 		  (const_sect_name == g_BSS_sect_name))) {
76128469ca3SGreg Clayton 	if (m_sect_headers[idx].size == 0)
76228469ca3SGreg Clayton 	  section_type = eSectionTypeZeroFill;
76328469ca3SGreg Clayton 	else
76428469ca3SGreg Clayton 	  section_type = eSectionTypeData;
765b9c1b51eSKate Stone       } else if (const_sect_name == g_debug_sect_name) {
76628469ca3SGreg Clayton 	section_type = eSectionTypeDebug;
767b9c1b51eSKate Stone       } else if (const_sect_name == g_stabstr_sect_name) {
76828469ca3SGreg Clayton 	section_type = eSectionTypeDataCString;
769b9c1b51eSKate Stone       } else if (const_sect_name == g_reloc_sect_name) {
77028469ca3SGreg Clayton 	section_type = eSectionTypeOther;
771b9c1b51eSKate Stone       } else if (const_sect_name == g_sect_name_dwarf_debug_abbrev)
772b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugAbbrev;
773b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_aranges)
774b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugAranges;
775b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_frame)
776b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugFrame;
777b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_info)
778b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugInfo;
779b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_line)
780b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugLine;
781b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_loc)
782b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugLoc;
783e4dee269SGeorge Rimar       else if (const_sect_name == g_sect_name_dwarf_debug_loclists)
784e4dee269SGeorge Rimar 	section_type = eSectionTypeDWARFDebugLocLists;
785b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_macinfo)
786b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugMacInfo;
787a041d848SPavel Labath       else if (const_sect_name == g_sect_name_dwarf_debug_names)
788a041d848SPavel Labath 	section_type = eSectionTypeDWARFDebugNames;
789b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_pubnames)
790b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugPubNames;
791b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_pubtypes)
792b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugPubTypes;
793b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_ranges)
794b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugRanges;
795b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_str)
796b9c1b51eSKate Stone 	section_type = eSectionTypeDWARFDebugStr;
7972550ca1eSGreg Clayton       else if (const_sect_name == g_sect_name_dwarf_debug_types)
7982550ca1eSGreg Clayton 	section_type = eSectionTypeDWARFDebugTypes;
799b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_eh_frame)
800b9c1b51eSKate Stone 	section_type = eSectionTypeEHFrame;
801b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_go_symtab)
802b9c1b51eSKate Stone 	section_type = eSectionTypeGoSymtab;
803b9c1b51eSKate Stone       else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE) {
80428469ca3SGreg Clayton 	section_type = eSectionTypeCode;
805b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
806b9c1b51eSKate Stone 		 llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) {
80728469ca3SGreg Clayton 	section_type = eSectionTypeData;
808b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
809b9c1b51eSKate Stone 		 llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
81028469ca3SGreg Clayton 	if (m_sect_headers[idx].size == 0)
81128469ca3SGreg Clayton 	  section_type = eSectionTypeZeroFill;
81228469ca3SGreg Clayton 	else
81328469ca3SGreg Clayton 	  section_type = eSectionTypeData;
81428469ca3SGreg Clayton       }
815f754f88fSGreg Clayton 
816f754f88fSGreg Clayton       // Use a segment ID of the segment index shifted left by 8 so they
817f754f88fSGreg Clayton       // never conflict with any of the sections.
818b9c1b51eSKate Stone       SectionSP section_sp(new Section(
819b9c1b51eSKate Stone 	  module_sp, // Module to which this section belongs
820a7499c98SMichael Sartain 	  this,      // Object file to which this section belongs
821b9c1b51eSKate Stone 	  idx + 1, // Section ID is the 1 based segment index shifted right by
822b9c1b51eSKate Stone 		   // 8 bits as not to collide with any of the 256 section IDs
823b9c1b51eSKate Stone 		   // that are possible
824f754f88fSGreg Clayton 	  const_sect_name, // Name of this section
82528469ca3SGreg Clayton 	  section_type,    // This section is a container of other sections.
826b9c1b51eSKate Stone 	  m_coff_header_opt.image_base +
827b9c1b51eSKate Stone 	      m_sect_headers[idx].vmaddr, // File VM address == addresses as
828b9c1b51eSKate Stone 					  // they are found in the object file
829f754f88fSGreg Clayton 	  m_sect_headers[idx].vmsize,     // VM size in bytes of this section
830b9c1b51eSKate Stone 	  m_sect_headers[idx]
831b9c1b51eSKate Stone 	      .offset, // Offset to the data for this section in the file
832b9c1b51eSKate Stone 	  m_sect_headers[idx]
833b9c1b51eSKate Stone 	      .size, // Size in bytes of this section as found in the file
83448672afbSGreg Clayton 	  m_coff_header_opt.sect_alignment, // Section alignment
835f754f88fSGreg Clayton 	  m_sect_headers[idx].flags));      // Flags for this section
836f754f88fSGreg Clayton 
837f754f88fSGreg Clayton       // section_sp->SetIsEncrypted (segment_is_encrypted);
838f754f88fSGreg Clayton 
8393046e668SGreg Clayton       unified_section_list.AddSection(section_sp);
840f754f88fSGreg Clayton       m_sections_ap->AddSection(section_sp);
841f754f88fSGreg Clayton     }
842f754f88fSGreg Clayton   }
843a1743499SGreg Clayton }
844f754f88fSGreg Clayton 
845b9c1b51eSKate Stone bool ObjectFilePECOFF::GetUUID(UUID *uuid) { return false; }
846f754f88fSGreg Clayton 
847037ed1beSAaron Smith uint32_t ObjectFilePECOFF::ParseDependentModules() {
848037ed1beSAaron Smith   ModuleSP module_sp(GetModule());
849037ed1beSAaron Smith   if (!module_sp)
850f754f88fSGreg Clayton     return 0;
851037ed1beSAaron Smith 
852037ed1beSAaron Smith   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
853037ed1beSAaron Smith   if (m_deps_filespec)
854037ed1beSAaron Smith     return m_deps_filespec->GetSize();
855037ed1beSAaron Smith 
856037ed1beSAaron Smith   // Cache coff binary if it is not done yet.
857037ed1beSAaron Smith   if (!CreateBinary())
858037ed1beSAaron Smith     return 0;
859037ed1beSAaron Smith 
860037ed1beSAaron Smith   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
861037ed1beSAaron Smith   if (log)
862037ed1beSAaron Smith     log->Printf("%p ObjectFilePECOFF::ParseDependentModules() module = %p "
863037ed1beSAaron Smith                 "(%s), binary = %p (Bin = %p)",
864037ed1beSAaron Smith                 static_cast<void *>(this), static_cast<void *>(module_sp.get()),
865037ed1beSAaron Smith                 module_sp->GetSpecificationDescription().c_str(),
866037ed1beSAaron Smith                 static_cast<void *>(m_owningbin.getPointer()),
867037ed1beSAaron Smith                 m_owningbin ? static_cast<void *>(m_owningbin->getBinary())
868037ed1beSAaron Smith                             : nullptr);
869037ed1beSAaron Smith 
870037ed1beSAaron Smith   auto COFFObj =
871037ed1beSAaron Smith       llvm::dyn_cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary());
872037ed1beSAaron Smith   if (!COFFObj)
873037ed1beSAaron Smith     return 0;
874037ed1beSAaron Smith 
875037ed1beSAaron Smith   m_deps_filespec = FileSpecList();
876037ed1beSAaron Smith 
877037ed1beSAaron Smith   for (const auto &entry : COFFObj->import_directories()) {
878037ed1beSAaron Smith     llvm::StringRef dll_name;
879037ed1beSAaron Smith     auto ec = entry.getName(dll_name);
880037ed1beSAaron Smith     // Report a bogus entry.
881037ed1beSAaron Smith     if (ec != std::error_code()) {
882037ed1beSAaron Smith       if (log)
883037ed1beSAaron Smith         log->Printf("ObjectFilePECOFF::ParseDependentModules() - failed to get "
884037ed1beSAaron Smith                     "import directory entry name: %s",
885037ed1beSAaron Smith                     ec.message().c_str());
886037ed1beSAaron Smith       continue;
887037ed1beSAaron Smith     }
888037ed1beSAaron Smith 
889037ed1beSAaron Smith     // At this moment we only have the base name of the DLL. The full path can
890037ed1beSAaron Smith     // only be seen after the dynamic loading.  Our best guess is Try to get it
891037ed1beSAaron Smith     // with the help of the object file's directory.
892b3f44ad9SStella Stamenova     llvm::SmallString<128> dll_fullpath;
893037ed1beSAaron Smith     FileSpec dll_specs(dll_name);
894037ed1beSAaron Smith     dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
895037ed1beSAaron Smith 
896037ed1beSAaron Smith     if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
897037ed1beSAaron Smith       m_deps_filespec->Append(FileSpec(dll_fullpath));
898037ed1beSAaron Smith     else {
899037ed1beSAaron Smith       // Known DLLs or DLL not found in the object file directory.
900037ed1beSAaron Smith       m_deps_filespec->Append(FileSpec(dll_name));
901037ed1beSAaron Smith     }
902037ed1beSAaron Smith   }
903037ed1beSAaron Smith   return m_deps_filespec->GetSize();
904037ed1beSAaron Smith }
905037ed1beSAaron Smith 
906037ed1beSAaron Smith uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
907037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
908037ed1beSAaron Smith   auto original_size = files.GetSize();
909037ed1beSAaron Smith 
910037ed1beSAaron Smith   for (unsigned i = 0; i < num_modules; ++i)
911037ed1beSAaron Smith     files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
912037ed1beSAaron Smith 
913037ed1beSAaron Smith   return files.GetSize() - original_size;
914f754f88fSGreg Clayton }
915f754f88fSGreg Clayton 
916b9c1b51eSKate Stone lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
9178e38c666SStephane Sezer   if (m_entry_point_address.IsValid())
9188e38c666SStephane Sezer     return m_entry_point_address;
9198e38c666SStephane Sezer 
9208e38c666SStephane Sezer   if (!ParseHeader() || !IsExecutable())
9218e38c666SStephane Sezer     return m_entry_point_address;
9228e38c666SStephane Sezer 
9238e38c666SStephane Sezer   SectionList *section_list = GetSectionList();
924a5235af9SAleksandr Urakov   addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
9258e38c666SStephane Sezer 
9268e38c666SStephane Sezer   if (!section_list)
927a5235af9SAleksandr Urakov     m_entry_point_address.SetOffset(file_addr);
9288e38c666SStephane Sezer   else
929a5235af9SAleksandr Urakov     m_entry_point_address.ResolveAddressUsingFileSections(file_addr, section_list);
9308e38c666SStephane Sezer   return m_entry_point_address;
9318e38c666SStephane Sezer }
9328e38c666SStephane Sezer 
933f754f88fSGreg Clayton //----------------------------------------------------------------------
934f754f88fSGreg Clayton // Dump
935f754f88fSGreg Clayton //
936f754f88fSGreg Clayton // Dump the specifics of the runtime file container (such as any headers
937f754f88fSGreg Clayton // segments, sections, etc).
938f754f88fSGreg Clayton //----------------------------------------------------------------------
939b9c1b51eSKate Stone void ObjectFilePECOFF::Dump(Stream *s) {
940a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
941b9c1b51eSKate Stone   if (module_sp) {
94216ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
943324a1036SSaleem Abdulrasool     s->Printf("%p: ", static_cast<void *>(this));
944f754f88fSGreg Clayton     s->Indent();
945f754f88fSGreg Clayton     s->PutCString("ObjectFilePECOFF");
946f754f88fSGreg Clayton 
947*f760f5aeSPavel Labath     ArchSpec header_arch = GetArchitecture();
948f754f88fSGreg Clayton 
949b9c1b51eSKate Stone     *s << ", file = '" << m_file
950b9c1b51eSKate Stone        << "', arch = " << header_arch.GetArchitectureName() << "\n";
951f754f88fSGreg Clayton 
9523046e668SGreg Clayton     SectionList *sections = GetSectionList();
9533046e668SGreg Clayton     if (sections)
9543046e668SGreg Clayton       sections->Dump(s, NULL, true, UINT32_MAX);
955f754f88fSGreg Clayton 
956f754f88fSGreg Clayton     if (m_symtab_ap.get())
957f754f88fSGreg Clayton       m_symtab_ap->Dump(s, NULL, eSortOrderNone);
958f754f88fSGreg Clayton 
959f754f88fSGreg Clayton     if (m_dos_header.e_magic)
960f754f88fSGreg Clayton       DumpDOSHeader(s, m_dos_header);
961b9c1b51eSKate Stone     if (m_coff_header.machine) {
962f754f88fSGreg Clayton       DumpCOFFHeader(s, m_coff_header);
963f754f88fSGreg Clayton       if (m_coff_header.hdrsize)
964f754f88fSGreg Clayton         DumpOptCOFFHeader(s, m_coff_header_opt);
965f754f88fSGreg Clayton     }
966f754f88fSGreg Clayton     s->EOL();
967f754f88fSGreg Clayton     DumpSectionHeaders(s);
968f754f88fSGreg Clayton     s->EOL();
969037ed1beSAaron Smith 
970037ed1beSAaron Smith     DumpDependentModules(s);
971037ed1beSAaron Smith     s->EOL();
972f754f88fSGreg Clayton   }
973a1743499SGreg Clayton }
974f754f88fSGreg Clayton 
975f754f88fSGreg Clayton //----------------------------------------------------------------------
976f754f88fSGreg Clayton // DumpDOSHeader
977f754f88fSGreg Clayton //
978f754f88fSGreg Clayton // Dump the MS-DOS header to the specified output stream
979f754f88fSGreg Clayton //----------------------------------------------------------------------
980b9c1b51eSKate Stone void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
981f754f88fSGreg Clayton   s->PutCString("MSDOS Header\n");
982f754f88fSGreg Clayton   s->Printf("  e_magic    = 0x%4.4x\n", header.e_magic);
983f754f88fSGreg Clayton   s->Printf("  e_cblp     = 0x%4.4x\n", header.e_cblp);
984f754f88fSGreg Clayton   s->Printf("  e_cp       = 0x%4.4x\n", header.e_cp);
985f754f88fSGreg Clayton   s->Printf("  e_crlc     = 0x%4.4x\n", header.e_crlc);
986f754f88fSGreg Clayton   s->Printf("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
987f754f88fSGreg Clayton   s->Printf("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
988f754f88fSGreg Clayton   s->Printf("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
989f754f88fSGreg Clayton   s->Printf("  e_ss       = 0x%4.4x\n", header.e_ss);
990f754f88fSGreg Clayton   s->Printf("  e_sp       = 0x%4.4x\n", header.e_sp);
991f754f88fSGreg Clayton   s->Printf("  e_csum     = 0x%4.4x\n", header.e_csum);
992f754f88fSGreg Clayton   s->Printf("  e_ip       = 0x%4.4x\n", header.e_ip);
993f754f88fSGreg Clayton   s->Printf("  e_cs       = 0x%4.4x\n", header.e_cs);
994f754f88fSGreg Clayton   s->Printf("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
995f754f88fSGreg Clayton   s->Printf("  e_ovno     = 0x%4.4x\n", header.e_ovno);
996f754f88fSGreg Clayton   s->Printf("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
997b9c1b51eSKate Stone             header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
998f754f88fSGreg Clayton   s->Printf("  e_oemid    = 0x%4.4x\n", header.e_oemid);
999f754f88fSGreg Clayton   s->Printf("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
1000b9c1b51eSKate Stone   s->Printf("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1001b9c1b51eSKate Stone             "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1002b9c1b51eSKate Stone             header.e_res2[0], header.e_res2[1], header.e_res2[2],
1003b9c1b51eSKate Stone             header.e_res2[3], header.e_res2[4], header.e_res2[5],
1004b9c1b51eSKate Stone             header.e_res2[6], header.e_res2[7], header.e_res2[8],
1005f754f88fSGreg Clayton             header.e_res2[9]);
1006f754f88fSGreg Clayton   s->Printf("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
1007f754f88fSGreg Clayton }
1008f754f88fSGreg Clayton 
1009f754f88fSGreg Clayton //----------------------------------------------------------------------
1010f754f88fSGreg Clayton // DumpCOFFHeader
1011f754f88fSGreg Clayton //
1012f754f88fSGreg Clayton // Dump the COFF header to the specified output stream
1013f754f88fSGreg Clayton //----------------------------------------------------------------------
1014b9c1b51eSKate Stone void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1015f754f88fSGreg Clayton   s->PutCString("COFF Header\n");
1016f754f88fSGreg Clayton   s->Printf("  machine = 0x%4.4x\n", header.machine);
1017f754f88fSGreg Clayton   s->Printf("  nsects  = 0x%4.4x\n", header.nsects);
1018f754f88fSGreg Clayton   s->Printf("  modtime = 0x%8.8x\n", header.modtime);
1019f754f88fSGreg Clayton   s->Printf("  symoff  = 0x%8.8x\n", header.symoff);
1020f754f88fSGreg Clayton   s->Printf("  nsyms   = 0x%8.8x\n", header.nsyms);
1021f754f88fSGreg Clayton   s->Printf("  hdrsize = 0x%4.4x\n", header.hdrsize);
1022f754f88fSGreg Clayton }
1023f754f88fSGreg Clayton 
1024f754f88fSGreg Clayton //----------------------------------------------------------------------
1025f754f88fSGreg Clayton // DumpOptCOFFHeader
1026f754f88fSGreg Clayton //
1027f754f88fSGreg Clayton // Dump the optional COFF header to the specified output stream
1028f754f88fSGreg Clayton //----------------------------------------------------------------------
1029b9c1b51eSKate Stone void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1030b9c1b51eSKate Stone                                          const coff_opt_header_t &header) {
1031f754f88fSGreg Clayton   s->PutCString("Optional COFF Header\n");
1032f754f88fSGreg Clayton   s->Printf("  magic                   = 0x%4.4x\n", header.magic);
1033b9c1b51eSKate Stone   s->Printf("  major_linker_version    = 0x%2.2x\n",
1034b9c1b51eSKate Stone             header.major_linker_version);
1035b9c1b51eSKate Stone   s->Printf("  minor_linker_version    = 0x%2.2x\n",
1036b9c1b51eSKate Stone             header.minor_linker_version);
1037f754f88fSGreg Clayton   s->Printf("  code_size               = 0x%8.8x\n", header.code_size);
1038f754f88fSGreg Clayton   s->Printf("  data_size               = 0x%8.8x\n", header.data_size);
1039f754f88fSGreg Clayton   s->Printf("  bss_size                = 0x%8.8x\n", header.bss_size);
1040f754f88fSGreg Clayton   s->Printf("  entry                   = 0x%8.8x\n", header.entry);
1041f754f88fSGreg Clayton   s->Printf("  code_offset             = 0x%8.8x\n", header.code_offset);
1042f754f88fSGreg Clayton   s->Printf("  data_offset             = 0x%8.8x\n", header.data_offset);
1043b9c1b51eSKate Stone   s->Printf("  image_base              = 0x%16.16" PRIx64 "\n",
1044b9c1b51eSKate Stone             header.image_base);
1045f754f88fSGreg Clayton   s->Printf("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
1046f754f88fSGreg Clayton   s->Printf("  file_alignment          = 0x%8.8x\n", header.file_alignment);
1047b9c1b51eSKate Stone   s->Printf("  major_os_system_version = 0x%4.4x\n",
1048b9c1b51eSKate Stone             header.major_os_system_version);
1049b9c1b51eSKate Stone   s->Printf("  minor_os_system_version = 0x%4.4x\n",
1050b9c1b51eSKate Stone             header.minor_os_system_version);
1051b9c1b51eSKate Stone   s->Printf("  major_image_version     = 0x%4.4x\n",
1052b9c1b51eSKate Stone             header.major_image_version);
1053b9c1b51eSKate Stone   s->Printf("  minor_image_version     = 0x%4.4x\n",
1054b9c1b51eSKate Stone             header.minor_image_version);
1055b9c1b51eSKate Stone   s->Printf("  major_subsystem_version = 0x%4.4x\n",
1056b9c1b51eSKate Stone             header.major_subsystem_version);
1057b9c1b51eSKate Stone   s->Printf("  minor_subsystem_version = 0x%4.4x\n",
1058b9c1b51eSKate Stone             header.minor_subsystem_version);
1059f754f88fSGreg Clayton   s->Printf("  reserved1               = 0x%8.8x\n", header.reserved1);
1060f754f88fSGreg Clayton   s->Printf("  image_size              = 0x%8.8x\n", header.image_size);
1061f754f88fSGreg Clayton   s->Printf("  header_size             = 0x%8.8x\n", header.header_size);
106228469ca3SGreg Clayton   s->Printf("  checksum                = 0x%8.8x\n", header.checksum);
1063f754f88fSGreg Clayton   s->Printf("  subsystem               = 0x%4.4x\n", header.subsystem);
1064f754f88fSGreg Clayton   s->Printf("  dll_flags               = 0x%4.4x\n", header.dll_flags);
1065b9c1b51eSKate Stone   s->Printf("  stack_reserve_size      = 0x%16.16" PRIx64 "\n",
1066b9c1b51eSKate Stone             header.stack_reserve_size);
1067b9c1b51eSKate Stone   s->Printf("  stack_commit_size       = 0x%16.16" PRIx64 "\n",
1068b9c1b51eSKate Stone             header.stack_commit_size);
1069b9c1b51eSKate Stone   s->Printf("  heap_reserve_size       = 0x%16.16" PRIx64 "\n",
1070b9c1b51eSKate Stone             header.heap_reserve_size);
1071b9c1b51eSKate Stone   s->Printf("  heap_commit_size        = 0x%16.16" PRIx64 "\n",
1072b9c1b51eSKate Stone             header.heap_commit_size);
1073f754f88fSGreg Clayton   s->Printf("  loader_flags            = 0x%8.8x\n", header.loader_flags);
1074b9c1b51eSKate Stone   s->Printf("  num_data_dir_entries    = 0x%8.8x\n",
1075b9c1b51eSKate Stone             (uint32_t)header.data_dirs.size());
1076f754f88fSGreg Clayton   uint32_t i;
1077b9c1b51eSKate Stone   for (i = 0; i < header.data_dirs.size(); i++) {
1078b9c1b51eSKate Stone     s->Printf("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1079b9c1b51eSKate Stone               header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1080f754f88fSGreg Clayton   }
1081f754f88fSGreg Clayton }
1082f754f88fSGreg Clayton //----------------------------------------------------------------------
1083f754f88fSGreg Clayton // DumpSectionHeader
1084f754f88fSGreg Clayton //
1085f754f88fSGreg Clayton // Dump a single ELF section header to the specified output stream
1086f754f88fSGreg Clayton //----------------------------------------------------------------------
1087b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1088b9c1b51eSKate Stone                                          const section_header_t &sh) {
1089f754f88fSGreg Clayton   std::string name;
1090f754f88fSGreg Clayton   GetSectionName(name, sh);
1091b9c1b51eSKate Stone   s->Printf("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x "
1092b9c1b51eSKate Stone             "0x%4.4x 0x%8.8x\n",
1093b9c1b51eSKate Stone             name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1094b9c1b51eSKate Stone             sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1095f754f88fSGreg Clayton }
1096f754f88fSGreg Clayton 
1097f754f88fSGreg Clayton //----------------------------------------------------------------------
1098f754f88fSGreg Clayton // DumpSectionHeaders
1099f754f88fSGreg Clayton //
1100f754f88fSGreg Clayton // Dump all of the ELF section header to the specified output stream
1101f754f88fSGreg Clayton //----------------------------------------------------------------------
1102b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1103f754f88fSGreg Clayton 
1104f754f88fSGreg Clayton   s->PutCString("Section Headers\n");
1105b9c1b51eSKate Stone   s->PutCString("IDX  name             vm addr    vm size    file off   file "
1106b9c1b51eSKate Stone                 "size  reloc off  line off   nreloc nline  flags\n");
1107b9c1b51eSKate Stone   s->PutCString("==== ---------------- ---------- ---------- ---------- "
1108b9c1b51eSKate Stone                 "---------- ---------- ---------- ------ ------ ----------\n");
1109f754f88fSGreg Clayton 
1110f754f88fSGreg Clayton   uint32_t idx = 0;
1111f754f88fSGreg Clayton   SectionHeaderCollIter pos, end = m_sect_headers.end();
1112f754f88fSGreg Clayton 
1113b9c1b51eSKate Stone   for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1114f754f88fSGreg Clayton     s->Printf("[%2u] ", idx);
1115f754f88fSGreg Clayton     ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1116f754f88fSGreg Clayton   }
1117f754f88fSGreg Clayton }
1118f754f88fSGreg Clayton 
1119037ed1beSAaron Smith //----------------------------------------------------------------------
1120037ed1beSAaron Smith // DumpDependentModules
1121037ed1beSAaron Smith //
1122037ed1beSAaron Smith // Dump all of the dependent modules to the specified output stream
1123037ed1beSAaron Smith //----------------------------------------------------------------------
1124037ed1beSAaron Smith void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1125037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
1126037ed1beSAaron Smith   if (num_modules > 0) {
1127037ed1beSAaron Smith     s->PutCString("Dependent Modules\n");
1128037ed1beSAaron Smith     for (unsigned i = 0; i < num_modules; ++i) {
1129037ed1beSAaron Smith       auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1130037ed1beSAaron Smith       s->Printf("  %s\n", spec.GetFilename().GetCString());
1131037ed1beSAaron Smith     }
1132037ed1beSAaron Smith   }
1133037ed1beSAaron Smith }
1134037ed1beSAaron Smith 
1135fb3b3bd1SZachary Turner bool ObjectFilePECOFF::IsWindowsSubsystem() {
1136fb3b3bd1SZachary Turner   switch (m_coff_header_opt.subsystem) {
1137fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1138fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1139fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1140fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1141fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1142fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1143fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1144fb3b3bd1SZachary Turner     return true;
1145fb3b3bd1SZachary Turner   default:
1146fb3b3bd1SZachary Turner     return false;
1147fb3b3bd1SZachary Turner   }
1148fb3b3bd1SZachary Turner }
1149fb3b3bd1SZachary Turner 
1150*f760f5aeSPavel Labath ArchSpec ObjectFilePECOFF::GetArchitecture() {
1151237ad974SCharles Davis   uint16_t machine = m_coff_header.machine;
1152b9c1b51eSKate Stone   switch (machine) {
1153*f760f5aeSPavel Labath   default:
1154*f760f5aeSPavel Labath     break;
1155237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1156237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1157237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1158237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1159237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
11601108cb36SSaleem Abdulrasool   case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1161237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1162*f760f5aeSPavel Labath     ArchSpec arch;
1163fb3b3bd1SZachary Turner     arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1164fb3b3bd1SZachary Turner                          IsWindowsSubsystem() ? llvm::Triple::Win32
1165fb3b3bd1SZachary Turner                                               : llvm::Triple::UnknownOS);
1166*f760f5aeSPavel Labath     return arch;
1167237ad974SCharles Davis   }
1168*f760f5aeSPavel Labath   return ArchSpec();
1169f754f88fSGreg Clayton }
1170f754f88fSGreg Clayton 
1171b9c1b51eSKate Stone ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1172b9c1b51eSKate Stone   if (m_coff_header.machine != 0) {
1173237ad974SCharles Davis     if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1174f754f88fSGreg Clayton       return eTypeExecutable;
1175f754f88fSGreg Clayton     else
1176f754f88fSGreg Clayton       return eTypeSharedLibrary;
1177f754f88fSGreg Clayton   }
1178f754f88fSGreg Clayton   return eTypeExecutable;
1179f754f88fSGreg Clayton }
1180f754f88fSGreg Clayton 
1181b9c1b51eSKate Stone ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }
11829cad24a7SZachary Turner 
1183f754f88fSGreg Clayton //------------------------------------------------------------------
1184f754f88fSGreg Clayton // PluginInterface protocol
1185f754f88fSGreg Clayton //------------------------------------------------------------------
1186b9c1b51eSKate Stone ConstString ObjectFilePECOFF::GetPluginName() { return GetPluginNameStatic(); }
1187f754f88fSGreg Clayton 
1188b9c1b51eSKate Stone uint32_t ObjectFilePECOFF::GetPluginVersion() { return 1; }
1189