1f754f88fSGreg Clayton //===-- ObjectFilePECOFF.cpp ------------------------------------*- C++ -*-===//
2f754f88fSGreg Clayton //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f754f88fSGreg Clayton //
7f754f88fSGreg Clayton //===----------------------------------------------------------------------===//
8f754f88fSGreg Clayton 
9f754f88fSGreg Clayton #include "ObjectFilePECOFF.h"
10f7d1893fSAdrian McCarthy #include "WindowsMiniDump.h"
11f754f88fSGreg Clayton 
12f754f88fSGreg Clayton #include "lldb/Core/FileSpecList.h"
13f754f88fSGreg Clayton #include "lldb/Core/Module.h"
14f4d6de6aSGreg Clayton #include "lldb/Core/ModuleSpec.h"
15f754f88fSGreg Clayton #include "lldb/Core/PluginManager.h"
16f754f88fSGreg Clayton #include "lldb/Core/Section.h"
17f754f88fSGreg Clayton #include "lldb/Core/StreamFile.h"
18f754f88fSGreg Clayton #include "lldb/Symbol/ObjectFile.h"
19f7d1893fSAdrian McCarthy #include "lldb/Target/Process.h"
202756adf3SVirgile Bello #include "lldb/Target/SectionLoadList.h"
212756adf3SVirgile Bello #include "lldb/Target/Target.h"
225f19b907SPavel Labath #include "lldb/Utility/ArchSpec.h"
23666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
245713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
25037ed1beSAaron Smith #include "lldb/Utility/Log.h"
26bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
2738d0632eSPavel Labath #include "lldb/Utility/Timer.h"
28666cc0b2SZachary Turner #include "lldb/Utility/UUID.h"
295f19b907SPavel Labath #include "llvm/BinaryFormat/COFF.h"
30f754f88fSGreg Clayton 
31037ed1beSAaron Smith #include "llvm/Object/COFFImportFile.h"
32037ed1beSAaron Smith #include "llvm/Support/Error.h"
333f4a4b36SZachary Turner #include "llvm/Support/MemoryBuffer.h"
343f4a4b36SZachary Turner 
35f754f88fSGreg Clayton #define IMAGE_DOS_SIGNATURE 0x5A4D    // MZ
36f754f88fSGreg Clayton #define IMAGE_NT_SIGNATURE 0x00004550 // PE00
37f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32 0x010b
38f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
39f754f88fSGreg Clayton 
40f754f88fSGreg Clayton using namespace lldb;
41f754f88fSGreg Clayton using namespace lldb_private;
42f754f88fSGreg Clayton 
43b8d03935SAaron Smith struct CVInfoPdb70 {
44b8d03935SAaron Smith   // 16-byte GUID
45b8d03935SAaron Smith   struct _Guid {
46b8d03935SAaron Smith     llvm::support::ulittle32_t Data1;
47b8d03935SAaron Smith     llvm::support::ulittle16_t Data2;
48b8d03935SAaron Smith     llvm::support::ulittle16_t Data3;
49b8d03935SAaron Smith     uint8_t Data4[8];
50b8d03935SAaron Smith   } Guid;
51b8d03935SAaron Smith 
52b8d03935SAaron Smith   llvm::support::ulittle32_t Age;
53b8d03935SAaron Smith };
54b8d03935SAaron Smith 
55b8d03935SAaron Smith static UUID GetCoffUUID(llvm::object::COFFObjectFile *coff_obj) {
56b8d03935SAaron Smith   if (!coff_obj)
57b8d03935SAaron Smith     return UUID();
58b8d03935SAaron Smith 
59b8d03935SAaron Smith   const llvm::codeview::DebugInfo *pdb_info = nullptr;
60b8d03935SAaron Smith   llvm::StringRef pdb_file;
61b8d03935SAaron Smith 
62b8d03935SAaron Smith   // This part is similar with what has done in minidump parser.
63b8d03935SAaron Smith   if (!coff_obj->getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
64b8d03935SAaron Smith     if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
65b8d03935SAaron Smith       using llvm::support::endian::read16be;
66b8d03935SAaron Smith       using llvm::support::endian::read32be;
67b8d03935SAaron Smith 
68b8d03935SAaron Smith       const uint8_t *sig = pdb_info->PDB70.Signature;
69b8d03935SAaron Smith       struct CVInfoPdb70 info;
70b8d03935SAaron Smith       info.Guid.Data1 = read32be(sig);
71b8d03935SAaron Smith       sig += 4;
72b8d03935SAaron Smith       info.Guid.Data2 = read16be(sig);
73b8d03935SAaron Smith       sig += 2;
74b8d03935SAaron Smith       info.Guid.Data3 = read16be(sig);
75b8d03935SAaron Smith       sig += 2;
76b8d03935SAaron Smith       memcpy(info.Guid.Data4, sig, 8);
77b8d03935SAaron Smith 
78b8d03935SAaron Smith       // Return 20-byte UUID if the Age is not zero
79b8d03935SAaron Smith       if (pdb_info->PDB70.Age) {
80b8d03935SAaron Smith         info.Age = read32be(&pdb_info->PDB70.Age);
81b8d03935SAaron Smith         return UUID::fromOptionalData(&info, sizeof(info));
82b8d03935SAaron Smith       }
83b8d03935SAaron Smith       // Otherwise return 16-byte GUID
84b8d03935SAaron Smith       return UUID::fromOptionalData(&info.Guid, sizeof(info.Guid));
85b8d03935SAaron Smith     }
86b8d03935SAaron Smith   }
87b8d03935SAaron Smith 
88b8d03935SAaron Smith   return UUID();
89b8d03935SAaron Smith }
90b8d03935SAaron Smith 
91b9c1b51eSKate Stone void ObjectFilePECOFF::Initialize() {
92b9c1b51eSKate Stone   PluginManager::RegisterPlugin(
93b9c1b51eSKate Stone       GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
94b9c1b51eSKate Stone       CreateMemoryInstance, GetModuleSpecifications, SaveCore);
95f754f88fSGreg Clayton }
96f754f88fSGreg Clayton 
97b9c1b51eSKate Stone void ObjectFilePECOFF::Terminate() {
98f754f88fSGreg Clayton   PluginManager::UnregisterPlugin(CreateInstance);
99f754f88fSGreg Clayton }
100f754f88fSGreg Clayton 
101b9c1b51eSKate Stone lldb_private::ConstString ObjectFilePECOFF::GetPluginNameStatic() {
10257abc5d6SGreg Clayton   static ConstString g_name("pe-coff");
10357abc5d6SGreg Clayton   return g_name;
104f754f88fSGreg Clayton }
105f754f88fSGreg Clayton 
106b9c1b51eSKate Stone const char *ObjectFilePECOFF::GetPluginDescriptionStatic() {
107b9c1b51eSKate Stone   return "Portable Executable and Common Object File Format object file reader "
108b9c1b51eSKate Stone          "(32 and 64 bit)";
109f754f88fSGreg Clayton }
110f754f88fSGreg Clayton 
111b9c1b51eSKate Stone ObjectFile *ObjectFilePECOFF::CreateInstance(const lldb::ModuleSP &module_sp,
1125ce9c565SGreg Clayton                                              DataBufferSP &data_sp,
1135ce9c565SGreg Clayton                                              lldb::offset_t data_offset,
1145ce9c565SGreg Clayton                                              const lldb_private::FileSpec *file,
1155ce9c565SGreg Clayton                                              lldb::offset_t file_offset,
116b9c1b51eSKate Stone                                              lldb::offset_t length) {
117b9c1b51eSKate Stone   if (!data_sp) {
11850251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
1193f4a4b36SZachary Turner     if (!data_sp)
1203f4a4b36SZachary Turner       return nullptr;
1215ce9c565SGreg Clayton     data_offset = 0;
1225ce9c565SGreg Clayton   }
1235ce9c565SGreg Clayton 
1243f4a4b36SZachary Turner   if (!ObjectFilePECOFF::MagicBytesMatch(data_sp))
1253f4a4b36SZachary Turner     return nullptr;
1263f4a4b36SZachary Turner 
1275ce9c565SGreg Clayton   // Update the data to contain the entire file if it doesn't already
1283f4a4b36SZachary Turner   if (data_sp->GetByteSize() < length) {
12950251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
1303f4a4b36SZachary Turner     if (!data_sp)
1313f4a4b36SZachary Turner       return nullptr;
132f754f88fSGreg Clayton   }
1333f4a4b36SZachary Turner 
134d5b44036SJonas Devlieghere   auto objfile_up = llvm::make_unique<ObjectFilePECOFF>(
1353f4a4b36SZachary Turner       module_sp, data_sp, data_offset, file, file_offset, length);
136d5b44036SJonas Devlieghere   if (!objfile_up || !objfile_up->ParseHeader())
1373f4a4b36SZachary Turner     return nullptr;
1383f4a4b36SZachary Turner 
139037ed1beSAaron Smith   // Cache coff binary.
140d5b44036SJonas Devlieghere   if (!objfile_up->CreateBinary())
141037ed1beSAaron Smith     return nullptr;
142037ed1beSAaron Smith 
143d5b44036SJonas Devlieghere   return objfile_up.release();
144f754f88fSGreg Clayton }
145f754f88fSGreg Clayton 
146b9c1b51eSKate Stone ObjectFile *ObjectFilePECOFF::CreateMemoryInstance(
147b9c1b51eSKate Stone     const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp,
148b9c1b51eSKate Stone     const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
149344546bdSWalter Erquinigo   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
150344546bdSWalter Erquinigo     return nullptr;
151d5b44036SJonas Devlieghere   auto objfile_up = llvm::make_unique<ObjectFilePECOFF>(
152344546bdSWalter Erquinigo       module_sp, data_sp, process_sp, header_addr);
153d5b44036SJonas Devlieghere   if (objfile_up.get() && objfile_up->ParseHeader()) {
154d5b44036SJonas Devlieghere     return objfile_up.release();
155344546bdSWalter Erquinigo   }
156344546bdSWalter Erquinigo   return nullptr;
157c9660546SGreg Clayton }
158c9660546SGreg Clayton 
159b9c1b51eSKate Stone size_t ObjectFilePECOFF::GetModuleSpecifications(
160b9c1b51eSKate Stone     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
161b9c1b51eSKate Stone     lldb::offset_t data_offset, lldb::offset_t file_offset,
162b9c1b51eSKate Stone     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
16389eb1baeSVirgile Bello   const size_t initial_count = specs.GetSize();
164b8d03935SAaron Smith   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
165b8d03935SAaron Smith     return initial_count;
16689eb1baeSVirgile Bello 
167b8d03935SAaron Smith   auto binary = llvm::object::createBinary(file.GetPath());
168b8d03935SAaron Smith   if (!binary)
169b8d03935SAaron Smith     return initial_count;
17089eb1baeSVirgile Bello 
171b8d03935SAaron Smith   if (!binary->getBinary()->isCOFF() &&
172b8d03935SAaron Smith       !binary->getBinary()->isCOFFImportFile())
173b8d03935SAaron Smith     return initial_count;
17489eb1baeSVirgile Bello 
175b8d03935SAaron Smith   auto COFFObj =
176b8d03935SAaron Smith     llvm::cast<llvm::object::COFFObjectFile>(binary->getBinary());
177b8d03935SAaron Smith 
178b8d03935SAaron Smith   ModuleSpec module_spec(file);
179b8d03935SAaron Smith   ArchSpec &spec = module_spec.GetArchitecture();
180b8d03935SAaron Smith   lldb_private::UUID &uuid = module_spec.GetUUID();
181b8d03935SAaron Smith   if (!uuid.IsValid())
182b8d03935SAaron Smith     uuid = GetCoffUUID(COFFObj);
183b8d03935SAaron Smith 
184b8d03935SAaron Smith   switch (COFFObj->getMachine()) {
185b8d03935SAaron Smith   case MachineAmd64:
186ad587ae4SZachary Turner     spec.SetTriple("x86_64-pc-windows");
187b8d03935SAaron Smith     specs.Append(module_spec);
188b8d03935SAaron Smith     break;
189b8d03935SAaron Smith   case MachineX86:
190ad587ae4SZachary Turner     spec.SetTriple("i386-pc-windows");
191b8d03935SAaron Smith     specs.Append(module_spec);
1925e6f4520SZachary Turner     spec.SetTriple("i686-pc-windows");
193b8d03935SAaron Smith     specs.Append(module_spec);
194b8d03935SAaron Smith     break;
195b8d03935SAaron Smith   case MachineArmNt:
1967b6e8ef6SStephane Sezer     spec.SetTriple("arm-pc-windows");
197b8d03935SAaron Smith     specs.Append(module_spec);
198b8d03935SAaron Smith     break;
199b8d03935SAaron Smith   default:
200b8d03935SAaron Smith     break;
20189eb1baeSVirgile Bello   }
20289eb1baeSVirgile Bello 
20389eb1baeSVirgile Bello   return specs.GetSize() - initial_count;
204f4d6de6aSGreg Clayton }
205f4d6de6aSGreg Clayton 
206b9c1b51eSKate Stone bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
207f7d1893fSAdrian McCarthy                                 const lldb_private::FileSpec &outfile,
20897206d57SZachary Turner                                 lldb_private::Status &error) {
209f7d1893fSAdrian McCarthy   return SaveMiniDump(process_sp, outfile, error);
210f7d1893fSAdrian McCarthy }
211f7d1893fSAdrian McCarthy 
212b9c1b51eSKate Stone bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP &data_sp) {
2135ce9c565SGreg Clayton   DataExtractor data(data_sp, eByteOrderLittle, 4);
214c7bece56SGreg Clayton   lldb::offset_t offset = 0;
215f754f88fSGreg Clayton   uint16_t magic = data.GetU16(&offset);
216f754f88fSGreg Clayton   return magic == IMAGE_DOS_SIGNATURE;
217f754f88fSGreg Clayton }
218f754f88fSGreg Clayton 
219b9c1b51eSKate Stone lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
220c35b91ceSAdrian McCarthy   // TODO:  We need to complete this mapping of COFF symbol types to LLDB ones.
221c35b91ceSAdrian McCarthy   // For now, here's a hack to make sure our function have types.
222b9c1b51eSKate Stone   const auto complex_type =
223b9c1b51eSKate Stone       coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
224b9c1b51eSKate Stone   if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
225c35b91ceSAdrian McCarthy     return lldb::eSymbolTypeCode;
226c35b91ceSAdrian McCarthy   }
227c35b91ceSAdrian McCarthy   return lldb::eSymbolTypeInvalid;
228c35b91ceSAdrian McCarthy }
229f754f88fSGreg Clayton 
230037ed1beSAaron Smith bool ObjectFilePECOFF::CreateBinary() {
231037ed1beSAaron Smith   if (m_owningbin)
232037ed1beSAaron Smith     return true;
233037ed1beSAaron Smith 
234037ed1beSAaron Smith   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
235037ed1beSAaron Smith 
236037ed1beSAaron Smith   auto binary = llvm::object::createBinary(m_file.GetPath());
237037ed1beSAaron Smith   if (!binary) {
238*63e5fb76SJonas Devlieghere     LLDB_LOGF(log,
239*63e5fb76SJonas Devlieghere               "ObjectFilePECOFF::CreateBinary() - failed to create binary "
240037ed1beSAaron Smith               "for file (%s): %s",
241037ed1beSAaron Smith               m_file ? m_file.GetPath().c_str() : "<NULL>",
242037ed1beSAaron Smith               errorToErrorCode(binary.takeError()).message().c_str());
243037ed1beSAaron Smith     return false;
244037ed1beSAaron Smith   }
245037ed1beSAaron Smith 
246037ed1beSAaron Smith   // Make sure we only handle COFF format.
247037ed1beSAaron Smith   if (!binary->getBinary()->isCOFF() &&
248037ed1beSAaron Smith       !binary->getBinary()->isCOFFImportFile())
249037ed1beSAaron Smith     return false;
250037ed1beSAaron Smith 
251037ed1beSAaron Smith   m_owningbin = OWNBINType(std::move(*binary));
252*63e5fb76SJonas Devlieghere   LLDB_LOGF(log,
253*63e5fb76SJonas Devlieghere             "%p ObjectFilePECOFF::CreateBinary() module = %p (%s), file = "
254037ed1beSAaron Smith             "%s, binary = %p (Bin = %p)",
255*63e5fb76SJonas Devlieghere             static_cast<void *>(this), static_cast<void *>(GetModule().get()),
256037ed1beSAaron Smith             GetModule()->GetSpecificationDescription().c_str(),
257037ed1beSAaron Smith             m_file ? m_file.GetPath().c_str() : "<NULL>",
258037ed1beSAaron Smith             static_cast<void *>(m_owningbin.getPointer()),
259037ed1beSAaron Smith             static_cast<void *>(m_owningbin->getBinary()));
260037ed1beSAaron Smith   return true;
261037ed1beSAaron Smith }
262037ed1beSAaron Smith 
263e72dfb32SGreg Clayton ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
2645ce9c565SGreg Clayton                                    DataBufferSP &data_sp,
2655ce9c565SGreg Clayton                                    lldb::offset_t data_offset,
266f754f88fSGreg Clayton                                    const FileSpec *file,
2675ce9c565SGreg Clayton                                    lldb::offset_t file_offset,
268b9c1b51eSKate Stone                                    lldb::offset_t length)
269b9c1b51eSKate Stone     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
270b9c1b51eSKate Stone       m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
271037ed1beSAaron Smith       m_entry_point_address(), m_deps_filespec(), m_owningbin() {
272f754f88fSGreg Clayton   ::memset(&m_dos_header, 0, sizeof(m_dos_header));
273f754f88fSGreg Clayton   ::memset(&m_coff_header, 0, sizeof(m_coff_header));
274f754f88fSGreg Clayton   ::memset(&m_coff_header_opt, 0, sizeof(m_coff_header_opt));
275f754f88fSGreg Clayton }
276f754f88fSGreg Clayton 
277344546bdSWalter Erquinigo ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
278344546bdSWalter Erquinigo                                    DataBufferSP &header_data_sp,
279344546bdSWalter Erquinigo                                    const lldb::ProcessSP &process_sp,
280344546bdSWalter Erquinigo                                    addr_t header_addr)
281344546bdSWalter Erquinigo     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
282344546bdSWalter Erquinigo       m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
283037ed1beSAaron Smith       m_entry_point_address(), m_deps_filespec(), m_owningbin() {
284344546bdSWalter Erquinigo   ::memset(&m_dos_header, 0, sizeof(m_dos_header));
285344546bdSWalter Erquinigo   ::memset(&m_coff_header, 0, sizeof(m_coff_header));
286344546bdSWalter Erquinigo   ::memset(&m_coff_header_opt, 0, sizeof(m_coff_header_opt));
287344546bdSWalter Erquinigo }
288344546bdSWalter Erquinigo 
289b9c1b51eSKate Stone ObjectFilePECOFF::~ObjectFilePECOFF() {}
290f754f88fSGreg Clayton 
291b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseHeader() {
292a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
293b9c1b51eSKate Stone   if (module_sp) {
29416ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
295f754f88fSGreg Clayton     m_sect_headers.clear();
296f754f88fSGreg Clayton     m_data.SetByteOrder(eByteOrderLittle);
297c7bece56SGreg Clayton     lldb::offset_t offset = 0;
298f754f88fSGreg Clayton 
299b9c1b51eSKate Stone     if (ParseDOSHeader(m_data, m_dos_header)) {
300f754f88fSGreg Clayton       offset = m_dos_header.e_lfanew;
301f754f88fSGreg Clayton       uint32_t pe_signature = m_data.GetU32(&offset);
302f754f88fSGreg Clayton       if (pe_signature != IMAGE_NT_SIGNATURE)
303f754f88fSGreg Clayton         return false;
304b9c1b51eSKate Stone       if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
305f754f88fSGreg Clayton         if (m_coff_header.hdrsize > 0)
306f754f88fSGreg Clayton           ParseCOFFOptionalHeader(&offset);
307f754f88fSGreg Clayton         ParseSectionHeaders(offset);
30828469ca3SGreg Clayton       }
309f754f88fSGreg Clayton       return true;
310f754f88fSGreg Clayton     }
311a1743499SGreg Clayton   }
312f754f88fSGreg Clayton   return false;
313f754f88fSGreg Clayton }
314f754f88fSGreg Clayton 
315b9c1b51eSKate Stone bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value,
316b9c1b51eSKate Stone                                       bool value_is_offset) {
3172756adf3SVirgile Bello   bool changed = false;
3182756adf3SVirgile Bello   ModuleSP module_sp = GetModule();
319b9c1b51eSKate Stone   if (module_sp) {
3202756adf3SVirgile Bello     size_t num_loaded_sections = 0;
3212756adf3SVirgile Bello     SectionList *section_list = GetSectionList();
322b9c1b51eSKate Stone     if (section_list) {
323b9c1b51eSKate Stone       if (!value_is_offset) {
3242756adf3SVirgile Bello         value -= m_image_base;
3252756adf3SVirgile Bello       }
3262756adf3SVirgile Bello 
3272756adf3SVirgile Bello       const size_t num_sections = section_list->GetSize();
3282756adf3SVirgile Bello       size_t sect_idx = 0;
3292756adf3SVirgile Bello 
330b9c1b51eSKate Stone       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
33105097246SAdrian Prantl         // Iterate through the object file sections to find all of the sections
33205097246SAdrian Prantl         // that have SHF_ALLOC in their flag bits.
3332756adf3SVirgile Bello         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
334b9c1b51eSKate Stone         if (section_sp && !section_sp->IsThreadSpecific()) {
335b9c1b51eSKate Stone           if (target.GetSectionLoadList().SetSectionLoadAddress(
336b9c1b51eSKate Stone                   section_sp, section_sp->GetFileAddress() + value))
3372756adf3SVirgile Bello             ++num_loaded_sections;
3382756adf3SVirgile Bello         }
3392756adf3SVirgile Bello       }
3402756adf3SVirgile Bello       changed = num_loaded_sections > 0;
3412756adf3SVirgile Bello     }
3422756adf3SVirgile Bello   }
3432756adf3SVirgile Bello   return changed;
3442756adf3SVirgile Bello }
3452756adf3SVirgile Bello 
346b9c1b51eSKate Stone ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; }
347f754f88fSGreg Clayton 
348b9c1b51eSKate Stone bool ObjectFilePECOFF::IsExecutable() const {
349237ad974SCharles Davis   return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
350f754f88fSGreg Clayton }
351f754f88fSGreg Clayton 
352b9c1b51eSKate Stone uint32_t ObjectFilePECOFF::GetAddressByteSize() const {
353f754f88fSGreg Clayton   if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
354f754f88fSGreg Clayton     return 8;
355f754f88fSGreg Clayton   else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
356f754f88fSGreg Clayton     return 4;
357f754f88fSGreg Clayton   return 4;
358f754f88fSGreg Clayton }
359f754f88fSGreg Clayton 
360f754f88fSGreg Clayton // NeedsEndianSwap
361f754f88fSGreg Clayton //
36205097246SAdrian Prantl // Return true if an endian swap needs to occur when extracting data from this
36305097246SAdrian Prantl // file.
364b9c1b51eSKate Stone bool ObjectFilePECOFF::NeedsEndianSwap() const {
365f754f88fSGreg Clayton #if defined(__LITTLE_ENDIAN__)
366f754f88fSGreg Clayton   return false;
367f754f88fSGreg Clayton #else
368f754f88fSGreg Clayton   return true;
369f754f88fSGreg Clayton #endif
370f754f88fSGreg Clayton }
371f754f88fSGreg Clayton // ParseDOSHeader
372b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data,
373b9c1b51eSKate Stone                                       dos_header_t &dos_header) {
374f754f88fSGreg Clayton   bool success = false;
375c7bece56SGreg Clayton   lldb::offset_t offset = 0;
37689eb1baeSVirgile Bello   success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
377f754f88fSGreg Clayton 
378b9c1b51eSKate Stone   if (success) {
37989eb1baeSVirgile Bello     dos_header.e_magic = data.GetU16(&offset); // Magic number
38089eb1baeSVirgile Bello     success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
381f754f88fSGreg Clayton 
382b9c1b51eSKate Stone     if (success) {
38389eb1baeSVirgile Bello       dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
38489eb1baeSVirgile Bello       dos_header.e_cp = data.GetU16(&offset);   // Pages in file
38589eb1baeSVirgile Bello       dos_header.e_crlc = data.GetU16(&offset); // Relocations
386b9c1b51eSKate Stone       dos_header.e_cparhdr =
387b9c1b51eSKate Stone           data.GetU16(&offset); // Size of header in paragraphs
388b9c1b51eSKate Stone       dos_header.e_minalloc =
389b9c1b51eSKate Stone           data.GetU16(&offset); // Minimum extra paragraphs needed
390b9c1b51eSKate Stone       dos_header.e_maxalloc =
391b9c1b51eSKate Stone           data.GetU16(&offset);               // Maximum extra paragraphs needed
39289eb1baeSVirgile Bello       dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
39389eb1baeSVirgile Bello       dos_header.e_sp = data.GetU16(&offset); // Initial SP value
39489eb1baeSVirgile Bello       dos_header.e_csum = data.GetU16(&offset); // Checksum
39589eb1baeSVirgile Bello       dos_header.e_ip = data.GetU16(&offset);   // Initial IP value
39689eb1baeSVirgile Bello       dos_header.e_cs = data.GetU16(&offset);   // Initial (relative) CS value
397b9c1b51eSKate Stone       dos_header.e_lfarlc =
398b9c1b51eSKate Stone           data.GetU16(&offset); // File address of relocation table
39989eb1baeSVirgile Bello       dos_header.e_ovno = data.GetU16(&offset); // Overlay number
400f754f88fSGreg Clayton 
40189eb1baeSVirgile Bello       dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
40289eb1baeSVirgile Bello       dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
40389eb1baeSVirgile Bello       dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
40489eb1baeSVirgile Bello       dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
405f754f88fSGreg Clayton 
406b9c1b51eSKate Stone       dos_header.e_oemid =
407b9c1b51eSKate Stone           data.GetU16(&offset); // OEM identifier (for e_oeminfo)
408b9c1b51eSKate Stone       dos_header.e_oeminfo =
409b9c1b51eSKate Stone           data.GetU16(&offset); // OEM information; e_oemid specific
41089eb1baeSVirgile Bello       dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
41189eb1baeSVirgile Bello       dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
41289eb1baeSVirgile Bello       dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
41389eb1baeSVirgile Bello       dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
41489eb1baeSVirgile Bello       dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
41589eb1baeSVirgile Bello       dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
41689eb1baeSVirgile Bello       dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
41789eb1baeSVirgile Bello       dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
41889eb1baeSVirgile Bello       dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
41989eb1baeSVirgile Bello       dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
420f754f88fSGreg Clayton 
421b9c1b51eSKate Stone       dos_header.e_lfanew =
422b9c1b51eSKate Stone           data.GetU32(&offset); // File address of new exe header
423f754f88fSGreg Clayton     }
424f754f88fSGreg Clayton   }
425f754f88fSGreg Clayton   if (!success)
42689eb1baeSVirgile Bello     memset(&dos_header, 0, sizeof(dos_header));
427f754f88fSGreg Clayton   return success;
428f754f88fSGreg Clayton }
429f754f88fSGreg Clayton 
430f754f88fSGreg Clayton // ParserCOFFHeader
431b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data,
432b9c1b51eSKate Stone                                        lldb::offset_t *offset_ptr,
433b9c1b51eSKate Stone                                        coff_header_t &coff_header) {
434b9c1b51eSKate Stone   bool success =
435b9c1b51eSKate Stone       data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
436b9c1b51eSKate Stone   if (success) {
43789eb1baeSVirgile Bello     coff_header.machine = data.GetU16(offset_ptr);
43889eb1baeSVirgile Bello     coff_header.nsects = data.GetU16(offset_ptr);
43989eb1baeSVirgile Bello     coff_header.modtime = data.GetU32(offset_ptr);
44089eb1baeSVirgile Bello     coff_header.symoff = data.GetU32(offset_ptr);
44189eb1baeSVirgile Bello     coff_header.nsyms = data.GetU32(offset_ptr);
44289eb1baeSVirgile Bello     coff_header.hdrsize = data.GetU16(offset_ptr);
44389eb1baeSVirgile Bello     coff_header.flags = data.GetU16(offset_ptr);
444f754f88fSGreg Clayton   }
445f754f88fSGreg Clayton   if (!success)
44689eb1baeSVirgile Bello     memset(&coff_header, 0, sizeof(coff_header));
447f754f88fSGreg Clayton   return success;
448f754f88fSGreg Clayton }
449f754f88fSGreg Clayton 
450b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) {
451f754f88fSGreg Clayton   bool success = false;
452c7bece56SGreg Clayton   const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
453b9c1b51eSKate Stone   if (*offset_ptr < end_offset) {
454f754f88fSGreg Clayton     success = true;
455f754f88fSGreg Clayton     m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
456f754f88fSGreg Clayton     m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr);
457f754f88fSGreg Clayton     m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr);
458f754f88fSGreg Clayton     m_coff_header_opt.code_size = m_data.GetU32(offset_ptr);
459f754f88fSGreg Clayton     m_coff_header_opt.data_size = m_data.GetU32(offset_ptr);
460f754f88fSGreg Clayton     m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr);
461f754f88fSGreg Clayton     m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
462f754f88fSGreg Clayton     m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr);
463f754f88fSGreg Clayton 
464f754f88fSGreg Clayton     const uint32_t addr_byte_size = GetAddressByteSize();
465f754f88fSGreg Clayton 
466b9c1b51eSKate Stone     if (*offset_ptr < end_offset) {
467b9c1b51eSKate Stone       if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) {
468f754f88fSGreg Clayton         // PE32 only
469f754f88fSGreg Clayton         m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr);
470b9c1b51eSKate Stone       } else
471f754f88fSGreg Clayton         m_coff_header_opt.data_offset = 0;
472f754f88fSGreg Clayton 
473b9c1b51eSKate Stone       if (*offset_ptr < end_offset) {
474b9c1b51eSKate Stone         m_coff_header_opt.image_base =
475b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
476f754f88fSGreg Clayton         m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr);
477f754f88fSGreg Clayton         m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr);
478f754f88fSGreg Clayton         m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr);
479f754f88fSGreg Clayton         m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr);
480f754f88fSGreg Clayton         m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr);
481f754f88fSGreg Clayton         m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr);
482f754f88fSGreg Clayton         m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr);
483f754f88fSGreg Clayton         m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr);
484f754f88fSGreg Clayton         m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr);
485f754f88fSGreg Clayton         m_coff_header_opt.image_size = m_data.GetU32(offset_ptr);
486f754f88fSGreg Clayton         m_coff_header_opt.header_size = m_data.GetU32(offset_ptr);
48728469ca3SGreg Clayton         m_coff_header_opt.checksum = m_data.GetU32(offset_ptr);
488f754f88fSGreg Clayton         m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr);
489f754f88fSGreg Clayton         m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr);
490b9c1b51eSKate Stone         m_coff_header_opt.stack_reserve_size =
491b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
492b9c1b51eSKate Stone         m_coff_header_opt.stack_commit_size =
493b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
494b9c1b51eSKate Stone         m_coff_header_opt.heap_reserve_size =
495b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
496b9c1b51eSKate Stone         m_coff_header_opt.heap_commit_size =
497b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
498f754f88fSGreg Clayton         m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr);
499f754f88fSGreg Clayton         uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
500f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.clear();
501f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
502f754f88fSGreg Clayton         uint32_t i;
503b9c1b51eSKate Stone         for (i = 0; i < num_data_dir_entries; i++) {
504f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
505f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
506f754f88fSGreg Clayton         }
5072756adf3SVirgile Bello 
5082756adf3SVirgile Bello         m_image_base = m_coff_header_opt.image_base;
509f754f88fSGreg Clayton       }
510f754f88fSGreg Clayton     }
511f754f88fSGreg Clayton   }
512f754f88fSGreg Clayton   // Make sure we are on track for section data which follows
513f754f88fSGreg Clayton   *offset_ptr = end_offset;
514f754f88fSGreg Clayton   return success;
515f754f88fSGreg Clayton }
516f754f88fSGreg Clayton 
517344546bdSWalter Erquinigo DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) {
518344546bdSWalter Erquinigo   if (m_file) {
5197f6a7a37SZachary Turner     // A bit of a hack, but we intend to write to this buffer, so we can't
5207f6a7a37SZachary Turner     // mmap it.
52150251fc7SPavel Labath     auto buffer_sp = MapFileData(m_file, size, offset);
522344546bdSWalter Erquinigo     return DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize());
523344546bdSWalter Erquinigo   }
524344546bdSWalter Erquinigo   ProcessSP process_sp(m_process_wp.lock());
525344546bdSWalter Erquinigo   DataExtractor data;
526344546bdSWalter Erquinigo   if (process_sp) {
527d5b44036SJonas Devlieghere     auto data_up = llvm::make_unique<DataBufferHeap>(size, 0);
52897206d57SZachary Turner     Status readmem_error;
529344546bdSWalter Erquinigo     size_t bytes_read =
530d5b44036SJonas Devlieghere         process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
531d5b44036SJonas Devlieghere                                data_up->GetByteSize(), readmem_error);
532344546bdSWalter Erquinigo     if (bytes_read == size) {
533d5b44036SJonas Devlieghere       DataBufferSP buffer_sp(data_up.release());
534344546bdSWalter Erquinigo       data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
535344546bdSWalter Erquinigo     }
536344546bdSWalter Erquinigo   }
537344546bdSWalter Erquinigo   return data;
538344546bdSWalter Erquinigo }
539344546bdSWalter Erquinigo 
540f754f88fSGreg Clayton // ParseSectionHeaders
541b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseSectionHeaders(
542b9c1b51eSKate Stone     uint32_t section_header_data_offset) {
543f754f88fSGreg Clayton   const uint32_t nsects = m_coff_header.nsects;
544f754f88fSGreg Clayton   m_sect_headers.clear();
545f754f88fSGreg Clayton 
546b9c1b51eSKate Stone   if (nsects > 0) {
547f754f88fSGreg Clayton     const size_t section_header_byte_size = nsects * sizeof(section_header_t);
548344546bdSWalter Erquinigo     DataExtractor section_header_data =
549344546bdSWalter Erquinigo         ReadImageData(section_header_data_offset, section_header_byte_size);
550f754f88fSGreg Clayton 
551c7bece56SGreg Clayton     lldb::offset_t offset = 0;
552b9c1b51eSKate Stone     if (section_header_data.ValidOffsetForDataOfSize(
553b9c1b51eSKate Stone             offset, section_header_byte_size)) {
554f754f88fSGreg Clayton       m_sect_headers.resize(nsects);
555f754f88fSGreg Clayton 
556b9c1b51eSKate Stone       for (uint32_t idx = 0; idx < nsects; ++idx) {
557f754f88fSGreg Clayton         const void *name_data = section_header_data.GetData(&offset, 8);
558b9c1b51eSKate Stone         if (name_data) {
559f754f88fSGreg Clayton           memcpy(m_sect_headers[idx].name, name_data, 8);
560f754f88fSGreg Clayton           m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
561f754f88fSGreg Clayton           m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
562f754f88fSGreg Clayton           m_sect_headers[idx].size = section_header_data.GetU32(&offset);
563f754f88fSGreg Clayton           m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
564f754f88fSGreg Clayton           m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
565f754f88fSGreg Clayton           m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
566f754f88fSGreg Clayton           m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
567f754f88fSGreg Clayton           m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
568f754f88fSGreg Clayton           m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
569f754f88fSGreg Clayton         }
570f754f88fSGreg Clayton       }
571f754f88fSGreg Clayton     }
572f754f88fSGreg Clayton   }
573f754f88fSGreg Clayton 
574a6682a41SJonas Devlieghere   return !m_sect_headers.empty();
575f754f88fSGreg Clayton }
576f754f88fSGreg Clayton 
5772886e4a0SPavel Labath llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t &sect) {
5782886e4a0SPavel Labath   llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name));
5792886e4a0SPavel Labath   hdr_name = hdr_name.split('\0').first;
5802886e4a0SPavel Labath   if (hdr_name.consume_front("/")) {
5812886e4a0SPavel Labath     lldb::offset_t stroff;
5822886e4a0SPavel Labath     if (!to_integer(hdr_name, stroff, 10))
5832886e4a0SPavel Labath       return "";
584b9c1b51eSKate Stone     lldb::offset_t string_file_offset =
585b9c1b51eSKate Stone         m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
5862886e4a0SPavel Labath     if (const char *name = m_data.GetCStr(&string_file_offset))
5872886e4a0SPavel Labath       return name;
5882886e4a0SPavel Labath     return "";
589f754f88fSGreg Clayton   }
5902886e4a0SPavel Labath   return hdr_name;
591f754f88fSGreg Clayton }
592f754f88fSGreg Clayton 
593f754f88fSGreg Clayton // GetNListSymtab
594b9c1b51eSKate Stone Symtab *ObjectFilePECOFF::GetSymtab() {
595a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
596b9c1b51eSKate Stone   if (module_sp) {
59716ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
598248a1305SKonrad Kleine     if (m_symtab_up == nullptr) {
599f754f88fSGreg Clayton       SectionList *sect_list = GetSectionList();
600d5b44036SJonas Devlieghere       m_symtab_up.reset(new Symtab(this));
601d5b44036SJonas Devlieghere       std::lock_guard<std::recursive_mutex> guard(m_symtab_up->GetMutex());
60228469ca3SGreg Clayton 
60328469ca3SGreg Clayton       const uint32_t num_syms = m_coff_header.nsyms;
60428469ca3SGreg Clayton 
605344546bdSWalter Erquinigo       if (m_file && num_syms > 0 && m_coff_header.symoff > 0) {
6060076e715SGreg Clayton         const uint32_t symbol_size = 18;
60728469ca3SGreg Clayton         const size_t symbol_data_size = num_syms * symbol_size;
608c35b91ceSAdrian McCarthy         // Include the 4-byte string table size at the end of the symbols
609344546bdSWalter Erquinigo         DataExtractor symtab_data =
610344546bdSWalter Erquinigo             ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
611c7bece56SGreg Clayton         lldb::offset_t offset = symbol_data_size;
61228469ca3SGreg Clayton         const uint32_t strtab_size = symtab_data.GetU32(&offset);
613344546bdSWalter Erquinigo         if (strtab_size > 0) {
614344546bdSWalter Erquinigo           DataExtractor strtab_data = ReadImageData(
615344546bdSWalter Erquinigo               m_coff_header.symoff + symbol_data_size, strtab_size);
61628469ca3SGreg Clayton 
6170076e715SGreg Clayton           // First 4 bytes should be zeroed after strtab_size has been read,
6180076e715SGreg Clayton           // because it is used as offset 0 to encode a NULL string.
619f76e099cSSaleem Abdulrasool           uint32_t *strtab_data_start = const_cast<uint32_t *>(
620f76e099cSSaleem Abdulrasool               reinterpret_cast<const uint32_t *>(strtab_data.GetDataStart()));
6210076e715SGreg Clayton           strtab_data_start[0] = 0;
6220076e715SGreg Clayton 
62328469ca3SGreg Clayton           offset = 0;
62428469ca3SGreg Clayton           std::string symbol_name;
625d5b44036SJonas Devlieghere           Symbol *symbols = m_symtab_up->Resize(num_syms);
626b9c1b51eSKate Stone           for (uint32_t i = 0; i < num_syms; ++i) {
627f754f88fSGreg Clayton             coff_symbol_t symbol;
62828469ca3SGreg Clayton             const uint32_t symbol_offset = offset;
629248a1305SKonrad Kleine             const char *symbol_name_cstr = nullptr;
630c35b91ceSAdrian McCarthy             // If the first 4 bytes of the symbol string are zero, then they
631c35b91ceSAdrian McCarthy             // are followed by a 4-byte string table offset. Else these
63228469ca3SGreg Clayton             // 8 bytes contain the symbol name
633b9c1b51eSKate Stone             if (symtab_data.GetU32(&offset) == 0) {
63405097246SAdrian Prantl               // Long string that doesn't fit into the symbol table name, so
63505097246SAdrian Prantl               // now we must read the 4 byte string table offset
63628469ca3SGreg Clayton               uint32_t strtab_offset = symtab_data.GetU32(&offset);
63728469ca3SGreg Clayton               symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
63828469ca3SGreg Clayton               symbol_name.assign(symbol_name_cstr);
639b9c1b51eSKate Stone             } else {
640b9c1b51eSKate Stone               // Short string that fits into the symbol table name which is 8
641b9c1b51eSKate Stone               // bytes
64228469ca3SGreg Clayton               offset += sizeof(symbol.name) - 4; // Skip remaining
64328469ca3SGreg Clayton               symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
644248a1305SKonrad Kleine               if (symbol_name_cstr == nullptr)
645f754f88fSGreg Clayton                 break;
64628469ca3SGreg Clayton               symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
64728469ca3SGreg Clayton             }
64828469ca3SGreg Clayton             symbol.value = symtab_data.GetU32(&offset);
64928469ca3SGreg Clayton             symbol.sect = symtab_data.GetU16(&offset);
65028469ca3SGreg Clayton             symbol.type = symtab_data.GetU16(&offset);
65128469ca3SGreg Clayton             symbol.storage = symtab_data.GetU8(&offset);
65228469ca3SGreg Clayton             symbol.naux = symtab_data.GetU8(&offset);
653037520e9SGreg Clayton             symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
654b9c1b51eSKate Stone             if ((int16_t)symbol.sect >= 1) {
655b9c1b51eSKate Stone               Address symbol_addr(sect_list->GetSectionAtIndex(symbol.sect - 1),
656b9c1b51eSKate Stone                                   symbol.value);
657358cf1eaSGreg Clayton               symbols[i].GetAddressRef() = symbol_addr;
658c35b91ceSAdrian McCarthy               symbols[i].SetType(MapSymbolType(symbol.type));
6590076e715SGreg Clayton             }
660f754f88fSGreg Clayton 
661b9c1b51eSKate Stone             if (symbol.naux > 0) {
662f754f88fSGreg Clayton               i += symbol.naux;
6630076e715SGreg Clayton               offset += symbol_size;
6640076e715SGreg Clayton             }
665f754f88fSGreg Clayton           }
666f754f88fSGreg Clayton         }
667344546bdSWalter Erquinigo       }
668a4fe3a12SVirgile Bello 
669a4fe3a12SVirgile Bello       // Read export header
670b9c1b51eSKate Stone       if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
671b9c1b51eSKate Stone           m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
672b9c1b51eSKate Stone           m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) {
673a4fe3a12SVirgile Bello         export_directory_entry export_table;
674b9c1b51eSKate Stone         uint32_t data_start =
675b9c1b51eSKate Stone             m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
676344546bdSWalter Erquinigo 
677344546bdSWalter Erquinigo         uint32_t address_rva = data_start;
678344546bdSWalter Erquinigo         if (m_file) {
679a4fe3a12SVirgile Bello           Address address(m_coff_header_opt.image_base + data_start, sect_list);
680344546bdSWalter Erquinigo           address_rva =
681344546bdSWalter Erquinigo               address.GetSection()->GetFileOffset() + address.GetOffset();
682344546bdSWalter Erquinigo         }
683344546bdSWalter Erquinigo         DataExtractor symtab_data =
684344546bdSWalter Erquinigo             ReadImageData(address_rva, m_coff_header_opt.data_dirs[0].vmsize);
685a4fe3a12SVirgile Bello         lldb::offset_t offset = 0;
686a4fe3a12SVirgile Bello 
687a4fe3a12SVirgile Bello         // Read export_table header
688a4fe3a12SVirgile Bello         export_table.characteristics = symtab_data.GetU32(&offset);
689a4fe3a12SVirgile Bello         export_table.time_date_stamp = symtab_data.GetU32(&offset);
690a4fe3a12SVirgile Bello         export_table.major_version = symtab_data.GetU16(&offset);
691a4fe3a12SVirgile Bello         export_table.minor_version = symtab_data.GetU16(&offset);
692a4fe3a12SVirgile Bello         export_table.name = symtab_data.GetU32(&offset);
693a4fe3a12SVirgile Bello         export_table.base = symtab_data.GetU32(&offset);
694a4fe3a12SVirgile Bello         export_table.number_of_functions = symtab_data.GetU32(&offset);
695a4fe3a12SVirgile Bello         export_table.number_of_names = symtab_data.GetU32(&offset);
696a4fe3a12SVirgile Bello         export_table.address_of_functions = symtab_data.GetU32(&offset);
697a4fe3a12SVirgile Bello         export_table.address_of_names = symtab_data.GetU32(&offset);
698a4fe3a12SVirgile Bello         export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
699a4fe3a12SVirgile Bello 
700a4fe3a12SVirgile Bello         bool has_ordinal = export_table.address_of_name_ordinals != 0;
701a4fe3a12SVirgile Bello 
702a4fe3a12SVirgile Bello         lldb::offset_t name_offset = export_table.address_of_names - data_start;
703b9c1b51eSKate Stone         lldb::offset_t name_ordinal_offset =
704b9c1b51eSKate Stone             export_table.address_of_name_ordinals - data_start;
705a4fe3a12SVirgile Bello 
706d5b44036SJonas Devlieghere         Symbol *symbols = m_symtab_up->Resize(export_table.number_of_names);
707a4fe3a12SVirgile Bello 
708a4fe3a12SVirgile Bello         std::string symbol_name;
709a4fe3a12SVirgile Bello 
710a4fe3a12SVirgile Bello         // Read each export table entry
711b9c1b51eSKate Stone         for (size_t i = 0; i < export_table.number_of_names; ++i) {
712b9c1b51eSKate Stone           uint32_t name_ordinal =
713b9c1b51eSKate Stone               has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
714a4fe3a12SVirgile Bello           uint32_t name_address = symtab_data.GetU32(&name_offset);
715a4fe3a12SVirgile Bello 
716b9c1b51eSKate Stone           const char *symbol_name_cstr =
717b9c1b51eSKate Stone               symtab_data.PeekCStr(name_address - data_start);
718a4fe3a12SVirgile Bello           symbol_name.assign(symbol_name_cstr);
719a4fe3a12SVirgile Bello 
720b9c1b51eSKate Stone           lldb::offset_t function_offset = export_table.address_of_functions -
721b9c1b51eSKate Stone                                            data_start +
722b9c1b51eSKate Stone                                            sizeof(uint32_t) * name_ordinal;
723a4fe3a12SVirgile Bello           uint32_t function_rva = symtab_data.GetU32(&function_offset);
724a4fe3a12SVirgile Bello 
725b9c1b51eSKate Stone           Address symbol_addr(m_coff_header_opt.image_base + function_rva,
726b9c1b51eSKate Stone                               sect_list);
727a4fe3a12SVirgile Bello           symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
728358cf1eaSGreg Clayton           symbols[i].GetAddressRef() = symbol_addr;
729a4fe3a12SVirgile Bello           symbols[i].SetType(lldb::eSymbolTypeCode);
730a4fe3a12SVirgile Bello           symbols[i].SetDebug(true);
731a4fe3a12SVirgile Bello         }
732a4fe3a12SVirgile Bello       }
733d5b44036SJonas Devlieghere       m_symtab_up->CalculateSymbolSizes();
734f754f88fSGreg Clayton     }
735a1743499SGreg Clayton   }
736d5b44036SJonas Devlieghere   return m_symtab_up.get();
737f754f88fSGreg Clayton }
738f754f88fSGreg Clayton 
739b9c1b51eSKate Stone bool ObjectFilePECOFF::IsStripped() {
7403046e668SGreg Clayton   // TODO: determine this for COFF
7413046e668SGreg Clayton   return false;
7423046e668SGreg Clayton }
7433046e668SGreg Clayton 
744b9c1b51eSKate Stone void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
745d5b44036SJonas Devlieghere   if (m_sections_up)
74688a2c2a4SPavel Labath     return;
747d5b44036SJonas Devlieghere   m_sections_up.reset(new SectionList());
7483046e668SGreg Clayton 
749a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
750b9c1b51eSKate Stone   if (module_sp) {
75116ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
7527db8b5c4SPavel Labath 
7537db8b5c4SPavel Labath     SectionSP image_sp = std::make_shared<Section>(
7547db8b5c4SPavel Labath         module_sp, this, ~user_id_t(0), ConstString(), eSectionTypeContainer,
7557db8b5c4SPavel Labath         m_coff_header_opt.image_base, m_coff_header_opt.image_size,
7567db8b5c4SPavel Labath         /*file_offset*/ 0, /*file_size*/ 0, m_coff_header_opt.sect_alignment,
7577db8b5c4SPavel Labath         /*flags*/ 0);
7587db8b5c4SPavel Labath     m_sections_up->AddSection(image_sp);
7597db8b5c4SPavel Labath     unified_section_list.AddSection(image_sp);
7607db8b5c4SPavel Labath 
761f754f88fSGreg Clayton     const uint32_t nsects = m_sect_headers.size();
762e72dfb32SGreg Clayton     ModuleSP module_sp(GetModule());
763b9c1b51eSKate Stone     for (uint32_t idx = 0; idx < nsects; ++idx) {
7642886e4a0SPavel Labath       ConstString const_sect_name(GetSectionName(m_sect_headers[idx]));
76528469ca3SGreg Clayton       static ConstString g_code_sect_name(".code");
76628469ca3SGreg Clayton       static ConstString g_CODE_sect_name("CODE");
76728469ca3SGreg Clayton       static ConstString g_data_sect_name(".data");
76828469ca3SGreg Clayton       static ConstString g_DATA_sect_name("DATA");
76928469ca3SGreg Clayton       static ConstString g_bss_sect_name(".bss");
77028469ca3SGreg Clayton       static ConstString g_BSS_sect_name("BSS");
77128469ca3SGreg Clayton       static ConstString g_debug_sect_name(".debug");
77228469ca3SGreg Clayton       static ConstString g_reloc_sect_name(".reloc");
77328469ca3SGreg Clayton       static ConstString g_stab_sect_name(".stab");
77428469ca3SGreg Clayton       static ConstString g_stabstr_sect_name(".stabstr");
7750076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_abbrev(".debug_abbrev");
7760076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_aranges(".debug_aranges");
7770076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_frame(".debug_frame");
7780076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_info(".debug_info");
7790076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_line(".debug_line");
7800076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_loc(".debug_loc");
781e4dee269SGeorge Rimar       static ConstString g_sect_name_dwarf_debug_loclists(".debug_loclists");
7820076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_macinfo(".debug_macinfo");
783a041d848SPavel Labath       static ConstString g_sect_name_dwarf_debug_names(".debug_names");
7840076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_pubnames(".debug_pubnames");
7850076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_pubtypes(".debug_pubtypes");
7860076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_ranges(".debug_ranges");
7870076e715SGreg Clayton       static ConstString g_sect_name_dwarf_debug_str(".debug_str");
7882550ca1eSGreg Clayton       static ConstString g_sect_name_dwarf_debug_types(".debug_types");
7890076e715SGreg Clayton       static ConstString g_sect_name_eh_frame(".eh_frame");
79065d4d5c3SRyan Brown       static ConstString g_sect_name_go_symtab(".gosymtab");
79128469ca3SGreg Clayton       SectionType section_type = eSectionTypeOther;
792237ad974SCharles Davis       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
793b9c1b51eSKate Stone           ((const_sect_name == g_code_sect_name) ||
794b9c1b51eSKate Stone            (const_sect_name == g_CODE_sect_name))) {
79528469ca3SGreg Clayton         section_type = eSectionTypeCode;
796b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
797b9c1b51eSKate Stone                      llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
798b9c1b51eSKate Stone                  ((const_sect_name == g_data_sect_name) ||
799b9c1b51eSKate Stone                   (const_sect_name == g_DATA_sect_name))) {
8009cad24a7SZachary Turner         if (m_sect_headers[idx].size == 0 && m_sect_headers[idx].offset == 0)
8019cad24a7SZachary Turner           section_type = eSectionTypeZeroFill;
8029cad24a7SZachary Turner         else
80328469ca3SGreg Clayton           section_type = eSectionTypeData;
804b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
805b9c1b51eSKate Stone                      llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
806b9c1b51eSKate Stone                  ((const_sect_name == g_bss_sect_name) ||
807b9c1b51eSKate Stone                   (const_sect_name == g_BSS_sect_name))) {
80828469ca3SGreg Clayton         if (m_sect_headers[idx].size == 0)
80928469ca3SGreg Clayton           section_type = eSectionTypeZeroFill;
81028469ca3SGreg Clayton         else
81128469ca3SGreg Clayton           section_type = eSectionTypeData;
812b9c1b51eSKate Stone       } else if (const_sect_name == g_debug_sect_name) {
81328469ca3SGreg Clayton         section_type = eSectionTypeDebug;
814b9c1b51eSKate Stone       } else if (const_sect_name == g_stabstr_sect_name) {
81528469ca3SGreg Clayton         section_type = eSectionTypeDataCString;
816b9c1b51eSKate Stone       } else if (const_sect_name == g_reloc_sect_name) {
81728469ca3SGreg Clayton         section_type = eSectionTypeOther;
818b9c1b51eSKate Stone       } else if (const_sect_name == g_sect_name_dwarf_debug_abbrev)
819b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugAbbrev;
820b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_aranges)
821b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugAranges;
822b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_frame)
823b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugFrame;
824b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_info)
825b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugInfo;
826b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_line)
827b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugLine;
828b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_loc)
829b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugLoc;
830e4dee269SGeorge Rimar       else if (const_sect_name == g_sect_name_dwarf_debug_loclists)
831e4dee269SGeorge Rimar         section_type = eSectionTypeDWARFDebugLocLists;
832b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_macinfo)
833b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugMacInfo;
834a041d848SPavel Labath       else if (const_sect_name == g_sect_name_dwarf_debug_names)
835a041d848SPavel Labath         section_type = eSectionTypeDWARFDebugNames;
836b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_pubnames)
837b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugPubNames;
838b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_pubtypes)
839b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugPubTypes;
840b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_ranges)
841b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugRanges;
842b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_dwarf_debug_str)
843b9c1b51eSKate Stone         section_type = eSectionTypeDWARFDebugStr;
8442550ca1eSGreg Clayton       else if (const_sect_name == g_sect_name_dwarf_debug_types)
8452550ca1eSGreg Clayton         section_type = eSectionTypeDWARFDebugTypes;
846b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_eh_frame)
847b9c1b51eSKate Stone         section_type = eSectionTypeEHFrame;
848b9c1b51eSKate Stone       else if (const_sect_name == g_sect_name_go_symtab)
849b9c1b51eSKate Stone         section_type = eSectionTypeGoSymtab;
850b9c1b51eSKate Stone       else if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_CNT_CODE) {
85128469ca3SGreg Clayton         section_type = eSectionTypeCode;
852b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
853b9c1b51eSKate Stone                  llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) {
85428469ca3SGreg Clayton         section_type = eSectionTypeData;
855b9c1b51eSKate Stone       } else if (m_sect_headers[idx].flags &
856b9c1b51eSKate Stone                  llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
85728469ca3SGreg Clayton         if (m_sect_headers[idx].size == 0)
85828469ca3SGreg Clayton           section_type = eSectionTypeZeroFill;
85928469ca3SGreg Clayton         else
86028469ca3SGreg Clayton           section_type = eSectionTypeData;
86128469ca3SGreg Clayton       }
862f754f88fSGreg Clayton 
863b9c1b51eSKate Stone       SectionSP section_sp(new Section(
8647db8b5c4SPavel Labath           image_sp,        // Parent section
865b9c1b51eSKate Stone           module_sp,       // Module to which this section belongs
866a7499c98SMichael Sartain           this,            // Object file to which this section belongs
8677db8b5c4SPavel Labath           idx + 1,         // Section ID is the 1 based section index.
868f754f88fSGreg Clayton           const_sect_name, // Name of this section
8697db8b5c4SPavel Labath           section_type,
870b9c1b51eSKate Stone           m_sect_headers[idx].vmaddr, // File VM address == addresses as
871b9c1b51eSKate Stone                                       // they are found in the object file
872f754f88fSGreg Clayton           m_sect_headers[idx].vmsize, // VM size in bytes of this section
873b9c1b51eSKate Stone           m_sect_headers[idx]
874b9c1b51eSKate Stone               .offset, // Offset to the data for this section in the file
875b9c1b51eSKate Stone           m_sect_headers[idx]
876b9c1b51eSKate Stone               .size, // Size in bytes of this section as found in the file
87748672afbSGreg Clayton           m_coff_header_opt.sect_alignment, // Section alignment
878f754f88fSGreg Clayton           m_sect_headers[idx].flags));      // Flags for this section
879f754f88fSGreg Clayton 
8807db8b5c4SPavel Labath       image_sp->GetChildren().AddSection(std::move(section_sp));
881f754f88fSGreg Clayton     }
882f754f88fSGreg Clayton   }
883a1743499SGreg Clayton }
884f754f88fSGreg Clayton 
885b8d03935SAaron Smith UUID ObjectFilePECOFF::GetUUID() {
886b8d03935SAaron Smith   if (m_uuid.IsValid())
887b8d03935SAaron Smith     return m_uuid;
888b8d03935SAaron Smith 
889b8d03935SAaron Smith   if (!CreateBinary())
890b8d03935SAaron Smith     return UUID();
891b8d03935SAaron Smith 
892b8d03935SAaron Smith   auto COFFObj =
893b8d03935SAaron Smith     llvm::cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary());
894b8d03935SAaron Smith 
895b8d03935SAaron Smith   m_uuid = GetCoffUUID(COFFObj);
896b8d03935SAaron Smith   return m_uuid;
897b8d03935SAaron Smith }
898f754f88fSGreg Clayton 
899037ed1beSAaron Smith uint32_t ObjectFilePECOFF::ParseDependentModules() {
900037ed1beSAaron Smith   ModuleSP module_sp(GetModule());
901037ed1beSAaron Smith   if (!module_sp)
902f754f88fSGreg Clayton     return 0;
903037ed1beSAaron Smith 
904037ed1beSAaron Smith   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
905037ed1beSAaron Smith   if (m_deps_filespec)
906037ed1beSAaron Smith     return m_deps_filespec->GetSize();
907037ed1beSAaron Smith 
908037ed1beSAaron Smith   // Cache coff binary if it is not done yet.
909037ed1beSAaron Smith   if (!CreateBinary())
910037ed1beSAaron Smith     return 0;
911037ed1beSAaron Smith 
912037ed1beSAaron Smith   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
913*63e5fb76SJonas Devlieghere   LLDB_LOGF(log,
914*63e5fb76SJonas Devlieghere             "%p ObjectFilePECOFF::ParseDependentModules() module = %p "
915037ed1beSAaron Smith             "(%s), binary = %p (Bin = %p)",
916037ed1beSAaron Smith             static_cast<void *>(this), static_cast<void *>(module_sp.get()),
917037ed1beSAaron Smith             module_sp->GetSpecificationDescription().c_str(),
918037ed1beSAaron Smith             static_cast<void *>(m_owningbin.getPointer()),
919b8d03935SAaron Smith             static_cast<void *>(m_owningbin->getBinary()));
920037ed1beSAaron Smith 
921037ed1beSAaron Smith   auto COFFObj =
922037ed1beSAaron Smith       llvm::dyn_cast<llvm::object::COFFObjectFile>(m_owningbin->getBinary());
923037ed1beSAaron Smith   if (!COFFObj)
924037ed1beSAaron Smith     return 0;
925037ed1beSAaron Smith 
926037ed1beSAaron Smith   m_deps_filespec = FileSpecList();
927037ed1beSAaron Smith 
928037ed1beSAaron Smith   for (const auto &entry : COFFObj->import_directories()) {
929037ed1beSAaron Smith     llvm::StringRef dll_name;
930037ed1beSAaron Smith     auto ec = entry.getName(dll_name);
931037ed1beSAaron Smith     // Report a bogus entry.
932037ed1beSAaron Smith     if (ec != std::error_code()) {
933*63e5fb76SJonas Devlieghere       LLDB_LOGF(log,
934*63e5fb76SJonas Devlieghere                 "ObjectFilePECOFF::ParseDependentModules() - failed to get "
935037ed1beSAaron Smith                 "import directory entry name: %s",
936037ed1beSAaron Smith                 ec.message().c_str());
937037ed1beSAaron Smith       continue;
938037ed1beSAaron Smith     }
939037ed1beSAaron Smith 
940037ed1beSAaron Smith     // At this moment we only have the base name of the DLL. The full path can
941037ed1beSAaron Smith     // only be seen after the dynamic loading.  Our best guess is Try to get it
942037ed1beSAaron Smith     // with the help of the object file's directory.
943b3f44ad9SStella Stamenova     llvm::SmallString<128> dll_fullpath;
944037ed1beSAaron Smith     FileSpec dll_specs(dll_name);
945037ed1beSAaron Smith     dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
946037ed1beSAaron Smith 
947037ed1beSAaron Smith     if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
948f893d5bfSJonas Devlieghere       m_deps_filespec->EmplaceBack(dll_fullpath);
949037ed1beSAaron Smith     else {
950037ed1beSAaron Smith       // Known DLLs or DLL not found in the object file directory.
951f893d5bfSJonas Devlieghere       m_deps_filespec->EmplaceBack(dll_name);
952037ed1beSAaron Smith     }
953037ed1beSAaron Smith   }
954037ed1beSAaron Smith   return m_deps_filespec->GetSize();
955037ed1beSAaron Smith }
956037ed1beSAaron Smith 
957037ed1beSAaron Smith uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
958037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
959037ed1beSAaron Smith   auto original_size = files.GetSize();
960037ed1beSAaron Smith 
961037ed1beSAaron Smith   for (unsigned i = 0; i < num_modules; ++i)
962037ed1beSAaron Smith     files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
963037ed1beSAaron Smith 
964037ed1beSAaron Smith   return files.GetSize() - original_size;
965f754f88fSGreg Clayton }
966f754f88fSGreg Clayton 
967b9c1b51eSKate Stone lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
9688e38c666SStephane Sezer   if (m_entry_point_address.IsValid())
9698e38c666SStephane Sezer     return m_entry_point_address;
9708e38c666SStephane Sezer 
9718e38c666SStephane Sezer   if (!ParseHeader() || !IsExecutable())
9728e38c666SStephane Sezer     return m_entry_point_address;
9738e38c666SStephane Sezer 
9748e38c666SStephane Sezer   SectionList *section_list = GetSectionList();
975a5235af9SAleksandr Urakov   addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
9768e38c666SStephane Sezer 
9778e38c666SStephane Sezer   if (!section_list)
978a5235af9SAleksandr Urakov     m_entry_point_address.SetOffset(file_addr);
9798e38c666SStephane Sezer   else
980b8d03935SAaron Smith     m_entry_point_address.ResolveAddressUsingFileSections(file_addr,
981b8d03935SAaron Smith                                                           section_list);
9828e38c666SStephane Sezer   return m_entry_point_address;
9838e38c666SStephane Sezer }
9848e38c666SStephane Sezer 
985d1304bbaSPavel Labath Address ObjectFilePECOFF::GetBaseAddress() {
986d1304bbaSPavel Labath   return Address(GetSectionList()->GetSectionAtIndex(0), 0);
987d1304bbaSPavel Labath }
988d1304bbaSPavel Labath 
989f754f88fSGreg Clayton // Dump
990f754f88fSGreg Clayton //
991f754f88fSGreg Clayton // Dump the specifics of the runtime file container (such as any headers
992f754f88fSGreg Clayton // segments, sections, etc).
993b9c1b51eSKate Stone void ObjectFilePECOFF::Dump(Stream *s) {
994a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
995b9c1b51eSKate Stone   if (module_sp) {
99616ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
997324a1036SSaleem Abdulrasool     s->Printf("%p: ", static_cast<void *>(this));
998f754f88fSGreg Clayton     s->Indent();
999f754f88fSGreg Clayton     s->PutCString("ObjectFilePECOFF");
1000f754f88fSGreg Clayton 
1001f760f5aeSPavel Labath     ArchSpec header_arch = GetArchitecture();
1002f754f88fSGreg Clayton 
1003b9c1b51eSKate Stone     *s << ", file = '" << m_file
1004b9c1b51eSKate Stone        << "', arch = " << header_arch.GetArchitectureName() << "\n";
1005f754f88fSGreg Clayton 
10063046e668SGreg Clayton     SectionList *sections = GetSectionList();
10073046e668SGreg Clayton     if (sections)
1008248a1305SKonrad Kleine       sections->Dump(s, nullptr, true, UINT32_MAX);
1009f754f88fSGreg Clayton 
1010d5b44036SJonas Devlieghere     if (m_symtab_up)
1011248a1305SKonrad Kleine       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
1012f754f88fSGreg Clayton 
1013f754f88fSGreg Clayton     if (m_dos_header.e_magic)
1014f754f88fSGreg Clayton       DumpDOSHeader(s, m_dos_header);
1015b9c1b51eSKate Stone     if (m_coff_header.machine) {
1016f754f88fSGreg Clayton       DumpCOFFHeader(s, m_coff_header);
1017f754f88fSGreg Clayton       if (m_coff_header.hdrsize)
1018f754f88fSGreg Clayton         DumpOptCOFFHeader(s, m_coff_header_opt);
1019f754f88fSGreg Clayton     }
1020f754f88fSGreg Clayton     s->EOL();
1021f754f88fSGreg Clayton     DumpSectionHeaders(s);
1022f754f88fSGreg Clayton     s->EOL();
1023037ed1beSAaron Smith 
1024037ed1beSAaron Smith     DumpDependentModules(s);
1025037ed1beSAaron Smith     s->EOL();
1026f754f88fSGreg Clayton   }
1027a1743499SGreg Clayton }
1028f754f88fSGreg Clayton 
1029f754f88fSGreg Clayton // DumpDOSHeader
1030f754f88fSGreg Clayton //
1031f754f88fSGreg Clayton // Dump the MS-DOS header to the specified output stream
1032b9c1b51eSKate Stone void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
1033f754f88fSGreg Clayton   s->PutCString("MSDOS Header\n");
1034f754f88fSGreg Clayton   s->Printf("  e_magic    = 0x%4.4x\n", header.e_magic);
1035f754f88fSGreg Clayton   s->Printf("  e_cblp     = 0x%4.4x\n", header.e_cblp);
1036f754f88fSGreg Clayton   s->Printf("  e_cp       = 0x%4.4x\n", header.e_cp);
1037f754f88fSGreg Clayton   s->Printf("  e_crlc     = 0x%4.4x\n", header.e_crlc);
1038f754f88fSGreg Clayton   s->Printf("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
1039f754f88fSGreg Clayton   s->Printf("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
1040f754f88fSGreg Clayton   s->Printf("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1041f754f88fSGreg Clayton   s->Printf("  e_ss       = 0x%4.4x\n", header.e_ss);
1042f754f88fSGreg Clayton   s->Printf("  e_sp       = 0x%4.4x\n", header.e_sp);
1043f754f88fSGreg Clayton   s->Printf("  e_csum     = 0x%4.4x\n", header.e_csum);
1044f754f88fSGreg Clayton   s->Printf("  e_ip       = 0x%4.4x\n", header.e_ip);
1045f754f88fSGreg Clayton   s->Printf("  e_cs       = 0x%4.4x\n", header.e_cs);
1046f754f88fSGreg Clayton   s->Printf("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
1047f754f88fSGreg Clayton   s->Printf("  e_ovno     = 0x%4.4x\n", header.e_ovno);
1048f754f88fSGreg Clayton   s->Printf("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1049b9c1b51eSKate Stone             header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1050f754f88fSGreg Clayton   s->Printf("  e_oemid    = 0x%4.4x\n", header.e_oemid);
1051f754f88fSGreg Clayton   s->Printf("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
1052b9c1b51eSKate Stone   s->Printf("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1053b9c1b51eSKate Stone             "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1054b9c1b51eSKate Stone             header.e_res2[0], header.e_res2[1], header.e_res2[2],
1055b9c1b51eSKate Stone             header.e_res2[3], header.e_res2[4], header.e_res2[5],
1056b9c1b51eSKate Stone             header.e_res2[6], header.e_res2[7], header.e_res2[8],
1057f754f88fSGreg Clayton             header.e_res2[9]);
1058f754f88fSGreg Clayton   s->Printf("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
1059f754f88fSGreg Clayton }
1060f754f88fSGreg Clayton 
1061f754f88fSGreg Clayton // DumpCOFFHeader
1062f754f88fSGreg Clayton //
1063f754f88fSGreg Clayton // Dump the COFF header to the specified output stream
1064b9c1b51eSKate Stone void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1065f754f88fSGreg Clayton   s->PutCString("COFF Header\n");
1066f754f88fSGreg Clayton   s->Printf("  machine = 0x%4.4x\n", header.machine);
1067f754f88fSGreg Clayton   s->Printf("  nsects  = 0x%4.4x\n", header.nsects);
1068f754f88fSGreg Clayton   s->Printf("  modtime = 0x%8.8x\n", header.modtime);
1069f754f88fSGreg Clayton   s->Printf("  symoff  = 0x%8.8x\n", header.symoff);
1070f754f88fSGreg Clayton   s->Printf("  nsyms   = 0x%8.8x\n", header.nsyms);
1071f754f88fSGreg Clayton   s->Printf("  hdrsize = 0x%4.4x\n", header.hdrsize);
1072f754f88fSGreg Clayton }
1073f754f88fSGreg Clayton 
1074f754f88fSGreg Clayton // DumpOptCOFFHeader
1075f754f88fSGreg Clayton //
1076f754f88fSGreg Clayton // Dump the optional COFF header to the specified output stream
1077b9c1b51eSKate Stone void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1078b9c1b51eSKate Stone                                          const coff_opt_header_t &header) {
1079f754f88fSGreg Clayton   s->PutCString("Optional COFF Header\n");
1080f754f88fSGreg Clayton   s->Printf("  magic                   = 0x%4.4x\n", header.magic);
1081b9c1b51eSKate Stone   s->Printf("  major_linker_version    = 0x%2.2x\n",
1082b9c1b51eSKate Stone             header.major_linker_version);
1083b9c1b51eSKate Stone   s->Printf("  minor_linker_version    = 0x%2.2x\n",
1084b9c1b51eSKate Stone             header.minor_linker_version);
1085f754f88fSGreg Clayton   s->Printf("  code_size               = 0x%8.8x\n", header.code_size);
1086f754f88fSGreg Clayton   s->Printf("  data_size               = 0x%8.8x\n", header.data_size);
1087f754f88fSGreg Clayton   s->Printf("  bss_size                = 0x%8.8x\n", header.bss_size);
1088f754f88fSGreg Clayton   s->Printf("  entry                   = 0x%8.8x\n", header.entry);
1089f754f88fSGreg Clayton   s->Printf("  code_offset             = 0x%8.8x\n", header.code_offset);
1090f754f88fSGreg Clayton   s->Printf("  data_offset             = 0x%8.8x\n", header.data_offset);
1091b9c1b51eSKate Stone   s->Printf("  image_base              = 0x%16.16" PRIx64 "\n",
1092b9c1b51eSKate Stone             header.image_base);
1093f754f88fSGreg Clayton   s->Printf("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
1094f754f88fSGreg Clayton   s->Printf("  file_alignment          = 0x%8.8x\n", header.file_alignment);
1095b9c1b51eSKate Stone   s->Printf("  major_os_system_version = 0x%4.4x\n",
1096b9c1b51eSKate Stone             header.major_os_system_version);
1097b9c1b51eSKate Stone   s->Printf("  minor_os_system_version = 0x%4.4x\n",
1098b9c1b51eSKate Stone             header.minor_os_system_version);
1099b9c1b51eSKate Stone   s->Printf("  major_image_version     = 0x%4.4x\n",
1100b9c1b51eSKate Stone             header.major_image_version);
1101b9c1b51eSKate Stone   s->Printf("  minor_image_version     = 0x%4.4x\n",
1102b9c1b51eSKate Stone             header.minor_image_version);
1103b9c1b51eSKate Stone   s->Printf("  major_subsystem_version = 0x%4.4x\n",
1104b9c1b51eSKate Stone             header.major_subsystem_version);
1105b9c1b51eSKate Stone   s->Printf("  minor_subsystem_version = 0x%4.4x\n",
1106b9c1b51eSKate Stone             header.minor_subsystem_version);
1107f754f88fSGreg Clayton   s->Printf("  reserved1               = 0x%8.8x\n", header.reserved1);
1108f754f88fSGreg Clayton   s->Printf("  image_size              = 0x%8.8x\n", header.image_size);
1109f754f88fSGreg Clayton   s->Printf("  header_size             = 0x%8.8x\n", header.header_size);
111028469ca3SGreg Clayton   s->Printf("  checksum                = 0x%8.8x\n", header.checksum);
1111f754f88fSGreg Clayton   s->Printf("  subsystem               = 0x%4.4x\n", header.subsystem);
1112f754f88fSGreg Clayton   s->Printf("  dll_flags               = 0x%4.4x\n", header.dll_flags);
1113b9c1b51eSKate Stone   s->Printf("  stack_reserve_size      = 0x%16.16" PRIx64 "\n",
1114b9c1b51eSKate Stone             header.stack_reserve_size);
1115b9c1b51eSKate Stone   s->Printf("  stack_commit_size       = 0x%16.16" PRIx64 "\n",
1116b9c1b51eSKate Stone             header.stack_commit_size);
1117b9c1b51eSKate Stone   s->Printf("  heap_reserve_size       = 0x%16.16" PRIx64 "\n",
1118b9c1b51eSKate Stone             header.heap_reserve_size);
1119b9c1b51eSKate Stone   s->Printf("  heap_commit_size        = 0x%16.16" PRIx64 "\n",
1120b9c1b51eSKate Stone             header.heap_commit_size);
1121f754f88fSGreg Clayton   s->Printf("  loader_flags            = 0x%8.8x\n", header.loader_flags);
1122b9c1b51eSKate Stone   s->Printf("  num_data_dir_entries    = 0x%8.8x\n",
1123b9c1b51eSKate Stone             (uint32_t)header.data_dirs.size());
1124f754f88fSGreg Clayton   uint32_t i;
1125b9c1b51eSKate Stone   for (i = 0; i < header.data_dirs.size(); i++) {
1126b9c1b51eSKate Stone     s->Printf("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1127b9c1b51eSKate Stone               header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1128f754f88fSGreg Clayton   }
1129f754f88fSGreg Clayton }
1130f754f88fSGreg Clayton // DumpSectionHeader
1131f754f88fSGreg Clayton //
1132f754f88fSGreg Clayton // Dump a single ELF section header to the specified output stream
1133b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1134b9c1b51eSKate Stone                                          const section_header_t &sh) {
11352886e4a0SPavel Labath   std::string name = GetSectionName(sh);
1136b9c1b51eSKate 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 "
1137b9c1b51eSKate Stone             "0x%4.4x 0x%8.8x\n",
1138b9c1b51eSKate Stone             name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1139b9c1b51eSKate Stone             sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1140f754f88fSGreg Clayton }
1141f754f88fSGreg Clayton 
1142f754f88fSGreg Clayton // DumpSectionHeaders
1143f754f88fSGreg Clayton //
1144f754f88fSGreg Clayton // Dump all of the ELF section header to the specified output stream
1145b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1146f754f88fSGreg Clayton 
1147f754f88fSGreg Clayton   s->PutCString("Section Headers\n");
1148b9c1b51eSKate Stone   s->PutCString("IDX  name             vm addr    vm size    file off   file "
1149b9c1b51eSKate Stone                 "size  reloc off  line off   nreloc nline  flags\n");
1150b9c1b51eSKate Stone   s->PutCString("==== ---------------- ---------- ---------- ---------- "
1151b9c1b51eSKate Stone                 "---------- ---------- ---------- ------ ------ ----------\n");
1152f754f88fSGreg Clayton 
1153f754f88fSGreg Clayton   uint32_t idx = 0;
1154f754f88fSGreg Clayton   SectionHeaderCollIter pos, end = m_sect_headers.end();
1155f754f88fSGreg Clayton 
1156b9c1b51eSKate Stone   for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1157f754f88fSGreg Clayton     s->Printf("[%2u] ", idx);
1158f754f88fSGreg Clayton     ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1159f754f88fSGreg Clayton   }
1160f754f88fSGreg Clayton }
1161f754f88fSGreg Clayton 
1162037ed1beSAaron Smith // DumpDependentModules
1163037ed1beSAaron Smith //
1164037ed1beSAaron Smith // Dump all of the dependent modules to the specified output stream
1165037ed1beSAaron Smith void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1166037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
1167037ed1beSAaron Smith   if (num_modules > 0) {
1168037ed1beSAaron Smith     s->PutCString("Dependent Modules\n");
1169037ed1beSAaron Smith     for (unsigned i = 0; i < num_modules; ++i) {
1170037ed1beSAaron Smith       auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1171037ed1beSAaron Smith       s->Printf("  %s\n", spec.GetFilename().GetCString());
1172037ed1beSAaron Smith     }
1173037ed1beSAaron Smith   }
1174037ed1beSAaron Smith }
1175037ed1beSAaron Smith 
1176fb3b3bd1SZachary Turner bool ObjectFilePECOFF::IsWindowsSubsystem() {
1177fb3b3bd1SZachary Turner   switch (m_coff_header_opt.subsystem) {
1178fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1179fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1180fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1181fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1182fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1183fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1184fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1185fb3b3bd1SZachary Turner     return true;
1186fb3b3bd1SZachary Turner   default:
1187fb3b3bd1SZachary Turner     return false;
1188fb3b3bd1SZachary Turner   }
1189fb3b3bd1SZachary Turner }
1190fb3b3bd1SZachary Turner 
1191f760f5aeSPavel Labath ArchSpec ObjectFilePECOFF::GetArchitecture() {
1192237ad974SCharles Davis   uint16_t machine = m_coff_header.machine;
1193b9c1b51eSKate Stone   switch (machine) {
1194f760f5aeSPavel Labath   default:
1195f760f5aeSPavel Labath     break;
1196237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1197237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1198237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1199237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1200237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
12011108cb36SSaleem Abdulrasool   case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1202237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1203f760f5aeSPavel Labath     ArchSpec arch;
1204fb3b3bd1SZachary Turner     arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1205fb3b3bd1SZachary Turner                          IsWindowsSubsystem() ? llvm::Triple::Win32
1206fb3b3bd1SZachary Turner                                               : llvm::Triple::UnknownOS);
1207f760f5aeSPavel Labath     return arch;
1208237ad974SCharles Davis   }
1209f760f5aeSPavel Labath   return ArchSpec();
1210f754f88fSGreg Clayton }
1211f754f88fSGreg Clayton 
1212b9c1b51eSKate Stone ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1213b9c1b51eSKate Stone   if (m_coff_header.machine != 0) {
1214237ad974SCharles Davis     if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1215f754f88fSGreg Clayton       return eTypeExecutable;
1216f754f88fSGreg Clayton     else
1217f754f88fSGreg Clayton       return eTypeSharedLibrary;
1218f754f88fSGreg Clayton   }
1219f754f88fSGreg Clayton   return eTypeExecutable;
1220f754f88fSGreg Clayton }
1221f754f88fSGreg Clayton 
1222b9c1b51eSKate Stone ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }
12239cad24a7SZachary Turner 
1224f754f88fSGreg Clayton // PluginInterface protocol
1225b9c1b51eSKate Stone ConstString ObjectFilePECOFF::GetPluginName() { return GetPluginNameStatic(); }
1226f754f88fSGreg Clayton 
1227b9c1b51eSKate Stone uint32_t ObjectFilePECOFF::GetPluginVersion() { return 1; }
1228